From 393f2399b2bb7ddc698e87969d3e60481e6998ea Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 19 Oct 2022 21:25:33 -0700 Subject: [PATCH 1/2] Remove Map, Set, etc --- src/.eslintrc.json | 7 +- src/cancellationToken/tsconfig.json | 3 - src/compiler/binder.ts | 12 +- src/compiler/builder.ts | 24 +- src/compiler/builderState.ts | 18 +- src/compiler/checker.ts | 946 +++++++++--------- src/compiler/commandLineParser.ts | 58 +- src/compiler/core.ts | 74 +- src/compiler/corePublic.ts | 100 -- src/compiler/debug.ts | 4 +- src/compiler/emitter.ts | 34 +- src/compiler/factory/emitHelpers.ts | 4 +- src/compiler/factory/nodeFactory.ts | 2 +- src/compiler/factory/parenthesizerRules.ts | 8 +- src/compiler/moduleNameResolver.ts | 42 +- src/compiler/moduleSpecifiers.ts | 16 +- src/compiler/parser.ts | 10 +- src/compiler/performance.ts | 2 +- src/compiler/program.ts | 28 +- src/compiler/resolutionCache.ts | 22 +- src/compiler/scanner.ts | 6 +- src/compiler/sourcemap.ts | 6 +- src/compiler/sys.ts | 8 +- src/compiler/tracing.ts | 2 +- src/compiler/transformers/classFields.ts | 6 +- src/compiler/transformers/declarations.ts | 16 +- src/compiler/transformers/es2015.ts | 12 +- src/compiler/transformers/es2017.ts | 6 +- src/compiler/transformers/es2018.ts | 82 +- src/compiler/transformers/generators.ts | 6 +- src/compiler/transformers/jsx.ts | 4 +- .../transformers/module/esnextAnd2015.ts | 6 +- src/compiler/transformers/module/system.ts | 2 +- src/compiler/transformers/ts.ts | 2 +- src/compiler/transformers/utilities.ts | 8 +- src/compiler/tsbuildPublic.ts | 56 +- src/compiler/types.ts | 60 +- src/compiler/utilities.ts | 32 +- src/compiler/watch.ts | 18 +- src/compiler/watchPublic.ts | 16 +- src/compiler/watchUtilities.ts | 20 +- .../4.0/renamedMapInterfaces.ts | 24 - src/deprecatedCompat/_namespaces/ts.ts | 1 - src/executeCommandLine/executeCommandLine.ts | 16 +- src/harness/client.ts | 4 +- src/harness/evaluatorImpl.ts | 2 +- src/harness/fourslashImpl.ts | 26 +- src/harness/fourslashInterfaceImpl.ts | 2 +- src/harness/harnessIO.ts | 24 +- src/harness/harnessLanguageService.ts | 4 +- src/harness/harnessUtils.ts | 2 +- src/harness/sourceMapRecorder.ts | 2 +- src/harness/tsconfig.json | 4 - src/harness/virtualFileSystemWithWatch.ts | 40 +- src/jsTyping/jsTyping.ts | 12 +- src/jsTyping/tsconfig.json | 4 - src/loggedIO/loggedIO.ts | 4 +- src/loggedIO/tsconfig.json | 4 - src/server/editorServices.ts | 42 +- src/server/moduleSpecifierCache.ts | 6 +- src/server/packageJsonCache.ts | 2 +- src/server/project.ts | 46 +- src/server/scriptInfo.ts | 2 +- src/server/session.ts | 8 +- src/server/typingsCache.ts | 2 +- src/server/utilities.ts | 2 +- src/server/utilitiesPublic.ts | 2 +- src/services/classifier.ts | 2 +- src/services/classifier2020.ts | 2 +- src/services/codeFixProvider.ts | 2 +- src/services/codefixes/addMissingAsync.ts | 2 +- src/services/codefixes/addMissingAwait.ts | 2 +- src/services/codefixes/addMissingConst.ts | 2 +- .../codefixes/addMissingDeclareProperty.ts | 2 +- src/services/codefixes/convertConstToLet.ts | 2 +- .../codefixes/convertToAsyncFunction.ts | 14 +- src/services/codefixes/convertToEsModule.ts | 40 +- .../codefixes/convertToTypeOnlyExport.ts | 2 +- .../codefixes/disableJsDiagnostics.ts | 2 +- .../codefixes/fixAddMissingConstraint.ts | 2 +- src/services/codefixes/fixAddMissingMember.ts | 4 +- src/services/codefixes/fixAddVoidToPromise.ts | 4 +- .../codefixes/fixAwaitInSyncFunction.ts | 2 +- ...sDoesntImplementInheritedAbstractMember.ts | 2 +- .../fixClassIncorrectlyImplementsInterface.ts | 2 +- .../fixClassSuperMustPrecedeThisAccess.ts | 2 +- .../codefixes/fixImportNonExportedMember.ts | 2 +- .../codefixes/fixUnmatchedParameter.ts | 2 +- src/services/codefixes/helpers.ts | 4 +- src/services/codefixes/importFixes.ts | 12 +- src/services/codefixes/inferFromUsage.ts | 2 +- src/services/completions.ts | 4 +- src/services/documentHighlights.ts | 2 +- src/services/documentRegistry.ts | 8 +- src/services/exportInfoMap.ts | 2 +- src/services/findAllReferences.ts | 10 +- src/services/importTracker.ts | 10 +- src/services/navigationBar.ts | 8 +- src/services/patternMatcher.ts | 12 +- src/services/refactorProvider.ts | 2 +- src/services/refactors/convertImport.ts | 4 +- src/services/refactors/extractSymbol.ts | 18 +- src/services/refactors/extractType.ts | 2 +- src/services/refactors/moveToNewFile.ts | 2 +- src/services/services.ts | 16 +- src/services/shims.ts | 8 +- src/services/sourcemaps.ts | 2 +- src/services/stringCompletions.ts | 4 +- src/services/suggestionDiagnostics.ts | 2 +- src/services/symbolDisplay.ts | 2 +- src/services/textChanges.ts | 4 +- src/services/transpile.ts | 2 +- src/services/types.ts | 22 +- src/services/utilities.ts | 2 +- src/testRunner/parallel/host.ts | 2 +- src/testRunner/parallel/worker.ts | 11 +- src/testRunner/rwcRunner.ts | 2 +- src/testRunner/tsconfig.json | 4 - .../unittests/config/commandLineParsing.ts | 4 +- .../unittests/config/projectReferences.ts | 2 +- src/testRunner/unittests/customTransforms.ts | 2 +- src/testRunner/unittests/helpers.ts | 8 +- src/testRunner/unittests/moduleResolution.ts | 34 +- src/testRunner/unittests/programApi.ts | 2 +- src/testRunner/unittests/publicApi.ts | 1 + .../unittests/reuseProgramStructure.ts | 12 +- .../unittests/services/extract/helpers.ts | 4 +- .../unittests/services/languageService.ts | 2 +- src/testRunner/unittests/tsbuild/helpers.ts | 4 +- src/testRunner/unittests/tsbuild/publicApi.ts | 2 +- src/testRunner/unittests/tsc/helpers.ts | 4 +- src/testRunner/unittests/tscWatch/watchApi.ts | 2 +- .../unittests/tscWatch/watchEnvironment.ts | 6 +- .../events/projectUpdatedInBackground.ts | 2 +- src/testRunner/unittests/tsserver/helpers.ts | 6 +- .../unittests/tsserver/inferredProjects.ts | 4 +- src/testRunner/unittests/tsserver/session.ts | 2 +- .../unittests/tsserver/typingsInstaller.ts | 20 +- .../unittests/tsserver/watchEnvironment.ts | 4 +- src/tsserver/nodeServer.ts | 6 +- src/typingsInstaller/nodeTypingsInstaller.ts | 6 +- src/typingsInstaller/tsconfig.json | 4 - src/typingsInstallerCore/tsconfig.json | 4 - src/typingsInstallerCore/typingsInstaller.ts | 10 +- src/watchGuard/tsconfig.json | 3 - .../reference/api/tsserverlibrary.d.ts | 79 +- tests/baselines/reference/api/typescript.d.ts | 71 +- tests/cases/compiler/APILibCheck.ts | 2 +- 148 files changed, 1201 insertions(+), 1467 deletions(-) delete mode 100644 src/deprecatedCompat/4.0/renamedMapInterfaces.ts diff --git a/src/.eslintrc.json b/src/.eslintrc.json index f29dc06406312..5d8be27666239 100644 --- a/src/.eslintrc.json +++ b/src/.eslintrc.json @@ -14,12 +14,7 @@ { "name": "clearInterval" }, { "name": "setImmediate" }, { "name": "clearImmediate" }, - { "name": "performance" }, - { "name": "Iterator" }, - { "name": "Map" }, - { "name": "ReadonlyMap" }, - { "name": "Set" }, - { "name": "ReadonlySet" } + { "name": "performance" } ] }, "overrides": [ diff --git a/src/cancellationToken/tsconfig.json b/src/cancellationToken/tsconfig.json index 9249fae5d1795..f5c0994d7c0fe 100644 --- a/src/cancellationToken/tsconfig.json +++ b/src/cancellationToken/tsconfig.json @@ -4,9 +4,6 @@ "module": "commonjs", "types": [ "node" - ], - "lib": [ - "es6" ] }, "include": ["**/*"] diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index ca6d9526fde1b..21b796d43609a 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -9,7 +9,7 @@ import { createSymbolTable, Debug, Declaration, declarationNameToString, DeleteExpression, DestructuringAssignment, DiagnosticCategory, DiagnosticMessage, DiagnosticRelatedInformation, Diagnostics, DiagnosticWithLocation, DoStatement, DynamicNamedDeclaration, ElementAccessChain, ElementAccessExpression, EntityNameExpression, - EnumDeclaration, escapeLeadingUnderscores, ESMap, every, ExportAssignment, exportAssignmentIsAlias, + EnumDeclaration, escapeLeadingUnderscores, every, ExportAssignment, exportAssignmentIsAlias, ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement, findAncestor, FlowFlags, FlowLabel, FlowNode, FlowReduceLabel, forEach, forEachChild, ForInOrOfStatement, ForStatement, FunctionDeclaration, FunctionExpression, FunctionLikeDeclaration, GetAccessorDeclaration, getAssignedExpandoInitializer, getAssignmentDeclarationKind, @@ -45,12 +45,12 @@ import { isVariableDeclaration, isVariableDeclarationInitializedToBareOrAccessedRequire, isVariableStatement, JSDocCallbackTag, JSDocClassTag, JSDocEnumTag, JSDocFunctionType, JSDocParameterTag, JSDocPropertyLikeTag, JSDocSignature, JSDocTypedefTag, JSDocTypeLiteral, JsxAttribute, JsxAttributes, LabeledStatement, length, - LiteralLikeElementAccessExpression, Map, MappedTypeNode, MethodDeclaration, ModifierFlags, ModuleBlock, + LiteralLikeElementAccessExpression, MappedTypeNode, MethodDeclaration, ModifierFlags, ModuleBlock, ModuleDeclaration, Mutable, NamespaceExportDeclaration, Node, NodeArray, NodeFlags, nodeHasName, nodeIsMissing, nodeIsPresent, NonNullChain, NonNullExpression, NumericLiteral, objectAllocator, ObjectLiteralExpression, OptionalChain, ParameterDeclaration, ParenthesizedExpression, Pattern, PatternAmbientModule, perfLogger, PostfixUnaryExpression, PrefixUnaryExpression, PrivateIdentifier, PropertyAccessChain, PropertyAccessExpression, - PropertyDeclaration, PropertySignature, removeFileExtension, ReturnStatement, ScriptTarget, Set, + PropertyDeclaration, PropertySignature, removeFileExtension, ReturnStatement, ScriptTarget, SetAccessorDeclaration, setParent, setParentRecursive, setValueDeclaration, ShorthandPropertyAssignment, shouldPreserveConstEnums, SignatureDeclaration, skipParentheses, sliceAfter, some, SourceFile, SpreadElement, Statement, StringLiteral, SwitchStatement, Symbol, SymbolFlags, symbolName, SymbolTable, SyntaxKind, TextRange, @@ -76,7 +76,7 @@ interface ActiveLabel { } /** @internal */ -export function getModuleInstanceState(node: ModuleDeclaration, visited?: ESMap): ModuleInstanceState { +export function getModuleInstanceState(node: ModuleDeclaration, visited?: Map): ModuleInstanceState { if (node.body && !node.body.parent) { // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already setParent(node.body, node); @@ -96,7 +96,7 @@ function getModuleInstanceStateCached(node: Node, visited = new Map): ModuleInstanceState { +function getModuleInstanceStateWorker(node: Node, visited: Map): ModuleInstanceState { // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations @@ -168,7 +168,7 @@ function getModuleInstanceStateWorker(node: Node, visited: ESMap) { +function getModuleInstanceStateForAliasTarget(specifier: ExportSpecifier, visited: Map) { const name = specifier.propertyName || specifier.name; let p: Node | undefined = specifier.parent; while (p) { diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index a0ab1339bca19..a98a37d25778a 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -7,12 +7,12 @@ import { createBuildInfo, createGetCanonicalFileName, createProgram, CustomTransformers, Debug, Diagnostic, DiagnosticCategory, DiagnosticMessageChain, DiagnosticRelatedInformation, DiagnosticWithLocation, EmitAndSemanticDiagnosticsBuilderProgram, EmitOnly, EmitResult, emitSkippedWithNoDiagnostics, emptyArray, - ensurePathIsNonModuleName, ESMap, filterSemanticDiagnostics, forEach, forEachEntry, forEachKey, generateDjb2Hash, + ensurePathIsNonModuleName, filterSemanticDiagnostics, forEach, forEachEntry, forEachKey, generateDjb2Hash, GetCanonicalFileName, getDirectoryPath, getEmitDeclarations, getNormalizedAbsolutePath, getOptionsNameMap, getOwnKeys, getRelativePathFromDirectory, getTsBuildInfoEmitOutputFilePath, handleNoEmitOptions, isArray, - isDeclarationFileName, isJsonSourceFile, isNumber, isString, map, Map, mapDefined, maybeBind, noop, notImplemented, - outFile, Path, Program, ProjectReference, ReadBuildProgramHost, ReadonlyCollection, ReadonlyESMap, ReadonlySet, - returnFalse, returnUndefined, SemanticDiagnosticsBuilderProgram, Set, skipTypeChecking, some, SourceFile, + isDeclarationFileName, isJsonSourceFile, isNumber, isString, map, mapDefined, maybeBind, noop, notImplemented, + outFile, Path, Program, ProjectReference, ReadBuildProgramHost, ReadonlyCollection, + returnFalse, returnUndefined, SemanticDiagnosticsBuilderProgram, skipTypeChecking, some, SourceFile, sourceFileMayBeEmitted, SourceMapEmitResult, toPath, tryAddToSet, WriteFileCallback, WriteFileCallbackData, } from "./_namespaces/ts"; @@ -51,7 +51,7 @@ export interface ReusableBuilderProgramState extends BuilderState { /** * Cache of bind and check diagnostics for files with their Path being the key */ - semanticDiagnosticsPerFile?: ESMap | undefined; + semanticDiagnosticsPerFile?: Map | undefined; /** * The map has key by source file's path that has been changed */ @@ -67,7 +67,7 @@ export interface ReusableBuilderProgramState extends BuilderState { /** * Files pending to be emitted */ - affectedFilesPendingEmit?: ReadonlyESMap; + affectedFilesPendingEmit?: ReadonlyMap; /** * emitKind pending for a program with --out */ @@ -79,7 +79,7 @@ export interface ReusableBuilderProgramState extends BuilderState { /** * Hash of d.ts emitted for the file, use to track when emit of d.ts changes */ - emitSignatures?: ESMap; + emitSignatures?: Map; /** * Hash of d.ts emit with --out */ @@ -118,7 +118,7 @@ export interface BuilderProgramState extends BuilderState, ReusableBuilderProgra /** * Cache of bind and check diagnostics for files with their Path being the key */ - semanticDiagnosticsPerFile: ESMap | undefined; + semanticDiagnosticsPerFile: Map | undefined; /** * The map has key by source file's path that has been changed */ @@ -154,7 +154,7 @@ export interface BuilderProgramState extends BuilderState, ReusableBuilderProgra /** * Files pending to be emitted */ - affectedFilesPendingEmit?: ESMap; + affectedFilesPendingEmit?: Map; /** * true if build info is emitted */ @@ -162,7 +162,7 @@ export interface BuilderProgramState extends BuilderState, ReusableBuilderProgra /** * Already seen emitted files */ - seenEmittedFiles: ESMap | undefined; + seenEmittedFiles: Map | undefined; /** Stores list of files that change signature during emit - test only */ filesChangingSignature?: Set; } @@ -954,7 +954,7 @@ function getBuildInfo(state: BuilderProgramState, getCanonicalFileName: GetCanon } let fileIdsList: (readonly ProgramBuildInfoFileId[])[] | undefined; - let fileNamesToFileIdListId: ESMap | undefined; + let fileNamesToFileIdListId: Map | undefined; let emitSignatures: ProgramBuildInfoEmitSignature[] | undefined; const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]): ProgramMultiFileEmitBuildInfoFileInfo => { // Ensure fileId @@ -1733,7 +1733,7 @@ export function getBuildInfoFileVersionMap( program: ProgramBuildInfo, buildInfoPath: string, host: Pick -): ESMap { +): Map { const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const fileInfos = new Map(); diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 6257d8a311b07..9e09ce8464290 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -1,9 +1,9 @@ import { arrayFrom, CancellationToken, computeSignatureWithDiagnostics, CustomTransformers, Debug, EmitOutput, emptyArray, - ESMap, ExportedModulesFromDeclarationEmit, GetCanonicalFileName, getDirectoryPath, getSourceFileOfNode, + ExportedModulesFromDeclarationEmit, GetCanonicalFileName, getDirectoryPath, getSourceFileOfNode, isDeclarationFileName, isExternalOrCommonJsModule, isGlobalScopeAugmentation, isJsonSourceFile, - isModuleWithStringLiteralName, isStringLiteral, Iterator, Map, mapDefined, mapDefinedIterator, ModuleDeclaration, - ModuleKind, outFile, OutputFile, Path, Program, ReadonlySet, Set, some, SourceFile, StringLiteralLike, Symbol, + isModuleWithStringLiteralName, isStringLiteral, mapDefined, mapDefinedIterator, ModuleDeclaration, + ModuleKind, outFile, OutputFile, Path, Program, some, SourceFile, StringLiteralLike, Symbol, toPath, TypeChecker, } from "./_namespaces/ts"; @@ -23,7 +23,7 @@ export interface BuilderState { /** * Information of the file eg. its version, signature etc */ - fileInfos: ESMap; + fileInfos: Map; /** * Contains the map of ReferencedSet=Referenced files of the file if module emit is enabled * Otherwise undefined @@ -52,11 +52,11 @@ export interface BuilderState { /** * Stores signatures before before the update till affected file is commited */ - oldSignatures?: ESMap; + oldSignatures?: Map; /** * Stores exportedModulesMap before the update till affected file is commited */ - oldExportedModulesMap?: ESMap | false>; + oldExportedModulesMap?: Map | false>; /** * Cache of all files excluding default library file for the current program */ @@ -90,7 +90,7 @@ export namespace BuilderState { } export function createManyToManyPathMap(): ManyToManyPathMap { - function create(forward: ESMap>, reverse: ESMap>, deleted: Set | undefined): ManyToManyPathMap { + function create(forward: Map>, reverse: Map>, deleted: Set | undefined): ManyToManyPathMap { const map: ManyToManyPathMap = { getKeys: v => reverse.get(v), getValues: k => forward.get(k), @@ -136,7 +136,7 @@ export namespace BuilderState { return create(new Map>(), new Map>(), /*deleted*/ undefined); } - function addToMultimap(map: ESMap>, k: K, v: V): void { + function addToMultimap(map: Map>, k: K, v: V): void { let set = map.get(k); if (!set) { set = new Set(); @@ -145,7 +145,7 @@ export namespace BuilderState { set.add(v); } - function deleteFromMultimap(map: ESMap>, k: K, v: V): boolean { + function deleteFromMultimap(map: Map>, k: K, v: V): boolean { const set = map.get(k); if (set?.delete(v)) { diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 310dbacba3aae..be770c06d6e01 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -26,7 +26,7 @@ import { DoStatement, DynamicNamedDeclaration, ElementAccessChain, ElementAccessExpression, ElementFlags, EmitFlags, EmitHint, EmitResolver, EmitTextWriter, emptyArray, endsWith, EntityName, EntityNameExpression, EntityNameOrEntityNameExpression, entityNameToString, EnumDeclaration, EnumMember, equateValues, - escapeLeadingUnderscores, escapeString, ESMap, every, EvolvingArrayType, ExclamationToken, ExportAssignment, + escapeLeadingUnderscores, escapeString, every, EvolvingArrayType, ExclamationToken, ExportAssignment, exportAssignmentIsAlias, ExportDeclaration, ExportSpecifier, Expression, expressionResultIsUnused, ExpressionStatement, ExpressionWithTypeArguments, Extension, ExternalEmitHelpers, externalHelpersModuleNameText, factory, fileExtensionIs, fileExtensionIsOneOf, filter, find, findAncestor, findBestPatternMatch, findIndex, @@ -151,7 +151,7 @@ import { JsxOpeningElement, JsxOpeningFragment, JsxOpeningLikeElement, JsxReferenceKind, JsxSelfClosingElement, JsxSpreadAttribute, JsxTagNameExpression, KeywordTypeNode, LabeledStatement, last, lastOrUndefined, LateBoundBinaryExpressionDeclaration, LateBoundDeclaration, LateBoundName, LateVisibilityPaintedStatement, - LeftHandSideExpression, length, LiteralExpression, LiteralType, LiteralTypeNode, mangleScopedPackageName, map, Map, + LeftHandSideExpression, length, LiteralExpression, LiteralType, LiteralTypeNode, mangleScopedPackageName, map, mapDefined, MappedSymbol, MappedType, MappedTypeNode, MatchingKeys, maybeBind, MemberName, MemberOverrideStatus, memoize, MetaProperty, MethodDeclaration, MethodSignature, minAndMax, MinusToken, Modifier, ModifierFlags, modifiersToFlags, modifierToFlag, ModuleBlock, ModuleDeclaration, ModuleInstanceState, ModuleKind, @@ -168,10 +168,10 @@ import { PrefixUnaryExpression, PrivateIdentifier, Program, PromiseOrAwaitableType, PropertyAccessChain, PropertyAccessEntityNameExpression, PropertyAccessExpression, PropertyAssignment, PropertyDeclaration, PropertyName, PropertySignature, PseudoBigInt, pseudoBigIntToString, pushIfUnique, QualifiedName, QuestionToken, rangeEquals, - rangeOfNode, rangeOfTypeParameters, ReadonlyESMap, ReadonlyKeyword, reduceLeft, RelationComparisonResult, + rangeOfNode, rangeOfTypeParameters, ReadonlyKeyword, reduceLeft, RelationComparisonResult, relativeComplement, removeExtension, removePrefix, replaceElement, resolutionExtensionIsTSOrJson, ResolvedModuleFull, ResolvedType, resolveTripleslashReference, resolvingEmptyArray, RestTypeNode, ReturnStatement, - ReverseMappedSymbol, ReverseMappedType, sameMap, SatisfiesExpression, ScriptKind, ScriptTarget, Set, + ReverseMappedSymbol, ReverseMappedType, sameMap, SatisfiesExpression, ScriptKind, ScriptTarget, SetAccessorDeclaration, setCommentRange, setEmitFlags, setNodeFlags, setOriginalNode, setParent, setSyntheticLeadingComments, setTextRange, setTextRangePosEnd, setValueDeclaration, ShorthandPropertyAssignment, shouldPreserveConstEnums, Signature, SignatureDeclaration, SignatureFlags, SignatureKind, singleElementArray, @@ -345,7 +345,7 @@ export const enum TypeFacts { AndFactsMask = All & ~OrFactsMask, } -const typeofNEFacts: ReadonlyESMap = new Map(getEntries({ +const typeofNEFacts: ReadonlyMap = new Map(getEntries({ string: TypeFacts.TypeofNEString, number: TypeFacts.TypeofNENumber, bigint: TypeFacts.TypeofNEBigInt, @@ -380,17 +380,17 @@ export const enum CheckMode { IsForSignatureHelp = 1 << 4, // Call resolution for purposes of signature help IsForStringLiteralArgumentCompletions = 1 << 5, // Do not infer from the argument currently being typed RestBindingElement = 1 << 6, // Checking a type that is going to be used to determine the type of a rest binding element - // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, - // we need to preserve generic types instead of substituting them for constraints + // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, + // we need to preserve generic types instead of substituting them for constraints } /** @internal */ export const enum SignatureCheckMode { BivariantCallback = 1 << 0, - StrictCallback = 1 << 1, + StrictCallback = 1 << 1, IgnoreReturnTypes = 1 << 2, - StrictArity = 1 << 3, - Callback = BivariantCallback | StrictCallback, + StrictArity = 1 << 3, + Callback = BivariantCallback | StrictCallback, } const enum IntersectionState { @@ -465,7 +465,7 @@ const enum IntrinsicTypeKind { Uncapitalize } -const intrinsicTypeKinds: ReadonlyESMap = new Map(getEntries({ +const intrinsicTypeKinds: ReadonlyMap = new Map(getEntries({ Uppercase: IntrinsicTypeKind.Uppercase, Lowercase: IntrinsicTypeKind.Lowercase, Capitalize: IntrinsicTypeKind.Capitalize, @@ -968,8 +968,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { apparentArgumentCount = argumentCount; const res = !node ? undefined : - editingArgument ? runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignature(node, candidatesOutArray, checkMode)) : - getResolvedSignature(node, candidatesOutArray, checkMode); + editingArgument ? runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignature(node, candidatesOutArray, checkMode)) : + getResolvedSignature(node, candidatesOutArray, checkMode); apparentArgumentCount = undefined; return res; } @@ -1148,10 +1148,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { readonly firstFile: SourceFile; readonly secondFile: SourceFile; /** Key is symbol name. */ - readonly conflictingSymbols: ESMap; + readonly conflictingSymbols: Map; } /** Key is "/path/to/a.ts|/path/to/b.ts". */ - let amalgamatedDuplicates: ESMap | undefined; + let amalgamatedDuplicates: Map | undefined; const reverseMappedCache = new Map(); let inInferTypeForHomomorphicMappedType = false; let ambientModulesCache: Symbol[] | undefined; @@ -1161,7 +1161,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * This is only used if there is no exact match. */ let patternAmbientModules: PatternAmbientModule[]; - let patternAmbientModuleAugmentations: ESMap | undefined; + let patternAmbientModuleAugmentations: Map | undefined; let globalObjectType: ObjectType; let globalFunctionType: ObjectType; @@ -1235,7 +1235,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const mergedSymbols: Symbol[] = []; const symbolLinks: SymbolLinks[] = []; const nodeLinks: NodeLinks[] = []; - const flowLoopCaches: ESMap[] = []; + const flowLoopCaches: Map[] = []; const flowLoopNodes: FlowNode[] = []; const flowLoopKeys: string[] = []; const flowLoopTypes: Type[][] = []; @@ -1415,7 +1415,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } function errorOrSuggestion(isError: boolean, location: Node, message: DiagnosticMessage | DiagnosticMessageChain, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): void { - // Pseudo-synthesized input node + // Pseudo-synthesized input node if (location.pos < 0 || location.end < 0) { if (!isError) { return; // Drop suggestions (we have no span to suggest on) @@ -1575,7 +1575,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isEitherBlockScoped = !!(target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable); const message = isEitherEnum ? Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations : isEitherBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : Diagnostics.Duplicate_identifier_0; + : Diagnostics.Duplicate_identifier_0; const sourceSymbolFile = source.declarations && getSourceFileOfNode(source.declarations[0]); const targetSymbolFile = target.declarations && getSourceFileOfNode(target.declarations[0]); @@ -1825,8 +1825,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property return !(getEmitScriptTarget(compilerOptions) === ScriptTarget.ESNext && useDefineForClassFields - && getContainingClass(declaration) === getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration)); + && getContainingClass(declaration) === getContainingClass(usage) + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -1952,8 +1952,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && (isPropertyDeclaration(declaration) && node.parent === declaration.parent - || isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) - ? "quit": true; + || isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) + ? "quit" : true; case SyntaxKind.Block: switch (node.parent.kind) { case SyntaxKind.GetAccessor: @@ -2145,7 +2145,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.SourceFile: if (!isExternalOrCommonJsModule(location as SourceFile)) break; isInExternalModule = true; - // falls through + // falls through case SyntaxKind.ModuleDeclaration: const moduleExports = getSymbolOfNode(location as SourceFile | ModuleDeclaration)?.exports || emptySymbols; if (location.kind === SyntaxKind.SourceFile || (isModuleDeclaration(location) && location.flags & NodeFlags.Ambient && !isGlobalScopeAugmentation(location))) { @@ -2281,7 +2281,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015) { break; } - // falls through + // falls through case SyntaxKind.MethodDeclaration: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: @@ -2378,7 +2378,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { lastLocation = location; location = isJSDocTemplateTag(location) ? getEffectiveContainerForJSDocTemplateTag(location) || location.parent : isJSDocParameterTag(location) || isJSDocReturnTag(location) ? getHostSignatureFromJSDoc(location) || location.parent : - location.parent; + location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. @@ -2459,7 +2459,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); const message = meaning === SymbolFlags.Namespace || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 - : Diagnostics.Cannot_find_name_0_Did_you_mean_1; + : Diagnostics.Cannot_find_name_0_Did_you_mean_1; const diagnostic = createError(errorLocation, message, diagnosticName(nameArg!), suggestionName); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { @@ -2500,7 +2500,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // we want to check for block-scoped if (errorLocation && (meaning & SymbolFlags.BlockScopedVariable || - ((meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value))) { + ((meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value))) { const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result!); if (exportOrLocalSymbol.flags & SymbolFlags.BlockScopedVariable || exportOrLocalSymbol.flags & SymbolFlags.Class || exportOrLocalSymbol.flags & SymbolFlags.Enum) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); @@ -2666,7 +2666,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isEntityNameExpression((node as ExpressionWithTypeArguments).expression)) { return (node as ExpressionWithTypeArguments).expression as EntityNameExpression; } - // falls through + // falls through default: return undefined; } @@ -2756,7 +2756,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isExtendedByInterface(node: Node): boolean { const grandparent = node.parent.parent; const parentOfGrandparent = grandparent.parent; - if(grandparent && parentOfGrandparent){ + if (grandparent && parentOfGrandparent) { const isExtending = isHeritageClause(grandparent) && grandparent.token === SyntaxKind.ExtendsKeyword; const isInterface = isInterfaceDeclaration(parentOfGrandparent); return isExtending && isInterface; @@ -2902,10 +2902,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node as ExportAssignment) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node) || isAccessExpression(node) - && isBinaryExpression(node.parent) - && node.parent.left === node - && node.parent.operatorToken.kind === SyntaxKind.EqualsToken - && isAliasableOrJsExpression(node.parent.right) + && isBinaryExpression(node.parent) + && node.parent.left === node + && node.parent.operatorToken.kind === SyntaxKind.EqualsToken + && isAliasableOrJsExpression(node.parent.right) || node.kind === SyntaxKind.ShorthandPropertyAssignment || node.kind === SyntaxKind.PropertyAssignment && isAliasableOrJsExpression((node as PropertyAssignment).initializer) || node.kind === SyntaxKind.VariableDeclaration && isVariableDeclarationInitializedToBareOrAccessedRequire(node) @@ -3098,7 +3098,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (exportStar) { const defaultExport = exportStar.declarations?.find(decl => !!( isExportDeclaration(decl) && decl.moduleSpecifier && - resolveExternalModuleName(decl, decl.moduleSpecifier)?.exports?.has(InternalSymbolName.Default) + resolveExternalModuleName(decl, decl.moduleSpecifier)?.exports?.has(InternalSymbolName.Default) )); if (defaultExport) { addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default)); @@ -3468,31 +3468,31 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * combined flags of all alias targets otherwise. */ function getAllSymbolFlags(symbol: Symbol): SymbolFlags { - let flags = symbol.flags; - let seenSymbols; - while (symbol.flags & SymbolFlags.Alias) { - const target = resolveAlias(symbol); - if (target === unknownSymbol) { - return SymbolFlags.All; - } - - // Optimizations - try to avoid creating or adding to - // `seenSymbols` if possible - if (target === symbol || seenSymbols?.has(target)) { - break; - } - if (target.flags & SymbolFlags.Alias) { - if (seenSymbols) { - seenSymbols.add(target); - } - else { - seenSymbols = new Set([symbol, target]); - } - } - flags |= target.flags; - symbol = target; - } - return flags; + let flags = symbol.flags; + let seenSymbols; + while (symbol.flags & SymbolFlags.Alias) { + const target = resolveAlias(symbol); + if (target === unknownSymbol) { + return SymbolFlags.All; + } + + // Optimizations - try to avoid creating or adding to + // `seenSymbols` if possible + if (target === symbol || seenSymbols?.has(target)) { + break; + } + if (target.flags & SymbolFlags.Alias) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; } /** @@ -3811,7 +3811,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : - undefined; + undefined; return initializer || decl; } @@ -3837,9 +3837,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function resolveExternalModuleName(location: Node, moduleReferenceExpression: Expression, ignoreErrors?: boolean): Symbol | undefined { const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic; - const errorMessage = isClassic? - Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option - : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; + const errorMessage = isClassic ? + Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option + : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage); } @@ -3863,12 +3863,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const currentSourceFile = getSourceFileOfNode(location); const contextSpecifier = isStringLiteralLike(location) ? location - : findAncestor(location, isImportCall)?.arguments[0] || - findAncestor(location, isImportDeclaration)?.moduleSpecifier || - findAncestor(location, isExternalModuleImportEqualsDeclaration)?.moduleReference.expression || - findAncestor(location, isExportDeclaration)?.moduleSpecifier || - (isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)?.name || - (isLiteralImportTypeNode(location) ? location : undefined)?.argument.literal; + : findAncestor(location, isImportCall)?.arguments[0] || + findAncestor(location, isImportDeclaration)?.moduleSpecifier || + findAncestor(location, isExternalModuleImportEqualsDeclaration)?.moduleReference.expression || + findAncestor(location, isExportDeclaration)?.moduleSpecifier || + (isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)?.name || + (isLiteralImportTypeNode(location) ? location : undefined)?.argument.literal; const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; const resolvedModule = getResolvedModule(currentSourceFile, moduleReference, mode); const resolutionDiagnostic = resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule); @@ -4228,16 +4228,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType: Type) { return !(resolvedExternalModuleType.flags & TypeFlags.Primitive || - getObjectFlags(resolvedExternalModuleType) & ObjectFlags.Class || - // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path - isArrayType(resolvedExternalModuleType) || - isTupleType(resolvedExternalModuleType)); + getObjectFlags(resolvedExternalModuleType) & ObjectFlags.Class || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol: Symbol): SymbolTable { return symbol.flags & SymbolFlags.LateBindingContainer ? getResolvedMembersOrExportsOfSymbol(symbol, MembersOrExportsResolutionKind.resolvedExports) : symbol.flags & SymbolFlags.Module ? getExportsOfModule(symbol) : - symbol.exports || emptySymbols; + symbol.exports || emptySymbols; } function getExportsOfModule(moduleSymbol: Symbol): SymbolTable { @@ -4413,20 +4413,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { && container.flags & SymbolFlags.Type && getDeclaredTypeOfSymbol(container).flags & TypeFlags.Object && meaning === SymbolFlags.Value - ? forEachSymbolTableInScope(enclosingDeclaration, t => { - return forEachEntry(t, s => { - if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { - return s; - } - }); - }) : undefined; + ? forEachSymbolTableInScope(enclosingDeclaration, t => { + return forEachEntry(t, s => { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; let res = firstVariableMatch ? [firstVariableMatch, ...additionalContainers, container] : [...additionalContainers, container]; res = append(res, objectLiteralContainer); res = addRange(res, reexportContainers); return res; } const candidates = mapDefined(symbol.declarations, d => { - if (!isAmbientModule(d) && d.parent){ + if (!isAmbientModule(d) && d.parent) { // direct children of a module if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { return getSymbolOfNode(d.parent); @@ -4648,7 +4648,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!isExternalOrCommonJsModule(location as SourceFile)) { break; } - // falls through + // falls through case SyntaxKind.ModuleDeclaration: const sym = getSymbolOfNode(location as ModuleDeclaration); // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten @@ -4690,7 +4690,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return rightMeaning === SymbolFlags.Value ? SymbolFlags.Value : SymbolFlags.Namespace; } - function getAccessibleSymbolChain(symbol: Symbol | undefined, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, useOnlyExternalAliasing: boolean, visitedSymbolTablesMap: ESMap = new Map()): Symbol[] | undefined { + function getAccessibleSymbolChain(symbol: Symbol | undefined, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, useOnlyExternalAliasing: boolean, visitedSymbolTablesMap: Map = new Map()): Symbol[] | undefined { if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { return undefined; } @@ -5214,8 +5214,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const nameType = getSymbolLinks(symbol).nameType; if (nameType && nameType.flags & (TypeFlags.EnumLiteral | TypeFlags.UniqueESSymbol)) { - context.enclosingDeclaration = nameType.symbol.valueDeclaration; - return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning)); + context.enclosingDeclaration = nameType.symbol.valueDeclaration; + return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning)); } } return symbolToExpression(symbol, context, meaning); @@ -5227,19 +5227,21 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { enclosingDeclaration, flags: flags || NodeBuilderFlags.None, // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: () => false, moduleResolverHost: flags! & NodeBuilderFlags.DoNotIncludeSymbolChain ? { - getCommonSourceDirectory: !!(host as Program).getCommonSourceDirectory ? () => (host as Program).getCommonSourceDirectory() : () => "", - getCurrentDirectory: () => host.getCurrentDirectory(), - getSymlinkCache: maybeBind(host, host.getSymlinkCache), - getPackageJsonInfoCache: () => host.getPackageJsonInfoCache?.(), - useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), - redirectTargetsMap: host.redirectTargetsMap, - getProjectReferenceRedirect: fileName => host.getProjectReferenceRedirect(fileName), - isSourceOfProjectReferenceRedirect: fileName => host.isSourceOfProjectReferenceRedirect(fileName), - fileExists: fileName => host.fileExists(fileName), - getFileIncludeReasons: () => host.getFileIncludeReasons(), - readFile: host.readFile ? (fileName => host.readFile!(fileName)) : undefined, - } : undefined }, + tracker: tracker && tracker.trackSymbol ? tracker : { + trackSymbol: () => false, moduleResolverHost: flags! & NodeBuilderFlags.DoNotIncludeSymbolChain ? { + getCommonSourceDirectory: !!(host as Program).getCommonSourceDirectory ? () => (host as Program).getCommonSourceDirectory() : () => "", + getCurrentDirectory: () => host.getCurrentDirectory(), + getSymlinkCache: maybeBind(host, host.getSymlinkCache), + getPackageJsonInfoCache: () => host.getPackageJsonInfoCache?.(), + useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), + redirectTargetsMap: host.redirectTargetsMap, + getProjectReferenceRedirect: fileName => host.getProjectReferenceRedirect(fileName), + isSourceOfProjectReferenceRedirect: fileName => host.isSourceOfProjectReferenceRedirect(fileName), + fileExists: fileName => host.fileExists(fileName), + getFileIncludeReasons: () => host.getFileIncludeReasons(), + readFile: host.readFile ? (fileName => host.readFile!(fileName)) : undefined, + } : undefined + }, encounteredError: false, reportedDiagnostic: false, visitedTypes: undefined, @@ -5713,8 +5715,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isConstructorObject = getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class; const id = getObjectFlags(type) & ObjectFlags.Reference && (type as TypeReference).node ? "N" + getNodeId((type as TypeReference).node!) : type.flags & TypeFlags.Conditional ? "N" + getNodeId((type as ConditionalType).root.node) : - type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) : - undefined; + type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) : + undefined; // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type if (!context.visitedTypes) { @@ -5755,7 +5757,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (result as any).truncating = true; } (result as any).addedLength = addedLength; - links?.serializedTypes?.set(key, result as TypeNode as TypeNode & {truncating?: boolean, addedLength: number}); + links?.serializedTypes?.set(key, result as TypeNode as TypeNode & { truncating?: boolean, addedLength: number }); } context.visitedTypes.delete(typeId); if (id) { @@ -5866,7 +5868,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel((type.target as TupleType).labeledElementDeclarations![i]))), flags & ElementFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, flags & ElementFlags.Rest ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : - tupleConstituentNodes[i] + tupleConstituentNodes[i] ); } } @@ -5875,8 +5877,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const flags = (type.target as TupleType).elementFlags[i]; tupleConstituentNodes[i] = flags & ElementFlags.Variable ? factory.createRestTypeNode(flags & ElementFlags.Rest ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : - flags & ElementFlags.Optional ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : - tupleConstituentNodes[i]; + flags & ElementFlags.Optional ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : + tupleConstituentNodes[i]; } } const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode(tupleConstituentNodes), EmitFlags.SingleLine); @@ -6303,20 +6305,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const node = kind === SyntaxKind.CallSignature ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === SyntaxKind.ConstructSignature ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === SyntaxKind.MethodSignature ? factory.createMethodSignature(modifiers, options?.name ?? factory.createIdentifier(""), options?.questionToken, typeParameters, parameters, returnTypeNode) : - kind === SyntaxKind.MethodDeclaration ? factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, options?.name ?? factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === SyntaxKind.Constructor ? factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : - kind === SyntaxKind.GetAccessor ? factory.createGetAccessorDeclaration(modifiers, options?.name ?? factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === SyntaxKind.SetAccessor ? factory.createSetAccessorDeclaration(modifiers, options?.name ?? factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === SyntaxKind.IndexSignature ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : - kind === SyntaxKind.JSDocFunctionType ? factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === SyntaxKind.FunctionType ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : - kind === SyntaxKind.ConstructorType ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : - kind === SyntaxKind.FunctionDeclaration ? factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, options?.name ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === SyntaxKind.FunctionExpression ? factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, options?.name ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, factory.createBlock([])) : - kind === SyntaxKind.ArrowFunction ? factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, factory.createBlock([])) : - Debug.assertNever(kind); + kind === SyntaxKind.ConstructSignature ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === SyntaxKind.MethodSignature ? factory.createMethodSignature(modifiers, options?.name ?? factory.createIdentifier(""), options?.questionToken, typeParameters, parameters, returnTypeNode) : + kind === SyntaxKind.MethodDeclaration ? factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, options?.name ?? factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === SyntaxKind.Constructor ? factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === SyntaxKind.GetAccessor ? factory.createGetAccessorDeclaration(modifiers, options?.name ?? factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === SyntaxKind.SetAccessor ? factory.createSetAccessorDeclaration(modifiers, options?.name ?? factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === SyntaxKind.IndexSignature ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : + kind === SyntaxKind.JSDocFunctionType ? factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === SyntaxKind.FunctionType ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : + kind === SyntaxKind.ConstructorType ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : + kind === SyntaxKind.FunctionDeclaration ? factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, options?.name ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === SyntaxKind.FunctionExpression ? factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, options?.name ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, factory.createBlock([])) : + kind === SyntaxKind.ArrowFunction ? factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, factory.createBlock([])) : + Debug.assertNever(kind); if (typeArguments) { node.typeArguments = factory.createNodeArray(typeArguments); @@ -6376,8 +6378,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const dotDotDotToken = isRest ? factory.createToken(SyntaxKind.DotDotDotToken) : undefined; const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === SyntaxKind.Identifier ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : - parameterDeclaration.name.kind === SyntaxKind.QualifiedName ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), EmitFlags.NoAsciiEscaping) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === SyntaxKind.QualifiedName ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), EmitFlags.NoAsciiEscaping) : + cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & CheckFlags.OptionalParameter; @@ -6612,7 +6614,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { importModuleSpecifierPreference: isBundle ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle ? "minimal" : resolutionMode === ModuleKind.ESNext ? "js" - : undefined, + : undefined, }, { overrideImportMode } )); @@ -6895,7 +6897,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } let expression: Expression | undefined; if (isSingleOrDoubleQuote(firstChar) && !(symbol.flags & SymbolFlags.EnumMember)) { - expression = factory.createStringLiteral(stripQuotes(symbolName).replace(/\\./g, s => s.substring(1)), firstChar === CharacterCodes.singleQuote); + expression = factory.createStringLiteral(stripQuotes(symbolName).replace(/\\./g, s => s.substring(1)), firstChar === CharacterCodes.singleQuote); } else if (("" + +symbolName) === symbolName) { expression = factory.createNumericLiteral(+symbolName); @@ -7211,7 +7213,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getNameForJSDocFunctionParameter(p: ParameterDeclaration, index: number) { return p.name && isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? `args` - : `arg${index}`; + : `arg${index}`; } function rewriteModuleSpecifier(parent: ImportTypeNode, lit: StringLiteral) { @@ -7256,7 +7258,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const enclosingDeclaration = context.enclosingDeclaration!; let results: Statement[] = []; const visitedSymbols = new Set(); - const deferredPrivatesStack: ESMap[] = []; + const deferredPrivatesStack: Map[] = []; const oldcontext = context; context = { ...oldcontext, @@ -7513,7 +7515,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; // If we need to emit a private with a keyword name, we're done for, since something else will try to refer to it by that name } let needsPostExportDefault = isDefault && !!( - symbol.flags & SymbolFlags.ExportDoesNotSupportDefaultModifier + symbol.flags & SymbolFlags.ExportDoesNotSupportDefaultModifier || (symbol.flags & SymbolFlags.Function && length(getPropertiesOfType(getTypeOfSymbol(symbol)))) ) && !(symbol.flags & SymbolFlags.Alias); // An alias symbol should preclude needing to make an alias ourselves let needsExportDeclaration = !needsPostExportDefault && !isPrivate && isStringANonContextualKeyword(symbolName) && !isDefault; @@ -7834,7 +7836,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined; return factory.createEnumMember(unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : - factory.createNumericLiteral(initializedValue)); + factory.createNumericLiteral(initializedValue)); }) ), modifierFlags); } @@ -8129,7 +8131,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ), modifierFlags); break; } - // else fall through and treat commonjs require just like import= + // else fall through and treat commonjs require just like import= case SyntaxKind.ImportEqualsDeclaration: // This _specifically_ only exists to handle json declarations - where we make aliases, but since // we emit no declarations for the json document, must not refer to it in the declarations @@ -8325,8 +8327,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Otherwise, the type itself should be exported. addResult(statement, target && target.flags & SymbolFlags.Property && target.escapedName === InternalSymbolName.ExportEquals ? ModifierFlags.Ambient - : name === varName ? ModifierFlags.Export - : ModifierFlags.None); + : name === varName ? ModifierFlags.Export + : ModifierFlags.None); } if (isExportAssignmentCompatibleSymbolName) { results.push(factory.createExportAssignment( @@ -8350,15 +8352,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it) const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration); return getObjectFlags(typeToSerialize) & (ObjectFlags.Anonymous | ObjectFlags.Mapped) && - !length(getIndexInfosOfType(typeToSerialize)) && - !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class - !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, SignatureKind.Call))) && - !length(getSignaturesOfType(typeToSerialize, SignatureKind.Construct)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && - !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && - !some(getPropertiesOfType(typeToSerialize), p => isLateBoundName(p.escapedName)) && - !some(getPropertiesOfType(typeToSerialize), p => some(p.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && - every(getPropertiesOfType(typeToSerialize), p => isIdentifierText(symbolName(p), languageVersion)); + !length(getIndexInfosOfType(typeToSerialize)) && + !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class + !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, SignatureKind.Call))) && + !length(getSignaturesOfType(typeToSerialize, SignatureKind.Construct)) && // TODO: could probably serialize as function + ns + class, now that that's OK + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && + !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && + !some(getPropertiesOfType(typeToSerialize), p => isLateBoundName(p.escapedName)) && + !some(getPropertiesOfType(typeToSerialize), p => some(p.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && + every(getPropertiesOfType(typeToSerialize), p => isIdentifierText(symbolName(p), languageVersion)); } function makeSerializePropertySymbol(createProperty: ( @@ -8392,9 +8394,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (p.flags & SymbolFlags.Prototype || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)!) === isReadonlySymbol(p) - && (p.flags & SymbolFlags.Optional) === (getPropertyOfType(baseType, p.escapedName)!.flags & SymbolFlags.Optional) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)!))) { + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)!) === isReadonlySymbol(p) + && (p.flags & SymbolFlags.Optional) === (getPropertyOfType(baseType, p.escapedName)!.flags & SymbolFlags.Optional) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)!))) { return []; } const flag = (modifierFlags & ~ModifierFlags.Async) | (isStatic ? ModifierFlags.Static : 0); @@ -8515,7 +8517,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (privateProtected) { return [setTextRange(factory.createConstructorDeclaration( factory.createModifiersFromModifierFlags(privateProtected), - /*parameters*/ [], + /*parameters*/[], /*body*/ undefined, ), signatures[0].declaration)]; } @@ -8718,16 +8720,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { encounteredError: boolean; reportedDiagnostic: boolean; visitedTypes: Set | undefined; - symbolDepth: ESMap | undefined; + symbolDepth: Map | undefined; inferTypeParameters: TypeParameter[] | undefined; approximateLength: number; truncating?: boolean; typeParameterSymbolList?: Set; - typeParameterNames?: ESMap; + typeParameterNames?: Map; typeParameterNamesByText?: Set; - typeParameterNamesByTextNextNameCount?: ESMap; + typeParameterNamesByTextNextNameCount?: Map; usedSymbolNames?: Set; - remappedSymbolNames?: ESMap; + remappedSymbolNames?: Map; reverseMappedStack?: ReverseMappedSymbol[]; } @@ -8765,10 +8767,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (context && symbol.escapedName === InternalSymbolName.Default && !(context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope) && // If it's not the first part of an entity name, it must print as `default` (!(context.flags & NodeBuilderFlags.InInitialEntityName) || - // if the symbol is synthesized, it will only be referenced externally it must print as `default` - !symbol.declarations || - // if not in the same binding context (source file, module declaration), it must print as `default` - (context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { return "default"; } if (symbol.declarations && symbol.declarations.length) { @@ -8837,7 +8839,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // If the binding pattern is empty, this variable declaration is not visible return false; } - // falls through + // falls through case SyntaxKind.ModuleDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: @@ -8868,8 +8870,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Private/protected properties/methods are not visible return false; } - // Public properties/methods are visible if its parents are visible, so: - // falls through + // Public properties/methods are visible if its parents are visible, so: + // falls through case SyntaxKind.Constructor: case SyntaxKind.ConstructSignature: @@ -9415,14 +9417,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const constructor = findConstructorDeclaration(declaration.parent); const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & ModifierFlags.Ambient ? getTypeOfPropertyInBaseClass(declaration.symbol) : - undefined; + undefined; return type && addOptionality(type, /*isProperty*/ true, isOptional); } else { const staticBlocks = filter(declaration.parent.members, isClassStaticBlockDeclaration); const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & ModifierFlags.Ambient ? getTypeOfPropertyInBaseClass(declaration.symbol) : - undefined; + undefined; return type && addOptionality(type, /*isProperty*/ true, isOptional); } } @@ -9570,7 +9572,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (const declaration of symbol.declarations) { const expression = (isBinaryExpression(declaration) || isCallExpression(declaration)) ? declaration : isAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; + undefined; if (!expression) { continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere } @@ -9698,7 +9700,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isDirectExport = kind === AssignmentDeclarationKind.ExportsProperty && (isPropertyAccessExpression(expression.left) || isElementAccessExpression(expression.left)) && (isModuleExportsAccessExpression(expression.left.expression) || (isIdentifier(expression.left.expression) && isExportsIdentifier(expression.left.expression))); const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : isDirectExport ? getRegularTypeOfLiteralType(checkExpressionCached(expression.right)) - : getWidenedLiteralType(checkExpressionCached(expression.right)); + : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & TypeFlags.Object && kind === AssignmentDeclarationKind.ModuleExports && symbol.escapedName === InternalSymbolName.ExportEquals) { @@ -10048,7 +10050,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if ( isBinaryExpression(declaration) || (isInJSFile(declaration) && - (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent)))) { + (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent)))) { type = getWidenedTypeForAssignmentDeclaration(symbol); } else if (isPropertyAccessExpression(declaration) @@ -10082,11 +10084,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, CheckMode.Normal); } else if (isParameter(declaration) - || isPropertyDeclaration(declaration) - || isPropertySignature(declaration) - || isVariableDeclaration(declaration) - || isBindingElement(declaration) - || isJSDocPropertyLikeTag(declaration)) { + || isPropertyDeclaration(declaration) + || isPropertySignature(declaration) + || isVariableDeclaration(declaration) + || isBindingElement(declaration) + || isJSDocPropertyLikeTag(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. @@ -10219,7 +10221,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); return baseConstructorType.flags & TypeFlags.TypeVariable ? baseConstructorType : baseConstructorType.flags & TypeFlags.Intersection ? find((baseConstructorType as IntersectionType).types, t => !!(t.flags & TypeFlags.TypeVariable)) : - undefined; + undefined; } function getTypeOfFuncClassEnumModule(symbol: Symbol): Type { @@ -10245,8 +10247,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return anyType; } else if (declaration && (declaration.kind === SyntaxKind.BinaryExpression || - isAccessExpression(declaration) && - declaration.parent.kind === SyntaxKind.BinaryExpression)) { + isAccessExpression(declaration) && + declaration.parent.kind === SyntaxKind.BinaryExpression)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & SymbolFlags.ValueModule && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -10291,9 +10293,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // up recursively calling getTypeOfAlias, causing a stack overflow. links.type = exportSymbol?.declarations && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations!.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType - : declaredType ? declaredType - : getAllSymbolFlags(targetSymbol) & SymbolFlags.Value ? getTypeOfSymbol(targetSymbol) - : errorType; + : declaredType ? declaredType + : getAllSymbolFlags(targetSymbol) & SymbolFlags.Value ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -11202,7 +11204,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!symbol.declarations) { symbol.declarations = [member]; } - else if(!member.symbol.isReplaceableByMethod) { + else if (!member.symbol.isReplaceableByMethod) { symbol.declarations.push(member); } if (symbolFlags & SymbolFlags.Value) { @@ -11290,7 +11292,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isStatic = resolutionKind === MembersOrExportsResolutionKind.resolvedExports; const earlySymbols = !isStatic ? symbol.members : symbol.flags & SymbolFlags.Module ? getExportsOfModuleWorker(symbol) : - symbol.exports; + symbol.exports; // In the event we recursively resolve the members/exports of the symbol, we // set the initial value of resolvedMembers/resolvedExports to the early-bound @@ -11710,8 +11712,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const paramName = leftName === rightName ? leftName : !leftName ? rightName : - !rightName ? leftName : - undefined; + !rightName ? leftName : + undefined; const paramSymbol = createSymbol( SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0), paramName || `arg${i}` as __String @@ -12122,7 +12124,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (isValidIndexKeyType(propNameType) || propNameType.flags & (TypeFlags.Any | TypeFlags.Enum)) { const indexKeyType = propNameType.flags & (TypeFlags.Any | TypeFlags.String) ? stringType : propNameType.flags & (TypeFlags.Number | TypeFlags.Enum) ? numberType : - propNameType; + propNameType; const propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType)); const indexInfo = createIndexInfo(indexKeyType, propType, !!(templateModifiers & MappedTypeModifiers.IncludeReadonly)); indexInfos = appendIndexInfo(indexInfos, indexInfo, /*union*/ true); @@ -12145,7 +12147,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // mode, if the underlying property is optional we remove 'undefined' from the type. let type = strictNullChecks && symbol.flags & SymbolFlags.Optional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(propType, /*isProperty*/ true) : symbol.checkFlags & CheckFlags.StripOptional ? removeMissingOrUndefinedType(propType) : - propType; + propType; if (!popTypeResolution()) { error(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType)); type = errorType; @@ -12376,8 +12378,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getConstraintOfType(type: InstantiableType | UnionOrIntersectionType): Type | undefined { return type.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(type as TypeParameter) : type.flags & TypeFlags.IndexedAccess ? getConstraintOfIndexedAccess(type as IndexedAccessType) : - type.flags & TypeFlags.Conditional ? getConstraintOfConditionalType(type as ConditionalType) : - getBaseConstraintOfType(type); + type.flags & TypeFlags.Conditional ? getConstraintOfConditionalType(type as ConditionalType) : + getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter: TypeParameter): Type | undefined { @@ -12599,7 +12601,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return t.flags & TypeFlags.Union && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & TypeFlags.Intersection && baseTypes.length ? getIntersectionType(baseTypes) : - undefined; + undefined; } if (t.flags & TypeFlags.Index) { return keyofConstraintType; @@ -12717,15 +12719,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const t = !(type.flags & TypeFlags.Instantiable) ? type : getBaseConstraintOfType(type) || unknownType; return getObjectFlags(t) & ObjectFlags.Mapped ? getApparentTypeOfMappedType(t as MappedType) : t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t as IntersectionType) : - t.flags & TypeFlags.StringLike ? globalStringType : - t.flags & TypeFlags.NumberLike ? globalNumberType : - t.flags & TypeFlags.BigIntLike ? getGlobalBigIntType() : - t.flags & TypeFlags.BooleanLike ? globalBooleanType : - t.flags & TypeFlags.ESSymbolLike ? getGlobalESSymbolType() : - t.flags & TypeFlags.NonPrimitive ? emptyObjectType : - t.flags & TypeFlags.Index ? keyofConstraintType : - t.flags & TypeFlags.Unknown && !strictNullChecks ? emptyObjectType : - t; + t.flags & TypeFlags.StringLike ? globalStringType : + t.flags & TypeFlags.NumberLike ? globalNumberType : + t.flags & TypeFlags.BigIntLike ? getGlobalBigIntType() : + t.flags & TypeFlags.BooleanLike ? globalBooleanType : + t.flags & TypeFlags.ESSymbolLike ? getGlobalESSymbolType() : + t.flags & TypeFlags.NonPrimitive ? emptyObjectType : + t.flags & TypeFlags.Index ? keyofConstraintType : + t.flags & TypeFlags.Unknown && !strictNullChecks ? emptyObjectType : + t; } function getReducedApparentType(type: Type): Type { @@ -12738,7 +12740,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: __String, skipObjectFunctionPropertyAugment?: boolean): Symbol | undefined { let singleProp: Symbol | undefined; - let propSet: ESMap | undefined; + let propSet: Map | undefined; let indexTypes: Type[] | undefined; const isUnion = containingType.flags & TypeFlags.Union; // Flags we want to propagate to the result if they exist in all source symbols @@ -13039,8 +13041,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (skipObjectFunctionPropertyAugment) return undefined; const functionType = resolved === anyFunctionType ? globalFunctionType : resolved.callSignatures.length ? globalCallableFunctionType : - resolved.constructSignatures.length ? globalNewableFunctionType : - undefined; + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; if (functionType) { const symbol = getPropertyOfObjectType(functionType, name); if (symbol) { @@ -13097,10 +13099,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // the intersected key type, we just use unknownType for the key type as nothing actually depends on the // keyType property of the returned IndexInfo. return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, info => info.type)), - reduceLeft(applicableInfos, (isReadonly, info) => isReadonly && info.isReadonly, /*initial*/ true)) : + reduceLeft(applicableInfos, (isReadonly, info) => isReadonly && info.isReadonly, /*initial*/ true)) : applicableInfo ? applicableInfo : - stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : - undefined; + stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : + undefined; } function isApplicableIndexType(source: Type, target: Type): boolean { @@ -13156,7 +13158,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return result?.length ? result : isFunctionDeclaration(declaration) ? getSignatureOfTypeTag(declaration)?.typeParameters - : undefined; + : undefined; } function symbolsToArray(symbols: SymbolTable): Symbol[] { @@ -13468,7 +13470,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (!isFunctionExpressionOrArrowFunction(decl) && !isObjectLiteralMethod(decl) && getSignatureOfTypeTag(decl)) || - getSignatureFromDeclaration(decl) + getSignatureFromDeclaration(decl) ); } return result; @@ -13539,8 +13541,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, UnionReduction.Subtype), signature.mapper) : - getReturnTypeFromAnnotation(signature.declaration!) || - (nodeIsMissing((signature.declaration as FunctionLikeDeclaration).body) ? anyType : getReturnTypeFromBody(signature.declaration as FunctionLikeDeclaration)); + getReturnTypeFromAnnotation(signature.declaration!) || + (nodeIsMissing((signature.declaration as FunctionLikeDeclaration).body) ? anyType : getReturnTypeFromBody(signature.declaration as FunctionLikeDeclaration)); if (signature.flags & SignatureFlags.IsInnerCallChain) { type = addOptionalTypeMarker(type); } @@ -13956,8 +13958,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const node = type.node; const typeArguments = !node ? emptyArray : node.kind === SyntaxKind.TypeReference ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters!)) : - node.kind === SyntaxKind.ArrayType ? [getTypeFromTypeNode(node.elementType)] : - map(node.elements, getTypeFromTypeNode); + node.kind === SyntaxKind.ArrayType ? [getTypeFromTypeNode(node.elementType)] : + map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; } @@ -14108,12 +14110,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getUnresolvedSymbolForEntityName(name: EntityNameOrEntityNameExpression) { const identifier = name.kind === SyntaxKind.QualifiedName ? name.right : name.kind === SyntaxKind.PropertyAccessExpression ? name.name : - name; + name; const text = identifier.escapedText; if (text) { const parentSymbol = name.kind === SyntaxKind.QualifiedName ? getUnresolvedSymbolForEntityName(name.left) : name.kind === SyntaxKind.PropertyAccessExpression ? getUnresolvedSymbolForEntityName(name.expression) : - undefined; + undefined; const path = parentSymbol ? `${getSymbolPath(parentSymbol)}.${text}` : text as string; let result = unresolvedSymbols.get(path); if (!result) { @@ -14215,7 +14217,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getImpliedConstraint(type: Type, checkNode: TypeNode, extendsNode: TypeNode): Type | undefined { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, (checkNode as TupleTypeNode).elements[0], (extendsNode as TupleTypeNode).elements[0]) : getActualTypeVariable(getTypeFromTypeNode(checkNode)) === getActualTypeVariable(type) ? getTypeFromTypeNode(extendsNode) : - undefined; + undefined; } function getConditionalFlowTypeOfType(type: Type, node: Node) { @@ -14608,7 +14610,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.NamedTupleMember: return (node as NamedTupleMember).questionToken ? ElementFlags.Optional : (node as NamedTupleMember).dotDotDotToken ? getRestTypeElementFlags(node as NamedTupleMember) : - ElementFlags.Required; + ElementFlags.Required; default: return ElementFlags.Required; } @@ -14634,8 +14636,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isDeferredTypeReferenceNode(node: TypeReferenceNode | ArrayTypeNode | TupleTypeNode, hasDefaultTypeArguments?: boolean) { return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && ( node.kind === SyntaxKind.ArrayType ? mayResolveTypeAlias(node.elementType) : - node.kind === SyntaxKind.TupleType ? some(node.elements, mayResolveTypeAlias) : - hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias)); + node.kind === SyntaxKind.TupleType ? some(node.elements, mayResolveTypeAlias) : + hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias)); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -14720,7 +14722,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const tupleTarget = getTupleTargetType(elementFlags || map(elementTypes, _ => ElementFlags.Required), readonly, namedMemberDeclarations); return tupleTarget === emptyGenericType ? emptyObjectType : elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) : - tupleTarget; + tupleTarget; } function getTupleTargetType(elementFlags: readonly ElementFlags[], readonly: boolean, namedMemberDeclarations?: readonly (NamedTupleMember | ParameterDeclaration)[]): GenericType { @@ -14875,7 +14877,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations); return tupleTarget === emptyGenericType ? emptyObjectType : expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) : - tupleTarget; + tupleTarget; function addElement(type: Type, flags: ElementFlags, declaration: NamedTupleMember | ParameterDeclaration | undefined) { if (flags & ElementFlags.Required) { @@ -15142,7 +15144,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (typeSet.length === 0) { return includes & TypeFlags.Null ? includes & TypeFlags.IncludesNonWideningType ? nullType : nullWideningType : includes & TypeFlags.Undefined ? includes & TypeFlags.IncludesNonWideningType ? undefinedType : undefinedWideningType : - neverType; + neverType; } } if (!origin && includes & TypeFlags.Union) { @@ -15219,8 +15221,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const typeKey = !origin ? getTypeListId(types) : origin.flags & TypeFlags.Union ? `|${getTypeListId((origin as UnionType).types)}` : - origin.flags & TypeFlags.Intersection ? `&${getTypeListId((origin as IntersectionType).types)}` : - `#${(origin as IndexType).type.id}|${getTypeListId(types)}`; // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + origin.flags & TypeFlags.Intersection ? `&${getTypeListId((origin as IntersectionType).types)}` : + `#${(origin as IndexType).type.id}|${getTypeListId(types)}`; // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving const id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); let type = unionTypes.get(id); if (!type) { @@ -15249,7 +15251,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return links.resolvedType; } - function addTypeToIntersection(typeSet: ESMap, includes: TypeFlags, type: Type) { + function addTypeToIntersection(typeSet: Map, includes: TypeFlags, type: Type) { const flags = type.flags; if (flags & TypeFlags.Intersection) { return addTypesToIntersection(typeSet, includes, (type as IntersectionType).types); @@ -15285,7 +15287,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. - function addTypesToIntersection(typeSet: ESMap, includes: TypeFlags, types: readonly Type[]) { + function addTypesToIntersection(typeSet: Map, includes: TypeFlags, types: readonly Type[]) { for (const type of types) { includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } @@ -15318,9 +15320,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!containsType(u.types, type)) { const primitive = type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : - type.flags & TypeFlags.BigIntLiteral ? bigintType : - type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : - undefined; + type.flags & TypeFlags.BigIntLiteral ? bigintType : + type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : + undefined; if (!primitive || !containsType(u.types, primitive)) { return false; } @@ -15428,7 +15430,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. function getIntersectionType(types: readonly Type[], aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[], noSupertypeReduction?: boolean): Type { - const typeMembershipMap: ESMap = new Map(); + const typeMembershipMap: Map = new Map(); const includes = addTypesToIntersection(typeMembershipMap, 0, types); const typeSet: Type[] = arrayFrom(typeMembershipMap.values()); // An intersection type is considered empty if it contains @@ -15557,7 +15559,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getConstituentCount(type: Type): number { return !(type.flags & TypeFlags.UnionOrIntersection) || type.aliasSymbol ? 1 : type.flags & TypeFlags.Union && (type as UnionType).origin ? getConstituentCount((type as UnionType).origin!) : - getConstituentCountOfTypes((type as UnionOrIntersectionType).types); + getConstituentCountOfTypes((type as UnionOrIntersectionType).types); } function getConstituentCountOfTypes(types: Type[]): number { @@ -15635,7 +15637,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // we had to pick apart the constraintType to potentially map/filter it - compare the final resulting list with the original constraintType, // so we can return the union that preserves aliases/origin data if possible const result = noIndexSignatures ? filterType(getUnionType(keyTypes), t => !(t.flags & (TypeFlags.Any | TypeFlags.String))) : getUnionType(keyTypes); - if (result.flags & TypeFlags.Union && constraintType.flags & TypeFlags.Union && getTypeListId((result as UnionType).types) === getTypeListId((constraintType as UnionType).types)){ + if (result.flags & TypeFlags.Union && constraintType.flags & TypeFlags.Union && getTypeListId((result as UnionType).types) === getTypeListId((constraintType as UnionType).types)) { return constraintType; } return result; @@ -15659,11 +15661,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isDistributive(type: Type): boolean { return type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Primitive | TypeFlags.Never | TypeFlags.TypeParameter | TypeFlags.Object | TypeFlags.NonPrimitive) ? true : type.flags & TypeFlags.Conditional ? (type as ConditionalType).root.isDistributive && (type as ConditionalType).checkType === typeVariable : - type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) ? every((type as UnionOrIntersectionType | TemplateLiteralType).types, isDistributive) : - type.flags & TypeFlags.IndexedAccess ? isDistributive((type as IndexedAccessType).objectType) && isDistributive((type as IndexedAccessType).indexType) : - type.flags & TypeFlags.Substitution ? isDistributive((type as SubstitutionType).baseType) && isDistributive((type as SubstitutionType).constraint): - type.flags & TypeFlags.StringMapping ? isDistributive((type as StringMappingType).type) : - false; + type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) ? every((type as UnionOrIntersectionType | TemplateLiteralType).types, isDistributive) : + type.flags & TypeFlags.IndexedAccess ? isDistributive((type as IndexedAccessType).objectType) && isDistributive((type as IndexedAccessType).indexType) : + type.flags & TypeFlags.Substitution ? isDistributive((type as SubstitutionType).baseType) && isDistributive((type as SubstitutionType).constraint) : + type.flags & TypeFlags.StringMapping ? isDistributive((type as StringMappingType).type) : + false; } } @@ -15726,13 +15728,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type = getReducedType(type); return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type as InstantiableType | UnionOrIntersectionType, stringsOnly) : type.flags & TypeFlags.Union ? getIntersectionType(map((type as UnionType).types, t => getIndexType(t, stringsOnly, noIndexSignatures))) : - type.flags & TypeFlags.Intersection ? getUnionType(map((type as IntersectionType).types, t => getIndexType(t, stringsOnly, noIndexSignatures))) : - getObjectFlags(type) & ObjectFlags.Mapped ? getIndexTypeForMappedType(type as MappedType, stringsOnly, noIndexSignatures) : - type === wildcardType ? wildcardType : - type.flags & TypeFlags.Unknown ? neverType : - type.flags & (TypeFlags.Any | TypeFlags.Never) ? keyofConstraintType : - getLiteralTypeFromProperties(type, (noIndexSignatures ? TypeFlags.StringLiteral : TypeFlags.StringLike) | (stringsOnly ? 0 : TypeFlags.NumberLike | TypeFlags.ESSymbolLike), - stringsOnly === keyofStringsOnly && !noIndexSignatures); + type.flags & TypeFlags.Intersection ? getUnionType(map((type as IntersectionType).types, t => getIndexType(t, stringsOnly, noIndexSignatures))) : + getObjectFlags(type) & ObjectFlags.Mapped ? getIndexTypeForMappedType(type as MappedType, stringsOnly, noIndexSignatures) : + type === wildcardType ? wildcardType : + type.flags & TypeFlags.Unknown ? neverType : + type.flags & (TypeFlags.Any | TypeFlags.Never) ? keyofConstraintType : + getLiteralTypeFromProperties(type, (noIndexSignatures ? TypeFlags.StringLiteral : TypeFlags.StringLike) | (stringsOnly ? 0 : TypeFlags.NumberLike | TypeFlags.ESSymbolLike), + stringsOnly === keyofStringsOnly && !noIndexSignatures); } function getExtractStringType(type: Type) { @@ -15852,9 +15854,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getTemplateStringForType(type: Type) { return type.flags & TypeFlags.StringLiteral ? (type as StringLiteralType).value : type.flags & TypeFlags.NumberLiteral ? "" + (type as NumberLiteralType).value : - type.flags & TypeFlags.BigIntLiteral ? pseudoBigIntToString((type as BigIntLiteralType).value) : - type.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) ? (type as IntrinsicType).intrinsicName : - undefined; + type.flags & TypeFlags.BigIntLiteral ? pseudoBigIntToString((type as BigIntLiteralType).value) : + type.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) ? (type as IntrinsicType).intrinsicName : + undefined; } function createTemplateLiteralType(texts: readonly string[], types: readonly Type[]) { @@ -15867,13 +15869,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getStringMappingType(symbol: Symbol, type: Type): Type { return type.flags & (TypeFlags.Union | TypeFlags.Never) ? mapType(type, t => getStringMappingType(symbol, t)) : type.flags & TypeFlags.StringLiteral ? getStringLiteralType(applyStringMapping(symbol, (type as StringLiteralType).value)) : - type.flags & TypeFlags.TemplateLiteral ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, (type as TemplateLiteralType).texts, (type as TemplateLiteralType).types)) : - // Mapping> === Mapping - type.flags & TypeFlags.StringMapping && symbol === type.symbol ? type : - type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.StringMapping) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - // This handles Mapping<`${number}`> and Mapping<`${bigint}`> - isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : - type; + type.flags & TypeFlags.TemplateLiteral ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, (type as TemplateLiteralType).texts, (type as TemplateLiteralType).types)) : + // Mapping> === Mapping + type.flags & TypeFlags.StringMapping && symbol === type.symbol ? type : + type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.StringMapping) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol: Symbol, str: string) { @@ -15953,10 +15955,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getPropertyNameFromIndex(indexType: Type, accessNode: StringLiteral | Identifier | PrivateIdentifier | ObjectBindingPattern | ArrayBindingPattern | ComputedPropertyName | NumericLiteral | IndexedAccessTypeNode | ElementAccessExpression | SyntheticExpression | undefined) { return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessNode && isPropertyName(accessNode) ? - // late bound names are handled in the first branch, so here we only need to handle normal names - getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node: Node, symbol: Symbol) { @@ -16054,8 +16056,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { !(objectType.symbol && objectType.symbol.flags & (SymbolFlags.RegularEnum | SymbolFlags.ConstEnum) && (indexType.symbol && - indexType.flags & TypeFlags.EnumLiteral && - getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + indexType.flags & TypeFlags.EnumLiteral && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { return getUnionType([indexInfo.type, undefinedType]); } return indexInfo.type; @@ -16164,8 +16166,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getIndexNodeForAccessExpression(accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression) { return accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.kind === SyntaxKind.IndexedAccessType ? accessNode.indexType : - accessNode.kind === SyntaxKind.ComputedPropertyName ? accessNode.expression : - accessNode; + accessNode.kind === SyntaxKind.ComputedPropertyName ? accessNode.expression : + accessNode; } function isPatternLiteralPlaceholderType(type: Type): boolean { @@ -16211,7 +16213,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getSimplifiedType(type: Type, writing: boolean): Type { return type.flags & TypeFlags.IndexedAccess ? getSimplifiedIndexedAccessType(type as IndexedAccessType, writing) : type.flags & TypeFlags.Conditional ? getSimplifiedConditionalType(type as ConditionalType, writing) : - type; + type; } function distributeIndexOverObjectType(objectType: Type, indexType: Type, writing: boolean) { @@ -16992,7 +16994,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getRegularTypeOfLiteralType(type: Type): Type { return type.flags & TypeFlags.Literal ? (type as LiteralType).regularType : type.flags & TypeFlags.Union ? ((type as UnionType).regularType || ((type as UnionType).regularType = mapType(type, getRegularTypeOfLiteralType) as UnionType)) : - type; + type; } function isFreshLiteralType(type: Type) { @@ -17115,7 +17117,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getTypeFromNamedTupleTypeNode(node: NamedTupleMember): Type { const links = getNodeLinks(node); return links.resolvedType || (links.resolvedType = - node.dotDotDotToken ? getTypeFromRestTypeNode(node) : + node.dotDotDotToken ? getTypeFromRestTypeNode(node) : addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true, !!node.questionToken)); } @@ -17423,7 +17425,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getObjectTypeInstantiation(type: AnonymousType | DeferredTypeReference, mapper: TypeMapper, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]) { const declaration = type.objectFlags & ObjectFlags.Reference ? (type as TypeReference).node! : type.objectFlags & ObjectFlags.InstantiationExpressionType ? (type as InstantiationExpressionType).node : - type.symbol.declarations![0]; + type.symbol.declarations![0]; const links = getNodeLinks(declaration); const target = type.objectFlags & ObjectFlags.Reference ? links.resolvedType! as DeferredTypeReference : type.objectFlags & ObjectFlags.Instantiated ? type.target! : type; @@ -17463,7 +17465,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const newMapper = createTypeMapper(typeParameters, typeArguments); result = target.objectFlags & ObjectFlags.Reference ? createDeferredTypeReference((type as DeferredTypeReference).target, (type as DeferredTypeReference).node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & ObjectFlags.Mapped ? instantiateMappedType(target as MappedType, newMapper, newAliasSymbol, newAliasTypeArguments) : - instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); + instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } return result; @@ -17508,7 +17510,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { tpScope = tpDeclaration.parent; } else if (tp.isThisType) { - // Type parameter is the this type, and its declaration is the class declaration. + // Type parameter is the this type, and its declaration is the class declaration. tpScope = tpDeclaration; } else { @@ -17597,7 +17599,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const elementTypes = map(getTypeArguments(tupleType), (t, i) => { const singleton = elementFlags[i] & ElementFlags.Variadic ? t : elementFlags[i] & ElementFlags.Rest ? createArrayType(t) : - createTupleType([t], [elementFlags[i]]); + createTupleType([t], [elementFlags[i]]); // The singleton is never a generic tuple type, so it is safe to recurse here. return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper)); }); @@ -17618,7 +17620,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const modifiers = getMappedTypeModifiers(mappedType); const newTupleModifiers = modifiers & MappedTypeModifiers.IncludeOptional ? map(elementFlags, f => f & ElementFlags.Required ? ElementFlags.Optional : f) : modifiers & MappedTypeModifiers.ExcludeOptional ? map(elementFlags, f => f & ElementFlags.Optional ? ElementFlags.Required : f) : - elementFlags; + elementFlags; const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); return contains(elementTypes, errorType) ? errorType : createTupleType(elementTypes, newTupleModifiers, newReadonly, tupleType.target.labeledElementDeclarations); @@ -17630,7 +17632,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & MappedTypeModifiers.IncludeOptional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(propType, /*isProperty*/ true) : strictNullChecks && modifiers & MappedTypeModifiers.ExcludeOptional && isOptional ? getTypeWithFacts(propType, TypeFacts.NEUndefined) : - propType; + propType; } function instantiateAnonymousType(type: AnonymousType, mapper: TypeMapper, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): AnonymousType { @@ -17936,10 +17938,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isTypeDerivedFrom(source: Type, target: Type): boolean { return source.flags & TypeFlags.Union ? every((source as UnionType).types, t => isTypeDerivedFrom(t, target)) : target.flags & TypeFlags.Union ? some((target as UnionType).types, t => isTypeDerivedFrom(source, t)) : - source.flags & TypeFlags.InstantiableNonPrimitive ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : - target === globalObjectType ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) : - target === globalFunctionType ? !!(source.flags & TypeFlags.Object) && isFunctionObjectType(source as ObjectType) : - hasBaseType(source, getTargetType(target)) || (isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType)); + source.flags & TypeFlags.InstantiableNonPrimitive ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : + target === globalObjectType ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) : + target === globalFunctionType ? !!(source.flags & TypeFlags.Object) && isFunctionObjectType(source as ObjectType) : + hasBaseType(source, getTargetType(target)) || (isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType)); } /** @@ -17975,7 +17977,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkTypeRelatedToAndOptionallyElaborate( source: Type, target: Type, - relation: ESMap, + relation: Map, errorNode: Node | undefined, expr: Expression | undefined, headMessage: DiagnosticMessage | undefined, @@ -17997,7 +17999,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: Expression | undefined, source: Type, target: Type, - relation: ESMap, + relation: Map, headMessage: DiagnosticMessage | undefined, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined @@ -18034,7 +18036,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: Expression, source: Type, target: Type, - relation: ESMap, + relation: Map, headMessage: DiagnosticMessage | undefined, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined @@ -18063,7 +18065,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: ArrowFunction, source: Type, target: Type, - relation: ESMap, + relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined ): boolean { @@ -18150,7 +18152,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { iterator: ElaborationIterator, source: Type, target: Type, - relation: ESMap, + relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined ) { @@ -18219,7 +18221,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return reportedError; } - function *generateJsxAttributes(node: JsxAttributes): ElaborationIterator { + function* generateJsxAttributes(node: JsxAttributes): ElaborationIterator { if (!length(node.properties)) return; for (const prop of node.properties) { if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(idText(prop.name))) continue; @@ -18227,7 +18229,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - function *generateJsxChildren(node: JsxElement, getInvalidTextDiagnostic: () => DiagnosticMessage): ElaborationIterator { + function* generateJsxChildren(node: JsxElement, getInvalidTextDiagnostic: () => DiagnosticMessage): ElaborationIterator { if (!length(node.children)) return; let memberOffset = 0; for (let i = 0; i < node.children.length; i++) { @@ -18268,7 +18270,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: JsxAttributes, source: Type, target: Type, - relation: ESMap, + relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined ) { @@ -18313,7 +18315,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const elem = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); if (elem) { result = elaborateElementwise( - (function*() { yield elem; })(), + (function* () { yield elem; })(), source, target, relation, @@ -18352,7 +18354,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - function *generateLimitedTupleElements(node: ArrayLiteralExpression, target: Type): ElaborationIterator { + function* generateLimitedTupleElements(node: ArrayLiteralExpression, target: Type): ElaborationIterator { const len = length(node.elements); if (!len) return; for (let i = 0; i < len; i++) { @@ -18369,7 +18371,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: ArrayLiteralExpression, source: Type, target: Type, - relation: ESMap, + relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined ) { @@ -18394,7 +18396,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - function *generateObjectLiteralElements(node: ObjectLiteralExpression): ElaborationIterator { + function* generateObjectLiteralElements(node: ObjectLiteralExpression): ElaborationIterator { if (!length(node.properties)) return; for (const prop of node.properties) { if (isSpreadAssignment(prop)) continue; @@ -18422,7 +18424,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: ObjectLiteralExpression, source: Type, target: Type, - relation: ESMap, + relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined ) { @@ -18560,13 +18562,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // here and just use the `any` type directly const targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) - : getReturnTypeOfSignature(target); + : getReturnTypeOfSignature(target); if (targetReturnType === voidType || targetReturnType === anyType) { return result; } const sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) - : getReturnTypeOfSignature(source); + : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions const targetTypePredicate = getTypePredicateOfSignature(target); @@ -18624,7 +18626,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const related = source.type === target.type ? Ternary.True : source.type && target.type ? compareTypes(source.type, target.type, reportErrors) : - Ternary.False; + Ternary.False; if (related === Ternary.False && reportErrors) { errorReporter!(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } @@ -18659,9 +18661,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isEmptyObjectType(type: Type): boolean { return type.flags & TypeFlags.Object ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type as ObjectType)) : type.flags & TypeFlags.NonPrimitive ? true : - type.flags & TypeFlags.Union ? some((type as UnionType).types, isEmptyObjectType) : - type.flags & TypeFlags.Intersection ? every((type as UnionType).types, isEmptyObjectType) : - false; + type.flags & TypeFlags.Union ? some((type as UnionType).types, isEmptyObjectType) : + type.flags & TypeFlags.Intersection ? every((type as UnionType).types, isEmptyObjectType) : + false; } function isEmptyAnonymousObjectType(type: Type) { @@ -18727,7 +18729,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; } - function isSimpleTypeRelatedTo(source: Type, target: Type, relation: ESMap, errorReporter?: ErrorReporter) { + function isSimpleTypeRelatedTo(source: Type, target: Type, relation: Map, errorReporter?: ErrorReporter) { const s = source.flags; const t = target.flags; if (t & TypeFlags.AnyOrUnknown || s & TypeFlags.Never || source === wildcardType) return true; @@ -18768,7 +18770,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } - function isTypeRelatedTo(source: Type, target: Type, relation: ESMap) { + function isTypeRelatedTo(source: Type, target: Type, relation: Map) { if (isFreshLiteralType(source)) { source = (source as FreshableType).regularType; } @@ -18808,10 +18810,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { while (true) { const t = isFreshLiteralType(type) ? (type as FreshableType).regularType : getObjectFlags(type) & ObjectFlags.Reference ? (type as TypeReference).node ? createTypeReference((type as TypeReference).target, getTypeArguments(type as TypeReference)) : getSingleBaseForNonAugmentingSubtype(type) || type : - type.flags & TypeFlags.UnionOrIntersection ? getNormalizedUnionOrIntersectionType(type as UnionOrIntersectionType, writing) : - type.flags & TypeFlags.Substitution ? writing ? (type as SubstitutionType).baseType : getSubstitutionIntersection(type as SubstitutionType) : - type.flags & TypeFlags.Simplifiable ? getSimplifiedType(type, writing) : - type; + type.flags & TypeFlags.UnionOrIntersection ? getNormalizedUnionOrIntersectionType(type as UnionOrIntersectionType, writing) : + type.flags & TypeFlags.Substitution ? writing ? (type as SubstitutionType).baseType : getSubstitutionIntersection(type as SubstitutionType) : + type.flags & TypeFlags.Simplifiable ? getSimplifiedType(type, writing) : + type; if (t === type) return t; type = t; } @@ -18845,7 +18847,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkTypeRelatedTo( source: Type, target: Type, - relation: ESMap, + relation: Map, errorNode: Node | undefined, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined, @@ -19007,12 +19009,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else { const prefix = (msg.code === Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) - ? "new " - : ""; + ? "new " + : ""; const params = (msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) - ? "" - : "..."; + ? "" + : "..."; path = `${prefix}${path}(${params})`; } break; @@ -19234,7 +19236,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const types = (target as UnionType).types; const candidate = types.length === 2 && types[0].flags & TypeFlags.Nullable ? types[1] : types.length === 3 && types[0].flags & TypeFlags.Nullable && types[1].flags & TypeFlags.Nullable ? types[2] : - undefined; + undefined; if (candidate && !(candidate.flags & TypeFlags.Nullable)) { target = getNormalizedType(candidate, /*writing*/ true); if (source === target) return Ternary.True; @@ -19821,7 +19823,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` if (!result && (source.flags & TypeFlags.Intersection || source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.Union)) { - const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types: [source], !!(target.flags & TypeFlags.Union)); + const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types : [source], !!(target.flags & TypeFlags.Union)); if (constraint && everyType(constraint, c => c !== source)) { // Skip comparison if expansion contains the source itself // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this result = isRelatedTo(constraint, target, RecursionFlags.Source, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); @@ -21074,7 +21076,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (const targetInfo of indexInfos) { const related = !sourceIsPrimitive && targetHasStringIndex && targetInfo.type.flags & TypeFlags.Any ? Ternary.True : isGenericMappedType(source) && targetHasStringIndex ? isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, RecursionFlags.Both, reportErrors) : - typeRelatedToIndexInfo(source, targetInfo, reportErrors, intersectionState); + typeRelatedToIndexInfo(source, targetInfo, reportErrors, intersectionState); if (!related) { return Ternary.False; } @@ -21334,7 +21336,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getVarianceModifiers(tp: TypeParameter): ModifierFlags { return (some(tp.symbol?.declarations, d => hasSyntacticModifier(d, ModifierFlags.In)) ? ModifierFlags.In : 0) | - (some(tp.symbol?.declarations, d => hasSyntacticModifier(d, ModifierFlags.Out)) ? ModifierFlags.Out: 0); + (some(tp.symbol?.declarations, d => hasSyntacticModifier(d, ModifierFlags.Out)) ? ModifierFlags.Out : 0); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. @@ -21399,7 +21401,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source: Type, target: Type, intersectionState: IntersectionState, relation: ESMap, ignoreConstraints: boolean) { + function getRelationKey(source: Type, target: Type, intersectionState: IntersectionState, relation: Map, ignoreConstraints: boolean) { if (relation === identityRelation && source.id > target.id) { const temp = source; source = target; @@ -21658,8 +21660,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function compareTypePredicatesIdentical(source: TypePredicate | undefined, target: TypePredicate | undefined, compareTypes: (s: Type, t: Type) => Ternary): Ternary { return !(source && target && typePredicateKindsMatch(source, target)) ? Ternary.False : source.type === target.type ? Ternary.True : - source.type && target.type ? compareTypes(source.type, target.type) : - Ternary.False; + source.type && target.type ? compareTypes(source.type, target.type) : + Ternary.False; } function literalTypesWithSameBaseType(types: Type[]): boolean { @@ -21806,17 +21808,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isLiteralType(type: Type): boolean { return type.flags & TypeFlags.Boolean ? true : type.flags & TypeFlags.Union ? type.flags & TypeFlags.EnumLiteral ? true : every((type as UnionType).types, isUnitType) : - isUnitType(type); + isUnitType(type); } function getBaseTypeOfLiteralType(type: Type): Type { return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type as LiteralType) : type.flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? stringType : - type.flags & TypeFlags.NumberLiteral ? numberType : - type.flags & TypeFlags.BigIntLiteral ? bigintType : - type.flags & TypeFlags.BooleanLiteral ? booleanType : - type.flags & TypeFlags.Union ? getBaseTypeOfLiteralTypeUnion(type as UnionType) : - type; + type.flags & TypeFlags.NumberLiteral ? numberType : + type.flags & TypeFlags.BigIntLiteral ? bigintType : + type.flags & TypeFlags.BooleanLiteral ? booleanType : + type.flags & TypeFlags.Union ? getBaseTypeOfLiteralTypeUnion(type as UnionType) : + type; } function getBaseTypeOfLiteralTypeUnion(type: UnionType) { @@ -21827,17 +21829,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getWidenedLiteralType(type: Type): Type { return type.flags & TypeFlags.EnumLiteral && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type as LiteralType) : type.flags & TypeFlags.StringLiteral && isFreshLiteralType(type) ? stringType : - type.flags & TypeFlags.NumberLiteral && isFreshLiteralType(type) ? numberType : - type.flags & TypeFlags.BigIntLiteral && isFreshLiteralType(type) ? bigintType : - type.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(type) ? booleanType : - type.flags & TypeFlags.Union ? mapType(type as UnionType, getWidenedLiteralType) : - type; + type.flags & TypeFlags.NumberLiteral && isFreshLiteralType(type) ? numberType : + type.flags & TypeFlags.BigIntLiteral && isFreshLiteralType(type) ? bigintType : + type.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(type) ? booleanType : + type.flags & TypeFlags.Union ? mapType(type as UnionType, getWidenedLiteralType) : + type; } function getWidenedUniqueESSymbolType(type: Type): Type { return type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : type.flags & TypeFlags.Union ? mapType(type as UnionType, getWidenedUniqueESSymbolType) : - type; + type; } function getWidenedLiteralLikeTypeForContextualType(type: Type, contextualType: Type | undefined) { @@ -21851,7 +21853,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (type && isUnitType(type)) { const contextualType = !contextualSignatureReturnType ? undefined : isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) : - contextualSignatureReturnType; + contextualSignatureReturnType; type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); } return type; @@ -21910,7 +21912,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { every(t1.target.elementFlags, (f, i) => (f & ElementFlags.Variable) === (t2.target.elementFlags[i] & ElementFlags.Variable)); } - function isZeroBigInt({value}: BigIntLiteralType) { + function isZeroBigInt({ value }: BigIntLiteralType) { return value.base10Value === "0"; } @@ -21925,14 +21927,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getDefinitelyFalsyPartOfType(type: Type): Type { return type.flags & TypeFlags.String ? emptyStringType : type.flags & TypeFlags.Number ? zeroType : - type.flags & TypeFlags.BigInt ? zeroBigIntType : - type === regularFalseType || - type === falseType || - type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null | TypeFlags.AnyOrUnknown) || - type.flags & TypeFlags.StringLiteral && (type as StringLiteralType).value === "" || - type.flags & TypeFlags.NumberLiteral && (type as NumberLiteralType).value === 0 || - type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type as BigIntLiteralType) ? type : - neverType; + type.flags & TypeFlags.BigInt ? zeroBigIntType : + type === regularFalseType || + type === falseType || + type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null | TypeFlags.AnyOrUnknown) || + type.flags & TypeFlags.StringLiteral && (type as StringLiteralType).value === "" || + type.flags & TypeFlags.NumberLiteral && (type as NumberLiteralType).value === 0 || + type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type as BigIntLiteralType) ? type : + neverType; } /** @@ -21944,8 +21946,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const missing = (flags & ~type.flags) & (TypeFlags.Undefined | TypeFlags.Null); return missing === 0 ? type : missing === TypeFlags.Undefined ? getUnionType([type, undefinedType]) : - missing === TypeFlags.Null ? getUnionType([type, nullType]) : - getUnionType([type, undefinedType, nullType]); + missing === TypeFlags.Null ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); } function getOptionalType(type: Type, isProperty = false): Type { @@ -21982,7 +21984,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getOptionalExpressionType(exprType: Type, expression: Expression) { return isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : - exprType; + exprType; } function removeMissingType(type: Type, isOptional: boolean) { @@ -22272,7 +22274,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.indexOf(param) > -1 && (resolveName(param, param.name.escapedText, SymbolFlags.Type, undefined, param.name.escapedText, /*isUse*/ true) || - param.name.originalKeywordKind && isTypeNodeKind(param.name.originalKeywordKind))) { + param.name.originalKeywordKind && isTypeNodeKind(param.name.originalKeywordKind))) { const newName = "arg" + param.parent.parameters.indexOf(param); const typeName = declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); @@ -22310,7 +22312,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } diagnostic = !noImplicitAny ? Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : wideningKind === WideningKind.GeneratorYield ? Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : - Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case SyntaxKind.MappedType: if (noImplicitAny) { @@ -22658,7 +22660,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getTypeFromInference(inference: InferenceInfo) { return inference.candidates ? getUnionType(inference.candidates, UnionReduction.Subtype) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : - undefined; + undefined; } function hasSkipDirectInferenceFlag(node: Node) { @@ -22775,8 +22777,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return source.flags & TypeFlags.StringLiteral ? inferFromLiteralPartsToTemplateLiteral([(source as StringLiteralType).value], emptyArray, target) : source.flags & TypeFlags.TemplateLiteral ? arraysEqual((source as TemplateLiteralType).texts, target.texts) ? map((source as TemplateLiteralType).types, getStringLikeTypeForType) : - inferFromLiteralPartsToTemplateLiteral((source as TemplateLiteralType).texts, (source as TemplateLiteralType).types, target) : - undefined; + inferFromLiteralPartsToTemplateLiteral((source as TemplateLiteralType).texts, (source as TemplateLiteralType).types, target) : + undefined; } function isTypeMatchedByTemplateLiteralType(source: Type, target: TemplateLiteralType): boolean { @@ -22868,7 +22870,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let propagationType: Type; let inferencePriority: number = InferencePriority.MaxValue; let allowComplexConstraintInference = true; - let visited: ESMap; + let visited: Map; let sourceStack: object[]; let targetStack: object[]; let expandingFlags = ExpandingFlags.None; @@ -23387,20 +23389,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // for each type in the constraint, find the highest priority matching type const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : - left.flags & TypeFlags.String ? left : right.flags & TypeFlags.String ? source : - left.flags & TypeFlags.TemplateLiteral ? left : right.flags & TypeFlags.TemplateLiteral && isTypeMatchedByTemplateLiteralType(source, right as TemplateLiteralType) ? source : - left.flags & TypeFlags.StringMapping ? left : right.flags & TypeFlags.StringMapping && str === applyStringMapping(right.symbol, str) ? source : - left.flags & TypeFlags.StringLiteral ? left : right.flags & TypeFlags.StringLiteral && (right as StringLiteralType).value === str ? right : - left.flags & TypeFlags.Number ? left : right.flags & TypeFlags.Number ? getNumberLiteralType(+str) : - left.flags & TypeFlags.Enum ? left : right.flags & TypeFlags.Enum ? getNumberLiteralType(+str) : - left.flags & TypeFlags.NumberLiteral ? left : right.flags & TypeFlags.NumberLiteral && (right as NumberLiteralType).value === +str ? right : - left.flags & TypeFlags.BigInt ? left : right.flags & TypeFlags.BigInt ? parseBigIntLiteralType(str) : - left.flags & TypeFlags.BigIntLiteral ? left : right.flags & TypeFlags.BigIntLiteral && pseudoBigIntToString((right as BigIntLiteralType).value) === str ? right : - left.flags & TypeFlags.Boolean ? left : right.flags & TypeFlags.Boolean ? str === "true" ? trueType : str === "false" ? falseType : booleanType : - left.flags & TypeFlags.BooleanLiteral ? left : right.flags & TypeFlags.BooleanLiteral && (right as IntrinsicType).intrinsicName === str ? right : - left.flags & TypeFlags.Undefined ? left : right.flags & TypeFlags.Undefined && (right as IntrinsicType).intrinsicName === str ? right : - left.flags & TypeFlags.Null ? left : right.flags & TypeFlags.Null && (right as IntrinsicType).intrinsicName === str ? right : - left, + left.flags & TypeFlags.String ? left : right.flags & TypeFlags.String ? source : + left.flags & TypeFlags.TemplateLiteral ? left : right.flags & TypeFlags.TemplateLiteral && isTypeMatchedByTemplateLiteralType(source, right as TemplateLiteralType) ? source : + left.flags & TypeFlags.StringMapping ? left : right.flags & TypeFlags.StringMapping && str === applyStringMapping(right.symbol, str) ? source : + left.flags & TypeFlags.StringLiteral ? left : right.flags & TypeFlags.StringLiteral && (right as StringLiteralType).value === str ? right : + left.flags & TypeFlags.Number ? left : right.flags & TypeFlags.Number ? getNumberLiteralType(+str) : + left.flags & TypeFlags.Enum ? left : right.flags & TypeFlags.Enum ? getNumberLiteralType(+str) : + left.flags & TypeFlags.NumberLiteral ? left : right.flags & TypeFlags.NumberLiteral && (right as NumberLiteralType).value === +str ? right : + left.flags & TypeFlags.BigInt ? left : right.flags & TypeFlags.BigInt ? parseBigIntLiteralType(str) : + left.flags & TypeFlags.BigIntLiteral ? left : right.flags & TypeFlags.BigIntLiteral && pseudoBigIntToString((right as BigIntLiteralType).value) === str ? right : + left.flags & TypeFlags.Boolean ? left : right.flags & TypeFlags.Boolean ? str === "true" ? trueType : str === "false" ? falseType : booleanType : + left.flags & TypeFlags.BooleanLiteral ? left : right.flags & TypeFlags.BooleanLiteral && (right as IntrinsicType).intrinsicName === str ? right : + left.flags & TypeFlags.Undefined ? left : right.flags & TypeFlags.Undefined && (right as IntrinsicType).intrinsicName === str ? right : + left.flags & TypeFlags.Null ? left : right.flags & TypeFlags.Null && (right as IntrinsicType).intrinsicName === str ? right : + left, neverType as Type); if (!(matchingType.flags & TypeFlags.Never)) { @@ -23625,7 +23627,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); const baseCandidates = primitiveConstraint ? sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? sameMap(candidates, getWidenedLiteralType) : - candidates; + candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. const unwidenedType = inference.priority! & InferencePriority.PriorityImpliesCombination ? @@ -23747,7 +23749,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isCallExpression(node.parent)) { return Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function; } - // falls through + // falls through default: if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; @@ -23794,7 +23796,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const symbol = getResolvedSymbol(node as Identifier); return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : undefined; } - // falls through + // falls through case SyntaxKind.ThisKeyword: return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`; case SyntaxKind.NonNullExpression: @@ -23842,8 +23844,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return isThisInTypeQuery(source) ? target.kind === SyntaxKind.ThisKeyword : target.kind === SyntaxKind.Identifier && getResolvedSymbol(source as Identifier) === getResolvedSymbol(target as Identifier) || - (target.kind === SyntaxKind.VariableDeclaration || target.kind === SyntaxKind.BindingElement) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source as Identifier)) === getSymbolOfNode(target); + (target.kind === SyntaxKind.VariableDeclaration || target.kind === SyntaxKind.BindingElement) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source as Identifier)) === getSymbolOfNode(target); case SyntaxKind.ThisKeyword: return target.kind === SyntaxKind.ThisKeyword; case SyntaxKind.SuperKeyword: @@ -24223,12 +24225,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (strictNullChecks) { switch (facts) { case TypeFacts.NEUndefined: - return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefined ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQNull && !maybeTypeOfKind(reduced, TypeFlags.Null) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]): t); + return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefined ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQNull && !maybeTypeOfKind(reduced, TypeFlags.Null) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t); case TypeFacts.NENull: - return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQNull ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQUndefined && !maybeTypeOfKind(reduced, TypeFlags.Undefined) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]): t); + return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQNull ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQUndefined && !maybeTypeOfKind(reduced, TypeFlags.Undefined) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t); case TypeFacts.NEUndefinedOrNull: case TypeFacts.Truthy: - return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefinedOrNull ? getGlobalNonNullableTypeInstantiation(t): t); + return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefinedOrNull ? getGlobalNonNullableTypeInstantiation(t) : t); } } return reduced; @@ -24551,9 +24553,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping | TypeFlags.NumberLiteral | TypeFlags.BigIntLiteral)) { return mapType(typeWithPrimitives, t => t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) : - isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? extractTypesOfKind(typeWithLiterals, TypeFlags.StringLiteral) : - t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : - t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t); + isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? extractTypesOfKind(typeWithLiterals, TypeFlags.StringLiteral) : + t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : + t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t); } return typeWithPrimitives; } @@ -24748,7 +24750,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, SignatureKind.Call); const candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : - undefined; + undefined; signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature; } return signature === unknownSignature ? undefined : signature; @@ -25129,7 +25131,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType)); const narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : predicate.kind === TypePredicateKind.AssertsIdentifier && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : - type; + type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } if (getReturnTypeOfSignature(signature).flags & TypeFlags.Never) { @@ -25453,7 +25455,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (candidate) { return operator === (assumeTrue ? SyntaxKind.EqualsEqualsEqualsToken : SyntaxKind.ExclamationEqualsEqualsToken) ? candidate : isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? removeType(type, candidate) : - type; + type; } } } @@ -25735,7 +25737,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const discriminantType = getUnionType(clauseTypes); const caseType = discriminantType.flags & TypeFlags.Never ? neverType : - replacePrimitivesWithLiterals(filterType(type, t => areTypesComparable(discriminantType, t)), discriminantType); + replacePrimitivesWithLiterals(filterType(type, t => areTypesComparable(discriminantType, t)), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -25764,14 +25766,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, // but are classified as "function" according to `typeof`. isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : - // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied - // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. - isTypeSubtypeOf(impliedType, t) ? impliedType : - // Neither the constituent nor the implied type is a subtype of the other, however their domains may still - // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate - // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. - getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : - neverType); + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType); } function narrowTypeBySwitchOnTypeOf(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): Type { @@ -25929,9 +25931,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // based on assignability, or as a last resort produce an intersection. return !(narrowedType.flags & TypeFlags.Never) ? narrowedType : isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type { @@ -26000,7 +26002,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } } - // falls through + // falls through case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: case SyntaxKind.PropertyAccessExpression: @@ -26137,7 +26139,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { parent.kind === SyntaxKind.QualifiedName || parent.kind === SyntaxKind.CallExpression && (parent as CallExpression).expression === node || parent.kind === SyntaxKind.ElementAccessExpression && (parent as ElementAccessExpression).expression === node && - !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression((parent as ElementAccessExpression).argumentExpression))); + !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression((parent as ElementAccessExpression).argumentExpression))); } function isGenericTypeWithUnionConstraint(type: Type): boolean { @@ -26392,10 +26394,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { const assignmentError = localOrExportSymbol.flags & SymbolFlags.Enum ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum : localOrExportSymbol.flags & SymbolFlags.Class ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class - : localOrExportSymbol.flags & SymbolFlags.Module ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace - : localOrExportSymbol.flags & SymbolFlags.Function ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function - : localOrExportSymbol.flags & SymbolFlags.Alias ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import - : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + : localOrExportSymbol.flags & SymbolFlags.Module ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & SymbolFlags.Function ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & SymbolFlags.Alias ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; error(node, assignmentError, symbolToString(symbol)); return errorType; @@ -26455,13 +26457,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // declaration container are the same). const assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void)) !== 0 || - isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || + isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || node.parent.kind === SyntaxKind.NonNullExpression || declaration.kind === SyntaxKind.VariableDeclaration && (declaration as VariableDeclaration).exclamationToken || declaration.flags & NodeFlags.Ambient; const initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration as VariableLikeDeclaration) : type) : type === autoType || type === autoArrayType ? undefinedType : - getOptionalType(type); + getOptionalType(type); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -26630,7 +26632,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function findFirstSuperCall(node: Node): SuperCall | undefined { return isSuperCall(node) ? node : isFunctionLike(node) ? undefined : - forEachChild(node, findFirstSuperCall); + forEachChild(node, findFirstSuperCall); } /** @@ -26662,7 +26664,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression: Node, container: Node) { if (isPropertyDeclaration(container) && hasStaticModifier(container) && container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) { - error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); + error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -27088,7 +27090,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { func.kind === SyntaxKind.GetAccessor || func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent as ObjectLiteralExpression : - undefined; + undefined; } function getThisTypeArgument(type: Type): Type | undefined { @@ -27374,7 +27376,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isImportCall(callTarget)) { return argIndex === 0 ? stringType : argIndex === 1 ? getGlobalImportCallOptionsType(/*reportErrors*/ false) : - anyType; + anyType; } // If we're already in the process of resolving the given signature, don't resolve again as @@ -27429,7 +27431,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * Try to find a resolved symbol for an expression without also resolving its type, as * getSymbolAtLocation would (as that could be reentrant into contextual typing) */ - function getSymbolForExpression(e: Expression) { + function getSymbolForExpression(e: Expression) { if (e.symbol) { return e.symbol; } @@ -27764,7 +27766,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); return apparentType.flags & TypeFlags.Union && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType as UnionType) : apparentType.flags & TypeFlags.Union && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType as UnionType) : - apparentType; + apparentType; } } @@ -27879,7 +27881,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const tag = isInJSFile(parent) ? getJSDocTypeTag(parent) : undefined; return !tag ? getContextualType(parent as ParenthesizedExpression, contextFlags) : isJSDocTypeTag(tag) && isConstTypeReference(tag.typeExpression.type) ? tryFindWhenConstTypeReference(parent as ParenthesizedExpression) : - getTypeFromTypeNode(tag.typeExpression.type); + getTypeFromTypeNode(tag.typeExpression.type); } case SyntaxKind.NonNullExpression: return getContextualType(parent as NonNullExpression, contextFlags); @@ -28056,8 +28058,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { signatures, (left, right) => left === right || !left ? left - : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) - : undefined) + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined) : undefined; } @@ -28098,8 +28100,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const paramName = leftName === rightName ? leftName : !leftName ? rightName : - !rightName ? leftName : - undefined; + !rightName ? leftName : + undefined; const paramSymbol = createSymbol( SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0), paramName || `arg${i}` as __String @@ -28460,7 +28462,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : - checkObjectLiteralMethod(memberDecl, checkMode); + checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { @@ -28821,7 +28823,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const childrenPropSymbol = createSymbol(SymbolFlags.Property, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : - createArrayType(getUnionType(childrenTypes)); + createArrayType(getUnionType(childrenTypes)); // Fake up a property declaration for the children childrenPropSymbol.valueDeclaration = factory.createPropertySignature(/*modifiers*/ undefined, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined); setParent(childrenPropSymbol.valueDeclaration, attributes); @@ -28958,8 +28960,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic; const errorMessage = isClassic - ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option - : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; + ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option + : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; const mod = resolveExternalModule(location!, runtimeImportSpecifier, errorMessage, location!); const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : undefined; if (links) { @@ -29239,7 +29241,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (isNodeOpeningLikeElement) { - const jsxOpeningLikeNode = node ; + const jsxOpeningLikeNode = node; const sig = getResolvedSignature(jsxOpeningLikeNode); checkDeprecatedSignature(sig, node); checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); @@ -29336,8 +29338,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const errorNode = !reportError ? undefined : node.kind === SyntaxKind.QualifiedName ? node.right : - node.kind === SyntaxKind.ImportType ? node : - node.kind === SyntaxKind.BindingElement && node.propertyName ? node.propertyName : node.name; + node.kind === SyntaxKind.ImportType ? node : + node.kind === SyntaxKind.BindingElement && node.propertyName ? node.propertyName : node.name; return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode); } @@ -30126,7 +30128,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const properties = getPropertiesOfType(containingType); const jsxSpecific = strName === "for" ? find(properties, x => symbolName(x) === "htmlFor") : strName === "class" ? find(properties, x => symbolName(x) === "className") - : undefined; + : undefined; return jsxSpecific ?? getSpellingSuggestionForName(strName, properties, SymbolFlags.Value); } @@ -30343,8 +30345,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // A #private property access in an optional chain is an error dealt with by the parser. - // The checker does not check for it, so we need to do our own check here. - if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) { + // The checker does not check for it, so we need to do our own check here. + if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) { const declClass = getContainingClass(property.valueDeclaration); return !isOptionalChain(node) && !!findAncestor(node, parent => parent === declClass); } @@ -30676,7 +30678,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const thisArgumentType = checkExpression(thisArgumentNode); return isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : - thisArgumentType; + thisArgumentType; } function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: readonly Expression[], checkMode: CheckMode, context: InferenceContext): Type[] { @@ -30775,8 +30777,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getMutableArrayOrTupleType(type: Type) { return type.flags & TypeFlags.Union ? mapType(type, getMutableArrayOrTupleType) : type.flags & TypeFlags.Any || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : - isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) : - createTupleType([type], [ElementFlags.Variadic]); + isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) : + createTupleType([type], [ElementFlags.Variadic]); } function getSpreadArgumentType(args: readonly Expression[], index: number, argCount: number, restType: Type, context: InferenceContext | undefined, checkMode: CheckMode) { @@ -30870,7 +30872,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkApplicableSignatureForJsxOpeningLikeElement( node: JsxOpeningLikeElement, signature: Signature, - relation: ESMap, + relation: Map, checkMode: CheckMode, reportErrors: boolean, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, @@ -30973,7 +30975,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: CallLikeExpression, args: readonly Expression[], signature: Signature, - relation: ESMap, + relation: Map, checkMode: CheckMode, reportErrors: boolean, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, @@ -31025,8 +31027,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const restArgCount = args.length - argCount; const errorNode = !reportErrors ? undefined : restArgCount === 0 ? node : - restArgCount === 1 ? args[argCount] : - setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end); + restArgCount === 1 ? args[argCount] : + setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end); if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) { Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors"); maybeAddMissingAwaitInfo(errorNode, spreadType, restType); @@ -31247,7 +31249,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const hasRestParameter = some(signatures, hasEffectiveRestParameter); const parameterRange = hasRestParameter ? min : min < max ? min + "-" + max - : min; + : min; const isVoidPromiseError = !hasRestParameter && parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node); if (isVoidPromiseError && isInJSFile(node)) { return getDiagnosticForCallNode(node, Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments); @@ -31270,7 +31272,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { parameter, isBindingPattern(parameter.name) ? Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : isRestParameter(parameter) ? Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided - : Diagnostics.An_argument_for_0_was_not_provided, + : Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !isBindingPattern(parameter.name) ? idText(getFirstIdentifier(parameter.name)) : undefined ); return addRelatedInfo(diagnostic, parameterError); @@ -31297,7 +31299,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const sig = signatures[0]; const min = getMinTypeArgumentCount(sig.typeParameters); const max = length(sig.typeParameters); - return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min , argCount); + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min, argCount); } // Overloads exist let belowArgCount = -Infinity; @@ -31537,7 +31539,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { candidateForTypeArgumentError = oldCandidateForTypeArgumentError; } - function chooseOverload(candidates: Signature[], relation: ESMap, isSingleNonGenericCandidate: boolean, signatureHelpTrailingComma = false) { + function chooseOverload(candidates: Signature[], relation: Map, isSingleNonGenericCandidate: boolean, signatureHelpTrailingComma = false) { candidatesForArgumentError = undefined; candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; @@ -31775,7 +31777,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const nonOptionalType = getOptionalExpressionType(funcType, node.expression); callChainFlags = nonOptionalType === funcType ? SignatureFlags.None : isOutermostOptionalChain(node) ? SignatureFlags.IsOuterCallChain : - SignatureFlags.IsInnerCallChain; + SignatureFlags.IsInnerCallChain; funcType = nonOptionalType; } else { @@ -32368,7 +32370,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : (isVariableDeclaration(node) || isPropertyAssignment(node)) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : - undefined; + undefined; if (func) { // If the node has a @class or @constructor tag, treat it like a constructor. if (getJSDocClassTag(node)) return true; @@ -32630,7 +32632,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (esModuleSymbol) { return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || - getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) ); } } @@ -32799,7 +32801,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkGrammarExpressionWithTypeArguments(node); const exprType = node.kind === SyntaxKind.ExpressionWithTypeArguments ? checkExpression(node.expression) : isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : - checkExpression(node.exprName); + checkExpression(node.exprName); const typeArguments = node.typeArguments; if (exprType === silentNeverType || isErrorType(exprType) || !some(typeArguments)) { return exprType; @@ -33373,7 +33375,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); const contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, IterationTypeKind.Yield, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, IterationTypeKind.Return, isAsync); @@ -33947,14 +33949,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ); break; } - // fallthrough + // fallthrough case ModuleKind.ES2022: case ModuleKind.ESNext: case ModuleKind.System: if (languageVersion >= ScriptTarget.ES2017) { break; } - // fallthrough + // fallthrough default: span ??= getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add( @@ -34039,7 +34041,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const facts = getTypeFacts(operandType) & (TypeFacts.Truthy | TypeFacts.Falsy); return facts === TypeFacts.Truthy ? falseType : facts === TypeFacts.Falsy ? trueType : - booleanType; + booleanType; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), @@ -34266,7 +34268,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). const possiblyOutOfBoundsType = checkIteratedTypeOrElementType(IterationUse.Destructuring | IterationUse.PossiblyOutOfBounds, sourceType, undefinedType, node) || errorType; - let inBoundsType: Type | undefined = compilerOptions.noUncheckedIndexedAccess ? undefined: possiblyOutOfBoundsType; + let inBoundsType: Type | undefined = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (let i = 0; i < elements.length; i++) { let type = possiblyOutOfBoundsType; if (node.elements[i].kind === SyntaxKind.SpreadElement) { @@ -34411,7 +34413,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } return isSideEffectFree((node as BinaryExpression).left) && - isSideEffectFree((node as BinaryExpression).right); + isSideEffectFree((node as BinaryExpression).right); case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: @@ -34872,8 +34874,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkForDisallowedESSymbolOperand(operator: SyntaxKind): boolean { const offendingSymbolOperand = maybeTypeOfKindConsideringBaseConstraint(leftType, TypeFlags.ESSymbolLike) ? left : - maybeTypeOfKindConsideringBaseConstraint(rightType, TypeFlags.ESSymbolLike) ? right : - undefined; + maybeTypeOfKindConsideringBaseConstraint(rightType, TypeFlags.ESSymbolLike) ? right : + undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator)); @@ -35037,7 +35039,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { effectiveLeft = leftBase; effectiveRight = rightBase; } - return [ effectiveLeft, effectiveRight ]; + return [effectiveLeft, effectiveRight]; } function checkYieldExpression(node: YieldExpression): Type { @@ -35297,7 +35299,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); } function checkPropertyAssignment(node: PropertyAssignment, checkMode?: CheckMode): Type { @@ -35663,7 +35665,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if ((node as CallExpression).expression.kind === SyntaxKind.ImportKeyword) { return checkImportCallExpression(node as ImportCall); } - // falls through + // falls through case SyntaxKind.NewExpression: return checkCallExpression(node as CallExpression, checkMode); case SyntaxKind.TaggedTemplateExpression: @@ -35857,7 +35859,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let hasReportedError = false; for (const { name } of parent.parameters) { if (isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -36023,8 +36025,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const privateStaticFlags = isPrivate && isStaticMember ? DeclarationMeaning.PrivateStatic : 0; const names = isPrivate ? privateIdentifiers : - isStaticMember ? staticNames : - instanceNames; + isStaticMember ? staticNames : + instanceNames; const memberName = name && getPropertyNameForPropertyNameNode(name); if (memberName) { @@ -36304,7 +36306,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const superCallShouldBeRootLevel = (getEmitScriptTarget(compilerOptions) !== ScriptTarget.ESNext || !useDefineForClassFields) && (some((node.parent as ClassDeclaration).members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); + some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); if (superCallShouldBeRootLevel) { // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional @@ -36954,10 +36956,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { forEach(declarations, declaration => { const diagnostic = declaration.kind === SyntaxKind.ClassDeclaration - ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 - : declaration.kind === SyntaxKind.FunctionDeclaration - ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient - : undefined; + ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 + : declaration.kind === SyntaxKind.FunctionDeclaration + ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient + : undefined; if (diagnostic) { addRelatedInfo( error(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)), @@ -37107,12 +37109,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ImportSpecifier: // https://github.com/Microsoft/TypeScript/pull/7591 case SyntaxKind.Identifier: // https://github.com/microsoft/TypeScript/issues/36098 - // Identifiers are used as declarations of assignment declarations whose parents may be - // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` - // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it) - // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;` - // all of which are pretty much always values, or at least imply a value meaning. - // It may be apprpriate to treat these as aliases in the future. + // Identifiers are used as declarations of assignment declarations whose parents may be + // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` + // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it) + // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;` + // all of which are pretty much always values, or at least imply a value meaning. + // It may be apprpriate to treat these as aliases in the future. return DeclarationSpaces.ExportValue; default: return Debug.failBadSyntaxKind(d); @@ -37259,7 +37261,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function unwrapAwaitedType(type: Type) { return type.flags & TypeFlags.Union ? mapType(type, unwrapAwaitedType) : isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : - type; + type; } function isAwaitedTypeNeeded(type: Type) { @@ -38132,7 +38134,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return !(getMergedSymbol(typeParameter.symbol).isReferenced! & SymbolFlags.TypeParameter) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); } - function addToGroup(map: ESMap, key: K, value: V, getKey: (key: K) => number | string): void { + function addToGroup(map: Map, key: K, value: V, getKey: (key: K) => number | string): void { const keyString = String(getKey(key)); const group = map.get(keyString); if (group) { @@ -38620,10 +38622,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isBindingElement(node)) { if ( - node.propertyName && - isIdentifier(node.name) && - isParameterDeclaration(node) && - nodeIsMissing((getContainingFunction(node) as FunctionLikeDeclaration).body)) { + node.propertyName && + isIdentifier(node.name) && + isParameterDeclaration(node) && + nodeIsMissing((getContainingFunction(node) as FunctionLikeDeclaration).body)) { // type F = ({a: string}) => void; // ^^^^^^ // variable renaming in function type notation is confusing, @@ -38865,8 +38867,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const testedNode = isIdentifier(location) ? location : isPropertyAccessExpression(location) ? location.name - : isBinaryExpression(location) && isIdentifier(location.right) ? location.right - : undefined; + : isBinaryExpression(location) && isIdentifier(location.right) ? location.right + : undefined; const testedSymbol = testedNode && getSymbolAtLocation(testedNode); if (!testedSymbol && !isPromise) { return; @@ -39159,10 +39161,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (iterationTypes) { const diagnostic = use & IterationUse.ForOfFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 : - use & IterationUse.SpreadFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 : - use & IterationUse.DestructuringFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 : - use & IterationUse.YieldStarFlag ? Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 : - undefined; + use & IterationUse.SpreadFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 : + use & IterationUse.DestructuringFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 : + use & IterationUse.YieldStarFlag ? Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 : + undefined; if (diagnostic) { checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic); } @@ -39633,7 +39635,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { errorNode.parent.expression === errorNode && getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false) - )); + )); return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } @@ -39978,7 +39980,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const container = getContainingFunctionOrClassStaticBlock(node); - if(container && isClassStaticBlockDeclaration(container)) { + if (container && isClassStaticBlockDeclaration(container)) { grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block); return; } @@ -41295,7 +41297,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isInfinityOrNaNString((expr as Identifier).escapedText)) { return +((expr as Identifier).escapedText); } - // falls through + // falls through case SyntaxKind.PropertyAccessExpression: if (isEntityNameExpression(expr)) { const symbol = resolveEntityName(expr, SymbolFlags.Value, /*ignoreErrors*/ true); @@ -41577,7 +41579,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } break; } - // falls through + // falls through case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.FunctionDeclaration: @@ -41670,8 +41672,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isInJSFile(node) && !(target.flags & SymbolFlags.Value) && !isTypeOnlyImportOrExportDeclaration(node)) { const errorNode = isImportOrExportSpecifier(node) ? node.propertyName || node.name : - isNamedDeclaration(node) ? node.name : - node; + isNamedDeclaration(node) ? node.name : + node; Debug.assert(node.kind !== SyntaxKind.NamespaceExport); if (node.kind === SyntaxKind.ExportSpecifier) { @@ -42312,7 +42314,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return checkJSDocPropertyTag(node as JSDocPropertyTag); case SyntaxKind.JSDocFunctionType: checkJSDocFunctionType(node as JSDocFunctionType); - // falls through + // falls through case SyntaxKind.JSDocNonNullableType: case SyntaxKind.JSDocNullableType: case SyntaxKind.JSDocAllType: @@ -42752,7 +42754,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (location.kind) { case SyntaxKind.SourceFile: if (!isExternalModule(location as SourceFile)) break; - // falls through + // falls through case SyntaxKind.ModuleDeclaration: copyLocallyVisibleExportSymbols(getSymbolOfNode(location as ModuleDeclaration | SourceFile).exports!, meaning & SymbolFlags.ModuleMember); break; @@ -43194,7 +43196,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!isThisInTypeQuery(node)) { return getSymbolOfNameOrPropertyAccessExpression(node as EntityName | PrivateIdentifier | PropertyAccessExpression); } - // falls through + // falls through case SyntaxKind.ThisKeyword: const container = getThisContainer(node, /*includeArrowFunctions*/ false); @@ -43207,7 +43209,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isInExpressionContext(node)) { return checkExpression(node as Expression).symbol; } - // falls through + // falls through case SyntaxKind.ThisType: return getTypeFromThisTypeNode(node as ThisExpression | ThisTypeNode).symbol; @@ -43239,7 +43241,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { return getSymbolOfNode(parent); } - // falls through + // falls through case SyntaxKind.NumericLiteral: // index access @@ -43463,7 +43465,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const propsByName = createSymbolTable(getPropertiesOfType(type)); const functionType = getSignaturesOfType(type, SignatureKind.Call).length ? globalCallableFunctionType : getSignaturesOfType(type, SignatureKind.Construct).length ? globalNewableFunctionType : - undefined; + undefined; if (functionType) { forEach(getPropertiesOfType(functionType), p => { if (!propsByName.has(p.escapedName)) { @@ -43490,7 +43492,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const { leftSpread, rightSpread, syntheticOrigin } = symbol as TransientSymbol; return leftSpread ? [leftSpread, rightSpread!] : syntheticOrigin ? [syntheticOrigin] - : singleElementArray(tryGetTarget(symbol)); + : singleElementArray(tryGetTarget(symbol)); } return undefined; } @@ -43513,8 +43515,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const parent = node.parent; if (!parent) return false; const isPropertyName = ((isPropertyAccessExpression(parent) - || isPropertyAssignment(parent)) - && parent.name === node); + || isPropertyAssignment(parent)) + && parent.name === node); return !isPropertyName && getReferencedValueSymbol(node) === argumentsSymbol; } @@ -44052,7 +44054,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const literalValue = (type as LiteralType).value; return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "number" ? factory.createNumericLiteral(literalValue) : - factory.createStringLiteral(literalValue); + factory.createStringLiteral(literalValue); } function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker) { @@ -44089,7 +44091,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // this variable and functions that use it are deliberately moved here from the outer scope // to avoid scope pollution const resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); - let fileToDirective: ESMap; + let fileToDirective: Map; if (resolvedTypeReferenceDirectives) { // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = new Map(); @@ -45427,14 +45429,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ); break; } - // fallthrough + // fallthrough case ModuleKind.ES2022: case ModuleKind.ESNext: case ModuleKind.System: if (languageVersion >= ScriptTarget.ES2017) { break; } - // fallthrough + // fallthrough default: diagnostics.add( createDiagnosticForNode(forInOrOfStatement.awaitModifier, @@ -46348,7 +46350,7 @@ function isNotAccessor(declaration: Declaration): boolean { function isNotOverload(declaration: Declaration): boolean { return (declaration.kind !== SyntaxKind.FunctionDeclaration && declaration.kind !== SyntaxKind.MethodDeclaration) || - !!(declaration as FunctionDeclaration).body; + !!(declaration as FunctionDeclaration).body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index aa0e7c7b91dbe..a9e808dadee17 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -4,7 +4,7 @@ import { CommandLineOptionOfListType, CompilerOptions, CompilerOptionsValue, ConfigFileSpecs, containsPath, convertToRelativePath, createCompilerDiagnostic, createDiagnosticForNodeInSourceFile, createGetCanonicalFileName, Debug, Diagnostic, DiagnosticMessage, Diagnostics, DidYouMeanOptionsDiagnostics, directorySeparator, emptyArray, - endsWith, ensureTrailingDirectorySeparator, ESMap, every, Expression, extend, Extension, FileExtensionInfo, + endsWith, ensureTrailingDirectorySeparator, every, Expression, extend, Extension, FileExtensionInfo, fileExtensionIs, fileExtensionIsOneOf, filter, filterMutate, find, findIndex, firstDefined, flatten, forEach, forEachEntry, getBaseFileName, getDirectoryPath, getEntries, getFileMatcherPatterns, getLocaleSpecificMessage, getNormalizedAbsolutePath, getRegexFromPattern, getRegularExpressionForWildcard, getRegularExpressionsForWildcards, @@ -12,7 +12,7 @@ import { getSupportedExtensionsWithJsonIfResolveJsonModule, getTextOfPropertyName, getTsConfigPropArray, getTsConfigPropArrayElementValue, hasExtension, hasProperty, ImportsNotUsedAsValues, isArray, isArrayLiteralExpression, isComputedNonLiteralName, isImplicitGlob, isObjectLiteralExpression, isRootedDiskPath, - isString, isStringDoubleQuoted, isStringLiteral, JsonSourceFile, JsxEmit, length, map, Map, mapDefined, mapIterator, + isString, isStringDoubleQuoted, isStringLiteral, JsonSourceFile, JsxEmit, length, map, mapDefined, mapIterator, MapLike, ModuleDetectionKind, ModuleKind, ModuleResolutionKind, NewLineKind, Node, NodeArray, nodeModuleNameResolver, normalizePath, normalizeSlashes, NumericLiteral, ObjectLiteralExpression, ParseConfigHost, ParsedCommandLine, parseJsonText, Path, PollingWatchKind, PrefixUnaryExpression, ProjectReference, PropertyName, @@ -1490,8 +1490,8 @@ export const typeAcquisitionDeclarations: CommandLineOption[] = [ /** @internal */ export interface OptionsNameMap { - optionsNameMap: ESMap; - shortOptionNames: ESMap; + optionsNameMap: Map; + shortOptionNames: Map; } /** @internal */ @@ -1885,7 +1885,7 @@ export function getParsedCommandLineOfConfigFile( configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, - extendedConfigCache?: Map, + extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[], ): ParsedCommandLine | undefined { @@ -1978,15 +1978,15 @@ const watchOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1 }; -let commandLineCompilerOptionsMapCache: ESMap; +let commandLineCompilerOptionsMapCache: Map; function getCommandLineCompilerOptionsMap() { return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(optionDeclarations)); } -let commandLineWatchOptionsMapCache: ESMap; +let commandLineWatchOptionsMapCache: Map; function getCommandLineWatchOptionsMap() { return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(optionsForWatch)); } -let commandLineTypeAcquisitionMapCache: ESMap; +let commandLineTypeAcquisitionMapCache: Map; function getCommandLineTypeAcquisitionMap() { return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(typeAcquisitionDeclarations)); } @@ -2152,13 +2152,13 @@ export function convertToObjectWorker( return convertPropertyValueToJson(rootExpression, knownRootOptions); - function isRootOptionMap(knownOptions: ESMap | undefined) { + function isRootOptionMap(knownOptions: Map | undefined) { return knownRootOptions && (knownRootOptions as TsConfigOnlyOption).elementOptions === knownOptions; } function convertObjectLiteralExpressionToJson( node: ObjectLiteralExpression, - knownOptions: ESMap | undefined, + knownOptions: Map | undefined, extraKeyDiagnostics: DidYouMeanOptionsDiagnostics | undefined, parentOption: string | undefined ): any { @@ -2430,7 +2430,7 @@ export function convertToTSConfig(configParseResult: ParsedCommandLine, configFi } /** @internal */ -export function optionMapToObject(optionMap: ESMap): object { +export function optionMapToObject(optionMap: Map): object { return { ...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}), }; @@ -2460,7 +2460,7 @@ function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined, return returnTrue; } -function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): ESMap | undefined { +function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { // this is of a type CommandLineOptionOfPrimitiveType return undefined; @@ -2474,7 +2474,7 @@ function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption } /** @internal */ -export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: ESMap): string | undefined { +export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: Map): string | undefined { // There is a typeMap associated with this command-line option so use it to map value back to its name return forEachEntry(customTypeMap, (mapValue, key) => { if (mapValue === value) { @@ -2487,7 +2487,7 @@ export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, custom export function serializeCompilerOptions( options: CompilerOptions, pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean } -): ESMap { +): Map { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -2499,7 +2499,7 @@ function serializeOptionBaseObject( options: OptionsBase, { optionsNameMap }: OptionsNameMap, pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean } -): ESMap { +): Map { const result = new Map(); const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); @@ -2553,7 +2553,7 @@ export function getCompilerOptionsDiffValue(options: CompilerOptions, newLine: s function getOverwrittenDefaultOptions() { const result: string[] = []; - const tab = makePadding(2); + const tab = makePadding(2); commandOptionsWithoutBuild.forEach(cmd => { if (!compilerOptionsMap.has(cmd.name)) { return; @@ -2576,7 +2576,7 @@ export function getCompilerOptionsDiffValue(options: CompilerOptions, newLine: s * Get the compiler options to be written into the tsconfig.json. * @param options commandlineOptions to be included in the compileOptions. */ -function getSerializedCompilerOption(options: CompilerOptions): ESMap { +function getSerializedCompilerOption(options: CompilerOptions): Map { const compilerOptions = extend(options, defaultInitCompilerOptions); return serializeCompilerOptions(compilerOptions); } @@ -2717,7 +2717,7 @@ function convertToOptionValueWithAbsolutePaths(option: CommandLineOption | undef * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ -export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine { +export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine { return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } @@ -2728,7 +2728,7 @@ export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, bas * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ -export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine { +export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine { tracing?.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName }); const result = parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); tracing?.pop(); @@ -2774,7 +2774,7 @@ function parseJsonConfigFileContentWorker( configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: readonly FileExtensionInfo[] = [], - extendedConfigCache?: ESMap + extendedConfigCache?: Map ): ParsedCommandLine { Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); const errors: Diagnostic[] = []; @@ -2996,7 +2996,7 @@ function parseConfig( configFileName: string | undefined, resolutionStack: string[], errors: Push, - extendedConfigCache?: ESMap + extendedConfigCache?: Map ): ParsedTsconfig { basePath = normalizeSlashes(basePath); const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath); @@ -3024,7 +3024,7 @@ function parseConfig( if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { const baseRaw = extendedConfig.raw; const raw = ownConfig.raw; - let relativeDifference: string | undefined ; + let relativeDifference: string | undefined; const setPropertyInRawIfNotUndefined = (propertyName: string) => { if (!raw[propertyName] && baseRaw[propertyName]) { raw[propertyName] = map(baseRaw[propertyName], (path: string) => isRootedDiskPath(path) ? path : combinePaths( @@ -3202,7 +3202,7 @@ function getExtendedConfig( host: ParseConfigHost, resolutionStack: string[], errors: Push, - extendedConfigCache?: ESMap + extendedConfigCache?: Map ): ParsedTsconfig | undefined { const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath); let value: ExtendedConfigCacheEntry | undefined; @@ -3290,11 +3290,11 @@ function convertWatchOptionsFromJsonWorker(jsonOptions: any, basePath: string, e return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors); } -function convertOptionsFromJson(optionsNameMap: ESMap, jsonOptions: any, basePath: string, +function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Push): WatchOptions | undefined; -function convertOptionsFromJson(optionsNameMap: ESMap, jsonOptions: any, basePath: string, +function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: CompilerOptions | TypeAcquisition, diagnostics: DidYouMeanOptionsDiagnostics, errors: Push): CompilerOptions | TypeAcquisition; -function convertOptionsFromJson(optionsNameMap: ESMap, jsonOptions: any, basePath: string, +function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: CompilerOptions | TypeAcquisition | WatchOptions | undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Push) { if (!jsonOptions) { @@ -3318,7 +3318,7 @@ export function convertJsonOption(opt: CommandLineOption, value: any, basePath: if (isCompilerOptionsValue(opt, value)) { const optType = opt.type; if (optType === "list" && isArray(value)) { - return convertJsonOptionOfListType(opt , value, basePath, errors); + return convertJsonOptionOfListType(opt, value, basePath, errors); } else if (!isString(optType)) { return convertJsonOptionOfCustomType(opt as CommandLineOptionOfCustomType, value as string, errors); @@ -3687,7 +3687,7 @@ function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: b * * @param file The path to the file. */ -function hasFileWithHigherPriorityExtension(file: string, literalFiles: ESMap, wildcardFiles: ESMap, extensions: readonly string[][], keyMapper: (value: string) => string) { +function hasFileWithHigherPriorityExtension(file: string, literalFiles: Map, wildcardFiles: Map, extensions: readonly string[][], keyMapper: (value: string) => string) { const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined); if (!extensionGroup) { return false; @@ -3717,7 +3717,7 @@ function hasFileWithHigherPriorityExtension(file: string, literalFiles: ESMap, extensions: readonly string[][], keyMapper: (value: string) => string) { +function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: Map, extensions: readonly string[][], keyMapper: (value: string) => string) { const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined); if (!extensionGroup) { return; diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 93e5aaef932de..73f6076a21bda 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1,26 +1,26 @@ import { - __String, CharacterCodes, Comparer, Comparison, Debug, EqualityComparer, ESMap, isWhiteSpaceLike, Iterator, Map, - MapLike, Push, Queue, ReadonlyESMap, ReadonlySet, Set, SortedArray, SortedReadonlyArray, TextSpan, + __String, CharacterCodes, Comparer, Comparison, Debug, EqualityComparer, isWhiteSpaceLike, + MapLike, Push, Queue, SortedArray, SortedReadonlyArray, TextSpan, UnderscoreEscapedMap, } from "./_namespaces/ts"; /** @internal */ -export function getIterator | ReadonlyESMap | undefined>(iterable: I): Iterator< - I extends ReadonlyESMap ? [K, V] : +export function getIterator | ReadonlyMap | undefined>(iterable: I): Iterator< + I extends ReadonlyMap ? [K, V] : I extends ReadonlySet ? T : I extends readonly (infer T)[] ? T : I extends undefined ? undefined : never>; /** @internal */ -export function getIterator(iterable: ReadonlyESMap): Iterator<[K, V]>; +export function getIterator(iterable: ReadonlyMap): Iterator<[K, V]>; /** @internal */ -export function getIterator(iterable: ReadonlyESMap | undefined): Iterator<[K, V]> | undefined; +export function getIterator(iterable: ReadonlyMap | undefined): Iterator<[K, V]> | undefined; /** @internal */ export function getIterator(iterable: readonly T[] | ReadonlySet): Iterator; /** @internal */ export function getIterator(iterable: readonly T[] | ReadonlySet | undefined): Iterator | undefined; /** @internal */ -export function getIterator(iterable: readonly any[] | ReadonlySet | ReadonlyESMap | undefined): Iterator | undefined { +export function getIterator(iterable: readonly any[] | ReadonlySet | ReadonlyMap | undefined): Iterator | undefined { if (iterable) { if (isArray(iterable)) return arrayIterator(iterable); if (iterable instanceof Map) return iterable.entries(); @@ -32,7 +32,7 @@ export function getIterator(iterable: readonly any[] | ReadonlySet | Readon /** @internal */ export const emptyArray: never[] = [] as never[]; /** @internal */ -export const emptyMap: ReadonlyESMap = new Map(); +export const emptyMap: ReadonlyMap = new Map(); /** @internal */ export const emptySet: ReadonlySet = new Set(); @@ -147,7 +147,7 @@ export function zipToIterator(arrayA: readonly T[], arrayB: readonly U[]): } /** @internal */ -export function zipToMap(keys: readonly K[], values: readonly V[]): ESMap { +export function zipToMap(keys: readonly K[], values: readonly V[]): Map { Debug.assert(keys.length === values.length); const map = new Map(); for (let i = 0; i < keys.length; ++i) { @@ -608,11 +608,11 @@ export function mapDefinedIterator(iter: Iterator, mapFn: (x: T) => U | } /** @internal */ -export function mapDefinedEntries(map: ReadonlyESMap, f: (key: K1, value: V1) => readonly [K2, V2] | undefined): ESMap; +export function mapDefinedEntries(map: ReadonlyMap, f: (key: K1, value: V1) => readonly [K2, V2] | undefined): Map; /** @internal */ -export function mapDefinedEntries(map: ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): ESMap | undefined; +export function mapDefinedEntries(map: ReadonlyMap | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): Map | undefined; /** @internal */ -export function mapDefinedEntries(map: ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): ESMap | undefined { +export function mapDefinedEntries(map: ReadonlyMap | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): Map | undefined { if (!map) { return undefined; } @@ -650,7 +650,7 @@ export function mapDefinedValues(set: ReadonlySet | undefined, f: (v } /** @internal */ -export function getOrUpdate(map: ESMap, key: K, callback: () => V) { +export function getOrUpdate(map: Map, key: K, callback: () => V) { if (map.has(key)) { return map.get(key)!; } @@ -737,11 +737,11 @@ export function spanMap(array: readonly T[] | undefined, keyfn: (x: T, } /** @internal */ -export function mapEntries(map: ReadonlyESMap, f: (key: K1, value: V1) => readonly [K2, V2]): ESMap; +export function mapEntries(map: ReadonlyMap, f: (key: K1, value: V1) => readonly [K2, V2]): Map; /** @internal */ -export function mapEntries(map: ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): ESMap | undefined; +export function mapEntries(map: ReadonlyMap | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): Map | undefined; /** @internal */ -export function mapEntries(map: ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): ESMap | undefined { +export function mapEntries(map: ReadonlyMap | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): Map | undefined { if (!map) { return undefined; } @@ -1569,15 +1569,15 @@ export function equalOwnProperties(left: MapLike | undefined, right: MapLi * * @internal */ -export function arrayToMap(array: readonly V[], makeKey: (value: V) => K | undefined): ESMap; +export function arrayToMap(array: readonly V[], makeKey: (value: V) => K | undefined): Map; /** @internal */ -export function arrayToMap(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V2): ESMap; +export function arrayToMap(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V2): Map; /** @internal */ -export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined): ESMap; +export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined): Map; /** @internal */ -export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): ESMap; +export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): Map; /** @internal */ -export function arrayToMap(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V1 | V2 = identity): ESMap { +export function arrayToMap(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V1 | V2 = identity): Map { const result = new Map(); for (const value of array) { const key = makeKey(value); @@ -1675,7 +1675,7 @@ export function maybeBind(obj: T, fn: ((this: T, ...args: } /** @internal */ -export interface MultiMap extends ESMap { +export interface MultiMap extends Map { /** * Adds the value to an array of values associated with the key, and returns the array. * Creates the array if it does not already exist. @@ -1798,10 +1798,10 @@ export function createSet(getHashCode: (element: TElem const multiMap = new Map(); let size = 0; - function getElementIterator(): Iterator { + function getElementIterator(): IterableIterator { const valueIt = multiMap.values(); let arrayIt: Iterator | undefined; - return { + const it: IterableIterator = { next: () => { while (true) { if (arrayIt) { @@ -1822,8 +1822,12 @@ export function createSet(getHashCode: (element: TElem arrayIt = arrayIterator(n.value); } } + }, + [Symbol.iterator]: () => { + return it; } }; + return it; } const set: Set = { @@ -1904,34 +1908,40 @@ export function createSet(getHashCode: (element: TElem get size() { return size; }, - forEach(action: (value: TElement, key: TElement) => void): void { + forEach(action: (value: TElement, key: TElement, set: Set) => void): void { for (const elements of arrayFrom(multiMap.values())) { if (isArray(elements)) { for (const element of elements) { - action(element, element); + action(element, element, set); } } else { const element = elements; - action(element, element); + action(element, element, set); } } }, - keys(): Iterator { + keys(): IterableIterator { return getElementIterator(); }, - values(): Iterator { + values(): IterableIterator { return getElementIterator(); }, - entries(): Iterator<[TElement, TElement]> { + entries(): IterableIterator<[TElement, TElement]> { const it = getElementIterator(); - return { + const it2: IterableIterator<[TElement, TElement]> = { next: () => { const n = it.next(); return n.done ? n : { value: [ n.value, n.value ] }; - } + }, + [Symbol.iterator]: () => it2, }; + return it2; + }, + [Symbol.iterator]: () => { + return getElementIterator(); }, + [Symbol.toStringTag]: multiMap[Symbol.toStringTag], }; return set; diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index aa0933e9e6e60..ca36fa2ff4041 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -35,63 +35,6 @@ export interface Collection extends ReadonlyCollection { delete(key: K): boolean; clear(): void; } - -/** ES6 Map interface, only read methods included. */ -export interface ReadonlyESMap extends ReadonlyCollection { - get(key: K): V | undefined; - values(): Iterator; - entries(): Iterator<[K, V]>; - forEach(action: (value: V, key: K) => void): void; -} - -/** - * ES6 Map interface, only read methods included. - */ -export interface ReadonlyMap extends ReadonlyESMap { -} - -/** ES6 Map interface. */ -export interface ESMap extends ReadonlyESMap, Collection { - set(key: K, value: V): this; -} - -/** - * ES6 Map interface. - */ -export interface Map extends ESMap { -} - -/** @internal */ -export interface MapConstructor { - // eslint-disable-next-line @typescript-eslint/prefer-function-type - new (iterable?: readonly (readonly [K, V])[] | ReadonlyESMap): ESMap; -} - -/** ES6 Set interface, only read methods included. */ -export interface ReadonlySet extends ReadonlyCollection { - has(value: T): boolean; - values(): Iterator; - entries(): Iterator<[T, T]>; - forEach(action: (value: T, key: T) => void): void; -} - -/** ES6 Set interface. */ -export interface Set extends ReadonlySet, Collection { - add(value: T): this; - delete(value: T): boolean; -} - -/** @internal */ -export interface SetConstructor { - // eslint-disable-next-line @typescript-eslint/prefer-function-type - new (iterable?: readonly T[] | ReadonlySet): Set; -} - -/** ES6 Iterator type. */ -export interface Iterator { - next(): { value: T, done?: false } | { value: void, done: true }; -} - /** Array that is only intended to be pushed to, never read. */ export interface Push { push(...values: T[]): void; @@ -110,46 +53,3 @@ export const enum Comparison { EqualTo = 0, GreaterThan = 1 } - -/** @internal */ -namespace NativeCollections { - declare const self: any; - - const globals = typeof globalThis !== "undefined" ? globalThis : - typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - undefined; - - /** - * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). - */ - export function tryGetNativeMap(): MapConstructor { - // Internet Explorer's Map doesn't support iteration, so don't use it. - const gMap = globals?.Map; - // eslint-disable-next-line local/no-in-operator - const constructor = typeof gMap !== "undefined" && "entries" in gMap.prototype && new gMap([[0, 0]]).size === 1 ? gMap : undefined; - if (!constructor) { - throw new Error("No compatible Map implementation found."); - } - return constructor; - } - - /** - * Returns the native Set implementation if it is available and compatible (i.e. supports iteration). - */ - export function tryGetNativeSet(): SetConstructor { - // Internet Explorer's Set doesn't support iteration, so don't use it. - const gSet = globals?.Set; - // eslint-disable-next-line local/no-in-operator - const constructor = typeof gSet !== "undefined" && "entries" in gSet.prototype && new gSet([0]).size === 1 ? gSet : undefined; - if (!constructor) { - throw new Error("No compatible Set implementation found."); - } - return constructor; - } -} - -/** @internal */ -export const Map = NativeCollections.tryGetNativeMap(); -/** @internal */ -export const Set = NativeCollections.tryGetNativeSet(); diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index adb2d539c8a4f..228fba72866d9 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -10,8 +10,8 @@ import { isOptionalTypeNode, isParameter, isParenthesizedTypeNode, isParseTreeNode, isPrivateIdentifier, isRestTypeNode, isSetAccessorDeclaration, isStringLiteral, isThisTypeNode, isTupleTypeNode, isTypeLiteralNode, isTypeOperatorNode, isTypeParameterDeclaration, isTypePredicateNode, isTypeQueryNode, isTypeReferenceNode, isUnionTypeNode, LiteralType, - map, Map, MatchingKeys, ModifierFlags, Node, NodeArray, NodeFlags, nodeIsSynthesized, noop, objectAllocator, - ObjectFlags, ObjectType, RelationComparisonResult, Set, Signature, SignatureCheckMode, + map, MatchingKeys, ModifierFlags, Node, NodeArray, NodeFlags, nodeIsSynthesized, noop, objectAllocator, + ObjectFlags, ObjectType, RelationComparisonResult, Signature, SignatureCheckMode, SignatureFlags, SnippetKind, SortedReadonlyArray, stableSort, Symbol, SymbolFlags, symbolName, SyntaxKind, TransformFlags, Type, TypeFacts, TypeFlags, TypeMapKind, TypeMapper, unescapeLeadingUnderscores, VarianceFlags, version, Version, zipWith, diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 4c878210dd016..4342078512d0b 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -16,7 +16,7 @@ import { ElementAccessExpression, emitDetachedComments, EmitFileNames, EmitFlags, EmitHint, EmitHost, emitNewLineBeforeLeadingCommentOfPosition, EmitOnly, EmitResolver, EmitResult, EmitTextWriter, EmitTransformers, emptyArray, ensurePathIsNonModuleName, ensureTrailingDirectorySeparator, EntityName, EnumDeclaration, EnumMember, - escapeJsxAttributeString, escapeLeadingUnderscores, escapeNonAsciiString, escapeString, ESMap, every, + escapeJsxAttributeString, escapeLeadingUnderscores, escapeNonAsciiString, escapeString, every, ExportAssignment, ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement, ExpressionWithTypeArguments, Extension, ExternalModuleReference, factory, fileExtensionIs, fileExtensionIsOneOf, FileReference, filter, findIndex, firstOrUndefined, forEach, forEachChild, forEachLeadingCommentRange, forEachTrailingCommentRange, @@ -52,7 +52,7 @@ import { JSDocTypeTag, JSDocVariadicType, JsxAttribute, JsxAttributes, JsxClosingElement, JsxClosingFragment, JsxElement, JsxEmit, JsxExpression, JsxFragment, JsxOpeningElement, JsxOpeningFragment, JsxSelfClosingElement, JsxSpreadAttribute, JsxTagNameExpression, JsxText, LabeledStatement, last, lastOrUndefined, LateBoundDeclaration, - length, ListFormat, LiteralExpression, LiteralLikeNode, LiteralTypeNode, makeIdentifierFromModuleName, Map, + length, ListFormat, LiteralExpression, LiteralLikeNode, LiteralTypeNode, makeIdentifierFromModuleName, MappedTypeNode, maybeBind, memoize, MetaProperty, MethodDeclaration, MethodSignature, Modifier, ModifierLike, ModuleBlock, ModuleDeclaration, ModuleKind, ModuleReference, NamedDeclaration, NamedExports, NamedImports, NamedImportsOrExports, NamedTupleMember, NamespaceExport, NamespaceExportDeclaration, NamespaceImport, @@ -65,7 +65,7 @@ import { PropertyAssignment, PropertyDeclaration, PropertySignature, QualifiedName, rangeEndIsOnSameLineAsRangeStart, rangeEndPositionsAreOnSameLine, rangeIsOnSingleLine, rangeStartPositionsAreOnSameLine, readJsonOrUndefined, removeFileExtension, resolvePath, RestTypeNode, returnFalse, ReturnStatement, returnUndefined, SatisfiesExpression, - ScriptTarget, Set, setEachParent, setOriginalNode, setParent, setTextRange, setTextRangePosEnd, + ScriptTarget, setEachParent, setOriginalNode, setParent, setTextRange, setTextRangePosEnd, setTextRangePosWidth, ShorthandPropertyAssignment, SignatureDeclaration, singleOrUndefined, skipPartiallyEmittedExpressions, skipTrivia, SnippetElement, SnippetKind, some, SourceFile, SourceFilePrologueDirective, SourceFilePrologueInfo, SourceMapEmitResult, SourceMapGenerator, SourceMapSource, @@ -192,10 +192,10 @@ function getSourceMapFilePath(jsFilePath: string, options: CompilerOptions) { /** @internal */ export function getOutputExtension(fileName: string, options: CompilerOptions): Extension { return fileExtensionIs(fileName, Extension.Json) ? Extension.Json : - options.jsx === JsxEmit.Preserve && fileExtensionIsOneOf(fileName, [Extension.Jsx, Extension.Tsx]) ? Extension.Jsx : - fileExtensionIsOneOf(fileName, [Extension.Mts, Extension.Mjs]) ? Extension.Mjs : - fileExtensionIsOneOf(fileName, [Extension.Cts, Extension.Cjs]) ? Extension.Cjs : - Extension.Js; + options.jsx === JsxEmit.Preserve && fileExtensionIsOneOf(fileName, [Extension.Jsx, Extension.Tsx]) ? Extension.Jsx : + fileExtensionIsOneOf(fileName, [Extension.Mts, Extension.Mjs]) ? Extension.Mjs : + fileExtensionIsOneOf(fileName, [Extension.Cts, Extension.Cjs]) ? Extension.Cjs : + Extension.Js; } function getOutputPathWithoutChangingExt(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, outputDir: string | undefined, getCommonSourceDirectory?: () => string) { @@ -992,8 +992,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes. let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables. let generatedNames: Set; // Set of names generated by the NameGenerator. - let formattedNameTempFlagsStack: (ESMap | undefined)[]; - let formattedNameTempFlags: ESMap | undefined; + let formattedNameTempFlagsStack: (Map | undefined)[]; + let formattedNameTempFlags: Map | undefined; let privateNameTempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes. let privateNameTempFlags: TempFlags; // TempFlags for the current name generation scope. let tempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes. @@ -1363,7 +1363,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri if (onEmitNode !== noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { return pipelineEmitWithNotification; } - // falls through + // falls through case PipelinePhase.Substitution: if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { if (currentParenthesizerRule) { @@ -1371,17 +1371,17 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } return pipelineEmitWithSubstitution; } - // falls through + // falls through case PipelinePhase.Comments: if (shouldEmitComments(node)) { return pipelineEmitWithComments; } - // falls through + // falls through case PipelinePhase.SourceMaps: if (shouldEmitSourceMaps(node)) { return pipelineEmitWithSourceMaps; } - // falls through + // falls through case PipelinePhase.Emit: return pipelineEmitWithHint; default: @@ -5081,7 +5081,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode); return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? `"${escapeString(text)}"` : - `"${escapeNonAsciiString(text)}"`; + `"${escapeNonAsciiString(text)}"`; } else { return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); @@ -5509,7 +5509,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri */ function makeName(name: GeneratedIdentifier | GeneratedPrivateIdentifier) { const prefix = formatGeneratedNamePart(name.autoGeneratePrefix, generateName); - const suffix = formatGeneratedNamePart (name.autoGenerateSuffix); + const suffix = formatGeneratedNamePart(name.autoGenerateSuffix); switch (name.autoGenerateFlags & GeneratedIdentifierFlags.KindMask) { case GeneratedIdentifierFlags.Auto: return makeTempVariableName(TempFlags.Auto, !!(name.autoGenerateFlags & GeneratedIdentifierFlags.ReservedInNestedScopes), isPrivateIdentifier(name), prefix, suffix); @@ -5829,7 +5829,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { - if(!currentSourceFile) return; + if (!currentSourceFile) return; // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space emitPos(commentPos); @@ -6134,5 +6134,5 @@ function emitListItemWithParenthesizerRule(node: Node, emit: (node: Node, parent function getEmitListItem | undefined>(emit: (node: Node, parenthesizerRule?: ((node: Node) => Node) | undefined) => void, parenthesizerRule: R): (node: Node, emit: (node: Node, parenthesizerRule?: ((node: Node) => Node) | undefined) => void, parenthesizerRule: R, index: number) => void { return emit.length === 1 ? emitListItemNoParenthesizer : typeof parenthesizerRule === "object" ? emitListItemWithParenthesizerRuleSelector : - emitListItemWithParenthesizerRule; + emitListItemWithParenthesizerRule; } diff --git a/src/compiler/factory/emitHelpers.ts b/src/compiler/factory/emitHelpers.ts index 8783c52b767f4..a22550781cef5 100644 --- a/src/compiler/factory/emitHelpers.ts +++ b/src/compiler/factory/emitHelpers.ts @@ -3,7 +3,7 @@ import { createExpressionFromEntityName, Debug, EmitFlags, EmitHelper, EmitHelperUniqueNameCallback, EmitNode, EntityName, Expression, FunctionExpression, GeneratedIdentifierFlags, getEmitFlags, getEmitScriptTarget, getPropertyNameOfBindingOrAssignmentElement, Identifier, isCallExpression, isComputedPropertyName, isIdentifier, - memoize, PrivateIdentifierKind, ReadonlyESMap, ScriptTarget, setEmitFlags, setTextRange, SyntaxKind, TextRange, + memoize, PrivateIdentifierKind, ScriptTarget, setEmitFlags, setTextRange, SyntaxKind, TextRange, TransformationContext, UnscopedEmitHelper, } from "../_namespaces/ts"; @@ -1034,7 +1034,7 @@ export const classPrivateFieldInHelper: UnscopedEmitHelper = { };` }; -let allUnscopedEmitHelpers: ReadonlyESMap | undefined; +let allUnscopedEmitHelpers: ReadonlyMap | undefined; /** @internal */ export function getAllUnscopedEmitHelpers() { diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index f2f111efb22c1..afa240bd0b392 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -48,7 +48,7 @@ import { JsxAttributeValue, JsxChild, JsxClosingElement, JsxClosingFragment, JsxElement, JsxExpression, JsxFragment, JsxOpeningElement, JsxOpeningFragment, JsxSelfClosingElement, JsxSpreadAttribute, JsxTagNameExpression, JsxText, KeywordSyntaxKind, KeywordToken, KeywordTypeNode, KeywordTypeSyntaxKind, LabeledStatement, LanguageVariant, - lastOrUndefined, LeftHandSideExpression, LiteralToken, LiteralTypeNode, map, Map, MappedTypeNode, + lastOrUndefined, LeftHandSideExpression, LiteralToken, LiteralTypeNode, map, MappedTypeNode, memoize, memoizeOne, MergeDeclarationMarker, MetaProperty, MethodDeclaration, MethodSignature, MinusToken, MissingDeclaration, Modifier, ModifierFlags, ModifierLike, modifiersToFlags, ModifierSyntaxKind, ModifierToken, ModuleBlock, ModuleBody, ModuleDeclaration, ModuleKind, ModuleName, ModuleReference, Mutable, MutableNodeArray, diff --git a/src/compiler/factory/parenthesizerRules.ts b/src/compiler/factory/parenthesizerRules.ts index 78abbbc097563..0f697835674a5 100644 --- a/src/compiler/factory/parenthesizerRules.ts +++ b/src/compiler/factory/parenthesizerRules.ts @@ -1,11 +1,11 @@ import { - Associativity, BinaryExpression, BinaryOperator, cast, compareValues, Comparison, ConciseBody, ESMap, Expression, + Associativity, BinaryExpression, BinaryOperator, cast, compareValues, Comparison, ConciseBody, Expression, getExpressionAssociativity, getExpressionPrecedence, getLeftmostExpression, getOperatorAssociativity, getOperatorPrecedence, identity, isBinaryExpression, isBlock, isCallExpression, isCommaSequence, isConditionalTypeNode, isConstructorTypeNode, isFunctionOrConstructorTypeNode, isFunctionTypeNode, isInferTypeNode, isIntersectionTypeNode, isJSDocNullableType, isLeftHandSideExpression, isLiteralKind, isNamedTupleMember, isNodeArray, isOptionalChain, isTypeOperatorNode, isUnaryExpression, isUnionTypeNode, last, LeftHandSideExpression, - Map, NamedTupleMember, NewExpression, NodeArray, NodeFactory, OperatorPrecedence, OuterExpressionKinds, + NamedTupleMember, NewExpression, NodeArray, NodeFactory, OperatorPrecedence, OuterExpressionKinds, ParenthesizerRules, sameMap, setTextRange, skipPartiallyEmittedExpressions, some, SyntaxKind, TypeNode, UnaryExpression, } from "../_namespaces/ts"; @@ -16,8 +16,8 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul cachedLiteralKind: SyntaxKind; } - let binaryLeftOperandParenthesizerCache: ESMap Expression> | undefined; - let binaryRightOperandParenthesizerCache: ESMap Expression> | undefined; + let binaryLeftOperandParenthesizerCache: Map Expression> | undefined; + let binaryRightOperandParenthesizerCache: Map Expression> | undefined; return { getParenthesizeLeftSideOfBinaryForOperator, diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 12039c33247cd..ba4cc56a125fb 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -2,14 +2,14 @@ import { append, appendIfUnique, arrayFrom, changeAnyExtension, CharacterCodes, combinePaths, comparePaths, Comparison, CompilerOptions, contains, containsPath, createCompilerDiagnostic, Debug, Diagnostic, DiagnosticMessage, DiagnosticReporter, Diagnostics, directoryProbablyExists, directorySeparator, emptyArray, endsWith, - ensureTrailingDirectorySeparator, ESMap, every, Extension, extensionIsTS, fileExtensionIs, fileExtensionIsOneOf, + ensureTrailingDirectorySeparator, every, Extension, extensionIsTS, fileExtensionIs, fileExtensionIsOneOf, FileReference, filter, firstDefined, forEach, forEachAncestorDirectory, formatMessage, getBaseFileName, GetCanonicalFileName, getCommonSourceDirectory, getDirectoryPath, GetEffectiveTypeRootsHost, getEmitModuleKind, getEmitModuleResolutionKind, getModeForUsageLocation, getNormalizedAbsolutePath, getOwnKeys, getPathComponents, getPathFromPathComponents, getPathsBasePath, getPossibleOriginalInputExtensionForExtension, getRelativePathFromDirectory, getRootLength, hasJSFileExtension, hasProperty, hasTrailingDirectorySeparator, hasTSFileExtension, hostGetCanonicalFileName, isArray, isExternalModuleNameRelative, isRootedDiskPath, isString, - isStringLiteralLike, lastOrUndefined, length, Map, MapLike, matchedText, MatchingKeys, matchPatternOrExact, + isStringLiteralLike, lastOrUndefined, length, MapLike, matchedText, MatchingKeys, matchPatternOrExact, ModuleKind, ModuleResolutionHost, ModuleResolutionKind, noop, noopPush, normalizePath, normalizeSlashes, optionsHaveModuleResolutionChanges, PackageId, packageIdToString, ParsedCommandLine, Path, pathIsRelative, Pattern, patternText, perfLogger, Push, readJson, removeExtension, removeFileExtension, removePrefix, @@ -610,7 +610,7 @@ export interface PackageJsonInfoCache { /** @internal */ getPackageJsonInfo(packageJsonPath: string): PackageJsonInfo | boolean | undefined; /** @internal */ setPackageJsonInfo(packageJsonPath: string, info: PackageJsonInfo | boolean): void; /** @internal */ entries(): [Path, PackageJsonInfo | boolean][]; - /** @internal */ getInternalMap(): ESMap | undefined; + /** @internal */ getInternalMap(): Map | undefined; clear(): void; } @@ -621,18 +621,18 @@ export interface PerModuleNameCache { /** @internal */ export interface CacheWithRedirects { - getOwnMap: () => ESMap; - redirectsMap: ESMap>; - getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): ESMap; + getOwnMap: () => Map; + redirectsMap: Map>; + getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map; clear(): void; setOwnOptions(newOptions: CompilerOptions): void; - setOwnMap(newOwnMap: ESMap): void; + setOwnMap(newOwnMap: Map): void; } /** @internal */ export function createCacheWithRedirects(options?: CompilerOptions): CacheWithRedirects { - let ownMap: ESMap = new Map(); - const redirectsMap = new Map>(); + let ownMap: Map = new Map(); + const redirectsMap = new Map>(); return { getOwnMap, redirectsMap, @@ -650,7 +650,7 @@ export function createCacheWithRedirects(options?: CompilerOptions): CacheWit options = newOptions; } - function setOwnMap(newOwnMap: ESMap) { + function setOwnMap(newOwnMap: Map) { ownMap = newOwnMap; } @@ -675,7 +675,7 @@ export function createCacheWithRedirects(options?: CompilerOptions): CacheWit } function createPackageJsonInfoCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): PackageJsonInfoCache { - let cache: ESMap | undefined; + let cache: Map | undefined; return { getPackageJsonInfo, setPackageJsonInfo, clear, entries, getInternalMap }; function getPackageJsonInfo(packageJsonPath: string) { return cache?.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); @@ -1311,8 +1311,8 @@ export enum NodeResolutionFeatures { } function node16ModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, - host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, - resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations { + host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, + resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations { return nodeNextModuleNameResolverWorker( NodeResolutionFeatures.Node16Default, moduleName, @@ -1326,8 +1326,8 @@ function node16ModuleNameResolver(moduleName: string, containingFile: string, co } function nodeNextModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, - host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, - resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations { + host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, + resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations { return nodeNextModuleNameResolverWorker( NodeResolutionFeatures.NodeNextDefault, moduleName, @@ -1860,7 +1860,7 @@ export interface PackageJsonInfoContents { * * @internal */ - export function getPackageScopeForPath(fileName: string, state: ModuleResolutionState): PackageJsonInfo | undefined { +export function getPackageScopeForPath(fileName: string, state: ModuleResolutionState): PackageJsonInfo | undefined { const parts = getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -2148,24 +2148,24 @@ function loadModuleFromImportsOrExports(extensions: Extensions, state: ModuleRes const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!endsWith(moduleName, directorySeparator) && moduleName.indexOf("*") === -1 && hasProperty(lookupTable, moduleName)) { - const target = (lookupTable as {[idx: string]: unknown})[moduleName]; + const target = (lookupTable as { [idx: string]: unknown })[moduleName]; return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike), k => k.indexOf("*") !== -1 || endsWith(k, "/")), comparePatternKeys); for (const potentialTarget of expandingKeys) { if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { - const target = (lookupTable as {[idx: string]: unknown})[potentialTarget]; + const target = (lookupTable as { [idx: string]: unknown })[potentialTarget]; const starPos = potentialTarget.indexOf("*"); const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { - const target = (lookupTable as {[idx: string]: unknown})[potentialTarget]; + const target = (lookupTable as { [idx: string]: unknown })[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length - 1); return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (startsWith(moduleName, potentialTarget)) { - const target = (lookupTable as {[idx: string]: unknown})[potentialTarget]; + const target = (lookupTable as { [idx: string]: unknown })[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length); return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } @@ -2293,7 +2293,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo function useCaseSensitiveFileNames() { return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : - state.host.useCaseSensitiveFileNames(); + state.host.useCaseSensitiveFileNames(); } function tryLoadInputFileForPath(finalPath: string, entry: string, packagePath: string, isImports: boolean) { diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index b6ddd551cf9c6..98c6a4f56c428 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -11,7 +11,7 @@ import { getTextOfIdentifierOrLiteral, hasJSFileExtension, hasTSFileExtension, hostGetCanonicalFileName, Identifier, isAmbientModule, isApplicableVersionedTypesKey, isExternalModuleAugmentation, isExternalModuleNameRelative, isModuleBlock, isModuleDeclaration, isNonGlobalAmbientModule, isRootedDiskPath, isSourceFile, isString, JsxEmit, - map, Map, mapDefined, MapLike, matchPatternOrExact, min, ModuleDeclaration, ModuleKind, ModulePath, + map, mapDefined, MapLike, matchPatternOrExact, min, ModuleDeclaration, ModuleKind, ModulePath, ModuleResolutionHost, ModuleResolutionKind, ModuleSpecifierCache, ModuleSpecifierOptions, ModuleSpecifierResolutionHost, NodeFlags, NodeModulePathParts, normalizePath, Path, pathContainsNodeModules, pathIsBareSpecifier, pathIsRelative, PropertyAccessExpression, removeFileExtension, removeSuffix, resolvePath, @@ -35,9 +35,9 @@ function getPreferences(host: ModuleSpecifierResolutionHost, { importModuleSpeci return { relativePreference: importModuleSpecifierPreference === "relative" ? RelativePreference.Relative : - importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative : - importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative : - RelativePreference.Shortest, + importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative : + importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative : + RelativePreference.Shortest, ending: getEnding(), }; function getEnding(): Ending { @@ -62,7 +62,7 @@ function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpec function isFormatRequiringExtensions(compilerOptions: CompilerOptions, importingSourceFileName: Path, host: ModuleSpecifierResolutionHost) { if (getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Node16 - && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeNext) { + && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeNext) { return false; } return getImpliedNodeFormatForFile(importingSourceFileName, host.getPackageJsonInfoCache?.(), getModuleResolutionHost(host), compilerOptions) !== ModuleKind.CommonJS; @@ -307,7 +307,7 @@ function computeModuleSpecifiers( return pathsSpecifiers?.length ? pathsSpecifiers : nodeModulesSpecifiers?.length ? nodeModulesSpecifiers : - Debug.checkDefined(relativeSpecifiers); + Debug.checkDefined(relativeSpecifiers); } interface Info { @@ -736,7 +736,7 @@ function tryGetModuleNameFromExports(options: CompilerOptions, targetFilePath: s const subPackageName = getNormalizedAbsolutePath(combinePaths(packageName, k), /*currentDirectory*/ undefined); const mode = endsWith(k, "/") ? MatchingMode.Directory : stringContains(k, "*") ? MatchingMode.Pattern - : MatchingMode.Exact; + : MatchingMode.Exact; return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, (exports as MapLike)[k], conditions, mode); }); } @@ -776,7 +776,7 @@ function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileNam : removeFileExtension(shortest); } -function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: SourceFile , host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ModuleKind.ESNext | ModuleKind.CommonJS): string | undefined { +function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: SourceFile, host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ModuleKind.ESNext | ModuleKind.CommonJS): string | undefined { if (!host.fileExists || !host.readFile) { return undefined; } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index b161549e0fc6e..0cbf7b38883e4 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -12,7 +12,7 @@ import { createDetachedDiagnostic, createNodeFactory, createScanner, createTextChangeRange, createTextSpanFromBounds, Debug, Decorator, DefaultClause, DeleteExpression, Diagnostic, DiagnosticMessage, Diagnostics, DiagnosticWithDetachedLocation, DoStatement, DotDotDotToken, ElementAccessExpression, emptyArray, emptyMap, - EndOfFileToken, ensureScriptKind, EntityName, EnumDeclaration, EnumMember, ESMap, ExclamationToken, + EndOfFileToken, ensureScriptKind, EntityName, EnumDeclaration, EnumMember, ExclamationToken, ExportAssignment, ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement, ExpressionWithTypeArguments, ExternalModuleReference, fileExtensionIsOneOf, FileReference, findIndex, forEach, ForEachChildNodes, ForInOrOfStatement, ForInStatement, ForOfStatement, ForStatement, FunctionDeclaration, FunctionExpression, @@ -39,7 +39,7 @@ import { JsxExpression, JsxFragment, JsxOpeningElement, JsxOpeningFragment, JsxOpeningLikeElement, JsxSelfClosingElement, JsxSpreadAttribute, JsxTagNameExpression, JsxTagNamePropertyAccess, JsxText, JsxTokenSyntaxKind, LabeledStatement, LanguageVariant, lastOrUndefined, LeftHandSideExpression, LiteralExpression, LiteralLikeNode, LiteralTypeNode, map, - Map, mapDefined, MappedTypeNode, MemberExpression, MetaProperty, MethodDeclaration, MethodSignature, MinusToken, + mapDefined, MappedTypeNode, MemberExpression, MetaProperty, MethodDeclaration, MethodSignature, MinusToken, MissingDeclaration, Modifier, ModifierFlags, ModifierLike, ModifiersArray, modifiersToFlags, ModuleBlock, ModuleDeclaration, ModuleKind, Mutable, NamedExportBindings, NamedExports, NamedImports, NamedImportsOrExports, NamedTupleMember, NamespaceDeclaration, NamespaceExport, NamespaceExportDeclaration, NamespaceImport, NewExpression, @@ -52,7 +52,7 @@ import { PrivateIdentifier, PropertyAccessEntityNameExpression, PropertyAccessExpression, PropertyAssignment, PropertyDeclaration, PropertyName, PropertySignature, QualifiedName, QuestionDotToken, QuestionToken, ReadonlyKeyword, ReadonlyPragmaMap, ReadonlyTextRange, RestTypeNode, ReturnStatement, SatisfiesExpression, - ScriptKind, ScriptTarget, Set, SetAccessorDeclaration, setParent, setParentRecursive, setTextRange, setTextRangePos, + ScriptKind, ScriptTarget, SetAccessorDeclaration, setParent, setParentRecursive, setTextRange, setTextRangePos, setTextRangePosEnd, setTextRangePosWidth, ShorthandPropertyAssignment, skipTrivia, some, SourceFile, SpreadAssignment, SpreadElement, startsWith, Statement, StringLiteral, supportedDeclarationExtensions, SwitchStatement, SyntaxKind, TaggedTemplateExpression, TemplateExpression, TemplateHead, TemplateLiteralToken, @@ -1132,8 +1132,8 @@ namespace Parser { let currentToken: SyntaxKind; let nodeCount: number; - let identifiers: ESMap; - let privateIdentifiers: ESMap; + let identifiers: Map; + let privateIdentifiers: Map; let identifierCount: number; let parsingContext: ParsingContext; diff --git a/src/compiler/performance.ts b/src/compiler/performance.ts index 774f0880e0668..2f0892b17dc1d 100644 --- a/src/compiler/performance.ts +++ b/src/compiler/performance.ts @@ -1,5 +1,5 @@ import { - Debug, Map, noop, Performance, PerformanceHooks, sys, System, timestamp, tryGetNativePerformanceHooks, + Debug, noop, Performance, PerformanceHooks, sys, System, timestamp, tryGetNativePerformanceHooks, } from "./_namespaces/ts"; /** Performance measurements for the compiler. */ diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 0ac682ac4b77f..4810c913eecfa 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -14,7 +14,7 @@ import { diagnosticCategoryName, DiagnosticMessage, DiagnosticMessageChain, DiagnosticReporter, Diagnostics, DiagnosticWithLocation, directorySeparator, DirectoryStructureHost, emitFiles, EmitFlags, EmitHost, EmitOnly, EmitResult, emptyArray, ensureTrailingDirectorySeparator, equateStringsCaseInsensitive, equateStringsCaseSensitive, - ESMap, explainIfFileIsRedirectAndImpliedFormat, ExportAssignment, ExportDeclaration, Extension, extensionFromPath, + explainIfFileIsRedirectAndImpliedFormat, ExportAssignment, ExportDeclaration, Extension, extensionFromPath, externalHelpersModuleNameText, factory, fileExtensionIs, fileExtensionIsOneOf, FileIncludeKind, FileIncludeReason, fileIncludeReasonToDiagnostics, FilePreprocessingDiagnostics, FilePreprocessingDiagnosticsKind, FileReference, filter, find, firstDefined, firstDefinedIterator, flatMap, flatten, forEach, forEachAncestorDirectory, forEachChild, @@ -39,7 +39,7 @@ import { isImportDeclaration, isImportEqualsDeclaration, isImportSpecifier, isImportTypeNode, isIncrementalCompilation, isInJSFile, isLiteralImportTypeNode, isModifier, isModuleDeclaration, isObjectLiteralExpression, isPlainJsFile, isRequireCall, isRootedDiskPath, isSourceFileJS, isString, isStringLiteral, isStringLiteralLike, isTraceEnabled, - JsonSourceFile, JsxEmit, length, libMap, libs, Map, mapDefined, mapDefinedIterator, maybeBind, memoize, + JsonSourceFile, JsxEmit, length, libMap, libs, mapDefined, mapDefinedIterator, maybeBind, memoize, MethodDeclaration, ModifierFlags, ModifierLike, ModuleBlock, ModuleDeclaration, ModuleKind, ModuleResolutionCache, ModuleResolutionHost, ModuleResolutionInfo, moduleResolutionIsEqualTo, ModuleResolutionKind, Mutable, Node, NodeArray, NodeFlags, nodeModulesPathPart, NodeWithTypeArguments, noop, normalizePath, notImplementedResolver, @@ -50,7 +50,7 @@ import { PropertyDeclaration, ReferencedFile, removeFileExtension, removePrefix, removeSuffix, resolutionExtensionIsTSOrJson, resolveConfigFileProjectName, ResolvedConfigFileName, ResolvedModuleFull, ResolvedModuleWithFailedLookupLocations, ResolvedProjectReference, ResolvedTypeReferenceDirective, resolveModuleName, resolveModuleNameFromCache, - resolveTypeReferenceDirective, returnFalse, returnUndefined, SatisfiesExpression, ScriptKind, ScriptTarget, Set, + resolveTypeReferenceDirective, returnFalse, returnUndefined, SatisfiesExpression, ScriptKind, ScriptTarget, setParent, setParentRecursive, setResolvedModule, setResolvedTypeReferenceDirective, skipTrivia, skipTypeChecking, some, sortAndDeduplicateDiagnostics, SortedReadonlyArray, SourceFile, sourceFileAffectingCompilerOptions, sourceFileMayBeEmitted, SourceOfProjectReferenceRedirect, stableSort, startsWith, Statement, stringContains, @@ -253,7 +253,7 @@ export function changeCompilerHostLikeToUseCache( const readFileCache = new Map(); const fileExistsCache = new Map(); const directoryExistsCache = new Map(); - const sourceFileCache = new Map>(); + const sourceFileCache = new Map>(); const readFileWithCache = (fileName: string): string | undefined => { const key = toPath(fileName); @@ -636,7 +636,7 @@ export function isExclusivelyTypeOnlyImportOrExport(decl: ImportDeclaration | Ex * @param usage The module reference string * @returns The final resolution mode of the import */ -export function getModeForUsageLocation(file: {impliedNodeFormat?: SourceFile["impliedNodeFormat"]}, usage: StringLiteralLike) { +export function getModeForUsageLocation(file: { impliedNodeFormat?: SourceFile["impliedNodeFormat"] }, usage: StringLiteralLike) { if (file.impliedNodeFormat === undefined) return undefined; if ((isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent))) { const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent); @@ -760,7 +760,7 @@ function forEachProjectReference( export const inferredTypesContainingFile = "__inferred type names__.ts"; interface DiagnosticCache { - perFile?: ESMap; + perFile?: Map; allDiagnostics?: readonly T[]; } @@ -885,7 +885,7 @@ export function isProgramUptoDate( function resolvedProjectReferenceUptoDate(oldResolvedRef: ResolvedProjectReference | undefined, oldRef: ProjectReference): boolean { if (oldResolvedRef) { - // Assume true + // Assume true if (contains(seenResolvedRefs, oldResolvedRef)) return true; const refPath = resolveProjectReferencePath(oldRef); @@ -948,8 +948,8 @@ export function getImpliedNodeFormatForFileWorker( case ModuleResolutionKind.NodeNext: return fileExtensionIsOneOf(fileName, [Extension.Dmts, Extension.Mts, Extension.Mjs]) ? ModuleKind.ESNext : fileExtensionIsOneOf(fileName, [Extension.Dcts, Extension.Cts, Extension.Cjs]) ? ModuleKind.CommonJS : - fileExtensionIsOneOf(fileName, [Extension.Dts, Extension.Ts, Extension.Tsx, Extension.Js, Extension.Jsx]) ? lookupFromPackageJson() : - undefined; // other extensions, like `json` or `tsbuildinfo`, are set as `undefined` here but they should never be fed through the transformer pipeline + fileExtensionIsOneOf(fileName, [Extension.Dts, Extension.Ts, Extension.Tsx, Extension.Js, Extension.Jsx]) ? lookupFromPackageJson() : + undefined; // other extensions, like `json` or `tsbuildinfo`, are set as `undefined` here but they should never be fed through the transformer pipeline default: return undefined; } @@ -1250,9 +1250,9 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files let resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined; - let projectReferenceRedirects: ESMap | undefined; - let mapFromFileToProjectReferenceRedirects: ESMap | undefined; - let mapFromToProjectReferenceRedirectSource: ESMap | undefined; + let projectReferenceRedirects: Map | undefined; + let mapFromFileToProjectReferenceRedirects: Map | undefined; + let mapFromToProjectReferenceRedirectSource: Map | undefined; const useSourceOfProjectReferenceRedirect = !!host.useSourceOfProjectReferenceRedirect?.() && !options.disableSourceOfProjectReferenceRedirect; @@ -2309,7 +2309,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } function getCachedSemanticDiagnostics(sourceFile?: SourceFile): readonly Diagnostic[] | undefined { - return sourceFile + return sourceFile ? cachedBindAndCheckDiagnosticsForFile.perFile?.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics; } @@ -2400,7 +2400,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // - check JS: .js files with either // ts-check or checkJs: true // - external: files that are added by plugins const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX - || sourceFile.scriptKind === ScriptKind.External || isPlainJs || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred); + || sourceFile.scriptKind === ScriptKind.External || isPlainJs || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred); let bindDiagnostics: readonly Diagnostic[] = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray; let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray; if (isPlainJs) { diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 2e52acb3cc02c..808df7d4ab4d0 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -3,18 +3,18 @@ import { arrayToMap, CachedDirectoryStructureHost, CacheWithRedirects, CharacterCodes, clearMap, closeFileWatcher, closeFileWatcherOf, CompilerOptions, contains, createCacheWithRedirects, createModeAwareCache, createModuleResolutionCache, createMultiMap, createTypeReferenceDirectiveResolutionCache, Debug, Diagnostics, - directorySeparator, DirectoryWatcherCallback, emptyArray, emptyIterator, endsWith, ESMap, Extension, extensionIsTS, + directorySeparator, DirectoryWatcherCallback, emptyArray, emptyIterator, endsWith, Extension, extensionIsTS, fileExtensionIs, fileExtensionIsOneOf, FileReference, FileWatcher, FileWatcherCallback, firstDefinedIterator, GetCanonicalFileName, getDirectoryPath, getEffectiveTypeRoots, getModeForFileReference, getModeForResolutionAtIndex, getModeForUsageLocation, getNormalizedAbsolutePath, getResolutionName, getRootLength, HasInvalidatedResolutions, ignoredPaths, inferredTypesContainingFile, isEmittedFileOfProgram, isExternalModuleNameRelative, isExternalOrCommonJsModule, isNodeModulesDirectory, isRootedDiskPath, isString, isStringLiteralLike, isTraceEnabled, - length, loadModuleFromGlobalCache, Map, memoize, MinimalResolutionCacheHost, ModeAwareCache, ModuleKind, + length, loadModuleFromGlobalCache, memoize, MinimalResolutionCacheHost, ModeAwareCache, ModuleKind, ModuleResolutionCache, ModuleResolutionHost, ModuleResolutionInfo, mutateMap, noopFileWatcher, normalizePath, PackageId, packageIdToString, parseNodeModuleFromPath, Path, pathContainsNodeModules, PerModuleNameCache, Program, - ReadonlyESMap, removeSuffix, removeTrailingDirectorySeparator, resolutionExtensionIsTSOrJson, ResolvedModuleFull, + removeSuffix, removeTrailingDirectorySeparator, resolutionExtensionIsTSOrJson, ResolvedModuleFull, ResolvedModuleWithFailedLookupLocations, ResolvedProjectReference, ResolvedTypeReferenceDirective, - ResolvedTypeReferenceDirectiveWithFailedLookupLocations, returnTrue, Set, some, SourceFile, startsWith, + ResolvedTypeReferenceDirectiveWithFailedLookupLocations, returnTrue, some, SourceFile, startsWith, stringContains, trace, TypeReferenceDirectiveResolutionInfo, unorderedRemoveItem, WatchDirectoryFlags, } from "./_namespaces/ts"; @@ -48,7 +48,7 @@ export interface ResolutionCache { invalidateResolutionOfFile(filePath: Path): void; removeResolutionsOfFile(filePath: Path): void; removeResolutionsFromProjectReferenceRedirects(filePath: Path): void; - setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: ESMap): void; + setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: Map): void; createHasInvalidatedResolutions(customHasInvalidatedResolutions: HasInvalidatedResolutions): HasInvalidatedResolutions; hasChangedAutomaticTypeDirectiveNames(): boolean; isFileWithInvalidatedNonRelativeUnresolvedImports(path: Path): boolean; @@ -201,7 +201,7 @@ type GetResolutionWithResolvedFileName | undefined; - let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyESMap | undefined; + let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyMap | undefined; const nonRelativeExternalModuleResolutions = createMultiMap(); const resolutionsWithFailedLookups: ResolutionWithFailedLookupLocations[] = []; @@ -445,7 +445,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD names: readonly string[] | readonly FileReference[]; containingFile: string; redirectedReference: ResolvedProjectReference | undefined; - cache: ESMap>; + cache: Map>; perDirectoryCacheWithRedirects: CacheWithRedirects>; loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, containingSourceFile?: SourceFile, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext | undefined) => T; getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName; @@ -517,8 +517,8 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD loader === resolveModuleName as unknown ? resolved?.resolvedFileName ? resolved.packagetId ? - Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: - Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: + Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4 : + Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved : resolved?.resolvedFileName ? resolved.packagetId ? @@ -966,7 +966,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD } function removeResolutionsOfFileFromCache( - cache: ESMap>, + cache: Map>, filePath: Path, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, ) { @@ -1023,7 +1023,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD } } - function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyESMap) { + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyMap) { Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index ee1439635cd78..643df8727844c 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -1,7 +1,7 @@ import { append, arraysEqual, binarySearch, CharacterCodes, CommentDirective, CommentDirectiveType, CommentKind, - CommentRange, compareValues, Debug, DiagnosticMessage, Diagnostics, ESMap, getEntries, identity, JSDocSyntaxKind, - JsxTokenSyntaxKind, KeywordSyntaxKind, LanguageVariant, LineAndCharacter, Map, MapLike, parsePseudoBigInt, + CommentRange, compareValues, Debug, DiagnosticMessage, Diagnostics, getEntries, identity, JSDocSyntaxKind, + JsxTokenSyntaxKind, KeywordSyntaxKind, LanguageVariant, LineAndCharacter, MapLike, parsePseudoBigInt, positionIsSynthesized, ScriptTarget, SourceFileLike, SyntaxKind, TokenFlags, trimStringStart, } from "./_namespaces/ts"; @@ -347,7 +347,7 @@ function isUnicodeIdentifierPart(code: number, languageVersion: ScriptTarget | u lookupInUnicodeMap(code, unicodeES3IdentifierPart); } -function makeReverseMap(source: ESMap): string[] { +function makeReverseMap(source: Map): string[] { const result: string[] = []; source.forEach((value, name) => { result[value] = name; diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index 4471ed5ad4ba3..3c86ba8564dc2 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -1,8 +1,8 @@ import { arrayFrom, binarySearchKey, CharacterCodes, combinePaths, compareValues, Debug, DocumentPosition, - DocumentPositionMapper, DocumentPositionMapperHost, EmitHost, emptyArray, ESMap, every, getDirectoryPath, + DocumentPositionMapper, DocumentPositionMapperHost, EmitHost, emptyArray, every, getDirectoryPath, getNormalizedAbsolutePath, getPositionOfLineAndCharacter, getRelativePathToDirectoryOrUrl, identity, isArray, - isString, Iterator, LineAndCharacter, Map, RawSourceMap, some, sortAndDeduplicate, SortedReadonlyArray, + isString, LineAndCharacter, RawSourceMap, some, sortAndDeduplicate, SortedReadonlyArray, SourceMapGenerator, trimStringEnd, } from "./_namespaces/ts"; import * as performance from "./_namespaces/ts.performance"; @@ -25,7 +25,7 @@ export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoo let sourcesContent: (string | null)[] | undefined; const names: string[] = []; - let nameToNameIndexMap: ESMap | undefined; + let nameToNameIndexMap: Map | undefined; const mappingCharCodes: number[] = []; let mappings = ""; diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index e3f3174e452cb..31df7422cd14e 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -1,9 +1,9 @@ import { AssertionLevel, closeFileWatcher, closeFileWatcherOf, combinePaths, Comparison, contains, containsPath, createGetCanonicalFileName, createMultiMap, Debug, directorySeparator, emptyArray, emptyFileSystemEntries, endsWith, - enumerateInsertsAndDeletes, ESMap, FileSystemEntries, getDirectoryPath, getFallbackOptions, + enumerateInsertsAndDeletes, FileSystemEntries, getDirectoryPath, getFallbackOptions, getNormalizedAbsolutePath, getRelativePathToDirectoryOrUrl, getRootLength, getStringComparer, isArray, isNodeLikeSystem, isString, - Map, mapDefined, matchesExclude, matchFiles, memoize, noop, normalizePath, normalizeSlashes, orderedRemoveItem, + mapDefined, matchesExclude, matchFiles, memoize, noop, normalizePath, normalizeSlashes, orderedRemoveItem, Path, perfLogger, PollingWatchKind, RequireResult, resolveJSModule, some, startsWith, stringContains, timestamp, unorderedRemoveItem, WatchDirectoryKind, WatchFileKind, WatchOptions, writeFileEnsuringDirectories, } from "./_namespaces/ts"; @@ -434,7 +434,7 @@ interface SingleFileWatcher{ callbacks: T[]; } function createSingleWatcherPerName( - cache: Map>, + cache: Map>, useCaseSensitiveFileNames: boolean, name: string, callback: T, @@ -610,7 +610,7 @@ function createDirectoryWatcherSupportingRecursive({ }; } - type InvokeMap = ESMap; + type InvokeMap = Map; function invokeCallbacks(dirPath: Path, fileName: string): void; function invokeCallbacks(dirPath: Path, invokeMap: InvokeMap, fileNames: string[] | undefined): void; function invokeCallbacks(dirPath: Path, fileNameOrInvokeMap: string | InvokeMap, fileNames?: string[]) { diff --git a/src/compiler/tracing.ts b/src/compiler/tracing.ts index 2102592d1a6d9..f53b477c5dac4 100644 --- a/src/compiler/tracing.ts +++ b/src/compiler/tracing.ts @@ -1,6 +1,6 @@ import { combinePaths, ConditionalType, Debug, EvolvingArrayType, getLineAndCharacterOfPosition, getSourceFileOfNode, - IndexedAccessType, IndexType, IntersectionType, LineAndCharacter, Map, Node, ObjectFlags, Path, ReverseMappedType, + IndexedAccessType, IndexType, IntersectionType, LineAndCharacter, Node, ObjectFlags, Path, ReverseMappedType, SubstitutionType, timestamp, Type, TypeFlags, TypeReference, unescapeLeadingUnderscores, UnionType, } from "./_namespaces/ts"; import * as performance from "./_namespaces/ts.performance"; diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index 28be1f5f87a43..e007a7d7475a8 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -5,7 +5,7 @@ import { classOrConstructorParameterIsDecorated, ClassStaticBlockDeclaration, compact, ComputedPropertyName, ConstructorDeclaration, createAccessorPropertyBackingField, createAccessorPropertyGetRedirector, createAccessorPropertySetRedirector, createMemberAccessForPropertyName, Debug, ElementAccessExpression, EmitFlags, - EmitHint, ESMap, expandPreOrPostfixIncrementOrDecrementExpression, Expression, ExpressionStatement, + EmitHint, expandPreOrPostfixIncrementOrDecrementExpression, Expression, ExpressionStatement, ExpressionWithTypeArguments, factory, filter, findSuperStatementIndex, ForStatement, GeneratedIdentifier, GeneratedIdentifierFlags, GeneratedNamePart, GeneratedPrivateIdentifier, GetAccessorDeclaration, getCommentRange, getEffectiveBaseTypeNode, getEmitFlags, getEmitScriptTarget, getInitializerOfBindingOrAssignmentElement, @@ -24,7 +24,7 @@ import { isPropertyAssignment, isPropertyDeclaration, isPropertyName, isSetAccessor, isSetAccessorDeclaration, isShorthandPropertyAssignment, isSimpleCopiableExpression, isSimpleInlineableExpression, isSpreadAssignment, isSpreadElement, isStatement, isStatic, isStaticModifier, isSuperProperty, isTemplateLiteral, isThisProperty, - LeftHandSideExpression, map, Map, MethodDeclaration, Modifier, ModifierFlags, moveRangePastModifiers, moveRangePos, + LeftHandSideExpression, map, MethodDeclaration, Modifier, ModifierFlags, moveRangePastModifiers, moveRangePos, Node, NodeCheckFlags, nodeIsSynthesized, ObjectLiteralElementLike, PostfixUnaryExpression, PrefixUnaryExpression, PrivateIdentifier, PrivateIdentifierPropertyAccessExpression, PrivateIdentifierPropertyDeclaration, PropertyAccessExpression, PropertyDeclaration, PropertyName, ScriptTarget, SetAccessorDeclaration, setCommentRange, @@ -135,7 +135,7 @@ interface PrivateIdentifierEnvironment { /** * A mapping of generated private names to information needed for transformation. */ - generatedIdentifiers?: ESMap; + generatedIdentifiers?: Map; } interface ClassLexicalEnvironment { diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 3e0eaed09cb96..481846566c9f9 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -6,7 +6,7 @@ import { createEmptyExports, createGetSymbolAccessibilityDiagnosticForNode, createGetSymbolAccessibilityDiagnosticForNodeName, createSymbolTable, createUnparsedSourceFile, Debug, Declaration, DeclarationDiagnosticProducing, DeclarationName, declarationNameToString, Diagnostics, DiagnosticWithLocation, - EmitFlags, EmitHost, EmitResolver, emptyArray, EntityNameOrEntityNameExpression, EnumDeclaration, ESMap, + EmitFlags, EmitHost, EmitResolver, emptyArray, EntityNameOrEntityNameExpression, EnumDeclaration, ExportAssignment, ExportDeclaration, ExpressionWithTypeArguments, factory, FileReference, filter, flatMap, flatten, forEach, FunctionDeclaration, FunctionTypeNode, GeneratedIdentifierFlags, GetAccessorDeclaration, getCommentRange, getDirectoryPath, getEffectiveBaseTypeNode, getEffectiveModifierFlags, @@ -27,11 +27,11 @@ import { isSemicolonClassElement, isSetAccessorDeclaration, isSourceFile, isSourceFileJS, isSourceFileNotJson, isStringANonContextualKeyword, isStringLiteral, isStringLiteralLike, isTupleTypeNode, isTypeAliasDeclaration, isTypeNode, isTypeParameterDeclaration, isTypeQueryNode, isUnparsedSource, last, LateBoundDeclaration, - LateVisibilityPaintedStatement, length, map, Map, mapDefined, MethodDeclaration, MethodSignature, Modifier, + LateVisibilityPaintedStatement, length, map, mapDefined, MethodDeclaration, MethodSignature, Modifier, ModifierFlags, ModuleBody, ModuleDeclaration, NamedDeclaration, NamespaceDeclaration, needsScopeMarker, Node, NodeArray, NodeBuilderFlags, NodeFlags, NodeId, normalizeSlashes, OmittedExpression, orderedRemoveItem, ParameterDeclaration, parseNodeFactory, pathContainsNodeModules, pathIsRelative, - PropertyDeclaration, PropertySignature, pushIfUnique, removeAllComments, Set, SetAccessorDeclaration, + PropertyDeclaration, PropertySignature, pushIfUnique, removeAllComments, SetAccessorDeclaration, setCommentRange, setEmitFlags, setOriginalNode, setParent, setTextRange, SignatureDeclaration, skipTrivia, some, SourceFile, startsWith, Statement, stringContains, StringLiteral, Symbol, SymbolAccessibility, SymbolAccessibilityResult, SymbolFlags, SymbolTracker, SyntaxKind, toFileNameLowerCase, toPath, @@ -105,7 +105,7 @@ export function transformDeclarations(context: TransformationContext) { let enclosingDeclaration: Node; let necessaryTypeReferences: Set<[specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]> | undefined; let lateMarkedStatements: LateVisibilityPaintedStatement[] | undefined; - let lateStatementReplacementMap: ESMap>; + let lateStatementReplacementMap: Map>; let suppressNewDiagnosticContexts: boolean; let exportedModulesFromDeclarationEmit: Symbol[] | undefined; @@ -130,8 +130,8 @@ export function transformDeclarations(context: TransformationContext) { let errorFallbackNode: Declaration | undefined; let currentSourceFile: SourceFile; - let refs: ESMap; - let libs: ESMap; + let refs: Map; + let libs: Map; let emittedImports: readonly AnyImportSyntax[] | undefined; // must be declared in container so it can be `undefined` while transformer's first pass const resolver = context.getEmitResolver(); const options = context.getCompilerOptions(); @@ -477,7 +477,7 @@ export function transformDeclarations(context: TransformationContext) { } } - function collectReferences(sourceFile: SourceFile | UnparsedSource, ret: ESMap) { + function collectReferences(sourceFile: SourceFile | UnparsedSource, ret: Map) { if (noResolve || (!isUnparsedSource(sourceFile) && isSourceFileJS(sourceFile))) return ret; forEach(sourceFile.referencedFiles, f => { const elem = host.getSourceFileFromReference(sourceFile, f); @@ -488,7 +488,7 @@ export function transformDeclarations(context: TransformationContext) { return ret; } - function collectLibs(sourceFile: SourceFile | UnparsedSource, ret: ESMap) { + function collectLibs(sourceFile: SourceFile | UnparsedSource, ret: Map) { forEach(sourceFile.libReferenceDirectives, ref => { const lib = host.getLibFileFromReference(ref); if (lib) { diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 545c48a3dd6e3..7168440df8da1 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -4,7 +4,7 @@ import { Block, BreakOrContinueStatement, CallExpression, CaseBlock, CaseClause, cast, CatchClause, chainBundle, ClassDeclaration, ClassElement, ClassExpression, ClassLikeDeclaration, CommaListExpression, ComputedPropertyName, concatenate, ConstructorDeclaration, createExpressionForPropertyName, createMemberAccessForPropertyName, - createRange, createTokenRange, Debug, Declaration, DoStatement, elementAt, EmitFlags, EmitHint, emptyArray, ESMap, + createRange, createTokenRange, Debug, Declaration, DoStatement, elementAt, EmitFlags, EmitHint, emptyArray, Expression, ExpressionStatement, ExpressionWithTypeArguments, filter, first, firstOrUndefined, flatMap, flatten, flattenDestructuringAssignment, flattenDestructuringBinding, FlattenLevel, ForInStatement, ForOfStatement, ForStatement, FunctionBody, FunctionDeclaration, FunctionExpression, FunctionLikeDeclaration, @@ -22,7 +22,7 @@ import { isPrologueDirective, isPropertyDeclaration, isPropertyName, isReturnStatement, isSpreadElement, isStatement, isStatic, isSuperProperty, isSwitchStatement, isTryStatement, isVariableDeclarationList, isVariableStatement, isWithStatement, IterationStatement, LabeledStatement, last, lastOrUndefined, LeftHandSideExpression, - LiteralExpression, map, Map, MetaProperty, MethodDeclaration, ModifierFlags, moveRangeEnd, moveRangePos, + LiteralExpression, map, MetaProperty, MethodDeclaration, ModifierFlags, moveRangeEnd, moveRangePos, moveSyntheticComments, NamedDeclaration, NewExpression, Node, NodeArray, NodeCheckFlags, NodeFlags, nodeIsSynthesized, NumericLiteral, ObjectLiteralElementLike, ObjectLiteralExpression, ParameterDeclaration, ParenthesizedExpression, PrimaryExpression, ProcessLevel, processTaggedTemplateExpression, PropertyAssignment, @@ -108,15 +108,15 @@ interface ConvertedLoopState { * set of labels that occurred inside the converted loop * used to determine if labeled jump can be emitted as is or it should be dispatched to calling code */ - labels?: ESMap; + labels?: Map; /* * collection of labeled jumps that transfer control outside the converted loop. * maps store association 'label -> labelMarker' where * - label - value of label as it appear in code * - label marker - return value that should be interpreted by calling code as 'jump to