Skip to content

Add alias ResolutionMode for ModuleKind.ESNext | ModuleKind.CommonJs | undefined #51482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 11, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/compiler/builderState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
ExportedModulesFromDeclarationEmit, GetCanonicalFileName, getDirectoryPath, getSourceFileOfNode,
isDeclarationFileName, isExternalOrCommonJsModule, isGlobalScopeAugmentation, isJsonSourceFile,
isModuleWithStringLiteralName, isStringLiteral, mapDefined, mapDefinedIterator, ModuleDeclaration,
ModuleKind, outFile, OutputFile, Path, Program, some, SourceFile, StringLiteralLike, Symbol,
ModuleKind, outFile, OutputFile, Path, Program, ResolutionMode, some, SourceFile, StringLiteralLike, Symbol,
toPath, TypeChecker,
} from "./_namespaces/ts";

Expand Down Expand Up @@ -75,7 +75,7 @@ export namespace BuilderState {
readonly version: string;
signature: string | undefined;
affectsGlobalScope: true | undefined;
impliedFormat: SourceFile["impliedNodeFormat"];
impliedFormat: ResolutionMode;
}

export interface ReadonlyManyToManyPathMap {
Expand Down
20 changes: 10 additions & 10 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ import {
usingSingleLineStringWriter, VariableDeclaration, VariableDeclarationList, VariableLikeDeclaration,
VariableStatement, VarianceFlags, visitEachChild, visitNode, visitNodes, Visitor, VisitResult, VoidExpression,
walkUpBindingElementsAndPatterns, walkUpParenthesizedExpressions, walkUpParenthesizedTypes,
walkUpParenthesizedTypesAndGetParentAndChild, WhileStatement, WideningContext, WithStatement, YieldExpression,
walkUpParenthesizedTypesAndGetParentAndChild, WhileStatement, WideningContext, WithStatement, YieldExpression, ResolutionMode,
} from "./_namespaces/ts";
import * as performance from "./_namespaces/ts.performance";
import * as moduleSpecifiers from "./_namespaces/ts.moduleSpecifiers";
Expand Down Expand Up @@ -2969,7 +2969,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return isStringLiteralLike(usage) ? getModeForUsageLocation(getSourceFileOfNode(usage), usage) : undefined;
}

function isESMFormatImportImportingCommonjsFormatFile(usageMode: SourceFile["impliedNodeFormat"], targetMode: SourceFile["impliedNodeFormat"]) {
function isESMFormatImportImportingCommonjsFormatFile(usageMode: ResolutionMode, targetMode: ResolutionMode) {
return usageMode === ModuleKind.ESNext && targetMode === ModuleKind.CommonJS;
}

Expand Down Expand Up @@ -6559,7 +6559,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return top;
}

function getSpecifierForModuleSymbol(symbol: Symbol, context: NodeBuilderContext, overrideImportMode?: SourceFile["impliedNodeFormat"]) {
function getSpecifierForModuleSymbol(symbol: Symbol, context: NodeBuilderContext, overrideImportMode?: ResolutionMode) {
let file = getDeclarationOfKind<SourceFile>(symbol, SyntaxKind.SourceFile);
if (!file) {
const equivalentFileSymbol = firstDefined(symbol.declarations, d => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol));
Expand Down Expand Up @@ -6623,7 +6623,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
return specifier;

function getSpecifierCacheKey(path: string, mode: SourceFile["impliedNodeFormat"] | undefined) {
function getSpecifierCacheKey(path: string, mode: ResolutionMode | undefined) {
return mode === undefined ? path : `${mode}|${path}`;
}
}
Expand Down Expand Up @@ -44091,10 +44091,10 @@ 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: Map<string, [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]>;
let fileToDirective: Map<string, [specifier: string, mode: ResolutionMode | undefined]>;
if (resolvedTypeReferenceDirectives) {
// populate reverse mapping: file path -> type reference directive that was resolved to this file
fileToDirective = new Map<string, [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]>();
fileToDirective = new Map<string, [specifier: string, mode: ResolutionMode | undefined]>();
resolvedTypeReferenceDirectives.forEach((resolvedDirective, key, mode) => {
if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
return;
Expand Down Expand Up @@ -44226,7 +44226,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

// defined here to avoid outer scope pollution
function getTypeReferenceDirectivesForEntityName(node: EntityNameOrEntityNameExpression): [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined {
function getTypeReferenceDirectivesForEntityName(node: EntityNameOrEntityNameExpression): [specifier: string, mode: ResolutionMode | undefined][] | undefined {
// program does not have any files with type reference directives - bail out
if (!fileToDirective) {
return undefined;
Expand All @@ -44251,13 +44251,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

// defined here to avoid outer scope pollution
function getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined {
function getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): [specifier: string, mode: ResolutionMode | undefined][] | undefined {
// program does not have any files with type reference directives - bail out
if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) {
return undefined;
}
// check what declarations in the symbol can contribute to the target meaning
let typeReferenceDirectives: [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined;
let typeReferenceDirectives: [specifier: string, mode: ResolutionMode | undefined][] | undefined;
for (const decl of symbol.declarations!) {
// check meaning of the local symbol to see if declaration needs to be analyzed further
if (decl.symbol && decl.symbol.flags & meaning!) {
Expand Down Expand Up @@ -44308,7 +44308,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return false;
}

function addReferencedFilesToTypeDirective(file: SourceFile, key: string, mode: SourceFile["impliedNodeFormat"] | undefined) {
function addReferencedFilesToTypeDirective(file: SourceFile, key: string, mode: ResolutionMode | undefined) {
if (fileToDirective.has(file.path)) return;
fileToDirective.set(file.path, [key, mode]);
for (const { fileName, resolutionMode } of file.referencedFiles) {
Expand Down
31 changes: 16 additions & 15 deletions src/compiler/moduleNameResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
ModuleKind, ModuleResolutionHost, ModuleResolutionKind, noop, noopPush, normalizePath, normalizeSlashes,
optionsHaveModuleResolutionChanges, PackageId, packageIdToString, ParsedCommandLine, Path, pathIsRelative, Pattern,
patternText, perfLogger, Push, readJson, removeExtension, removeFileExtension, removePrefix,
ResolutionMode,
ResolvedModuleWithFailedLookupLocations, ResolvedProjectReference, ResolvedTypeReferenceDirective,
ResolvedTypeReferenceDirectiveWithFailedLookupLocations, some, sort, SourceFile, startsWith, stringContains,
StringLiteralLike, supportedTSExtensionsFlat, toFileNameLowerCase, toPath, tryExtractTSExtension, tryGetExtensionFromPath,
Expand Down Expand Up @@ -333,7 +334,7 @@ function arePathsEqual(path1: string, path2: string, host: ModuleResolutionHost)
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache, resolutionMode?: SourceFile["impliedNodeFormat"]): ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache, resolutionMode?: ResolutionMode): ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
Debug.assert(typeof typeReferenceDirectiveName === "string", "Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.");
const traceEnabled = isTraceEnabled(options, host);
if (redirectedReference) {
Expand Down Expand Up @@ -571,11 +572,11 @@ export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResol
}

export interface ModeAwareCache<T> {
get(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): T | undefined;
set(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, value: T): this;
delete(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): this;
has(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): boolean;
forEach(cb: (elem: T, key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined) => void): void;
get(key: string, mode: ResolutionMode): T | undefined;
set(key: string, mode: ResolutionMode, value: T): this;
delete(key: string, mode: ResolutionMode): this;
has(key: string, mode: ResolutionMode): boolean;
forEach(cb: (elem: T, key: string, mode: ResolutionMode) => void): void;
size(): number;
}

Expand Down Expand Up @@ -603,7 +604,7 @@ export interface ModuleResolutionCache extends PerDirectoryResolutionCache<Resol
* We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive.
*/
export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache {
getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, redirectedReference?: ResolvedProjectReference): PerModuleNameCache;
getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerModuleNameCache;
}

export interface PackageJsonInfoCache {
Expand Down Expand Up @@ -758,7 +759,7 @@ function createPerDirectoryResolutionCache<T>(currentDirectory: string, getCanon
export function createModeAwareCache<T>(): ModeAwareCache<T> {
const underlying = new Map<ModeAwareCacheKey, T>();
type ModeAwareCacheKey = string & { __modeAwareCacheKey: any; };
const memoizedReverseKeys = new Map<ModeAwareCacheKey, [specifier: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined]>();
const memoizedReverseKeys = new Map<ModeAwareCacheKey, [specifier: string, mode: ResolutionMode]>();

const cache: ModeAwareCache<T> = {
get(specifier, mode) {
Expand Down Expand Up @@ -787,7 +788,7 @@ export function createModeAwareCache<T>(): ModeAwareCache<T> {
};
return cache;

function getUnderlyingCacheKey(specifier: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined) {
function getUnderlyingCacheKey(specifier: string, mode: ResolutionMode) {
const result = (mode === undefined ? specifier : `${mode}|${specifier}`) as ModeAwareCacheKey;
memoizedReverseKeys.set(result, [specifier, mode]);
return result;
Expand Down Expand Up @@ -864,7 +865,7 @@ export function createModuleResolutionCache(
updateRedirectsMap(options, directoryToModuleNameMap!, moduleNameToDirectoryMap);
}

function getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, redirectedReference?: ResolvedProjectReference): PerModuleNameCache {
function getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerModuleNameCache {
Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName));
return getOrCreateCache(moduleNameToDirectoryMap!, redirectedReference, mode === undefined ? nonRelativeModuleName : `${mode}|${nonRelativeModuleName}`, createPerModuleNameCache);
}
Expand Down Expand Up @@ -983,14 +984,14 @@ export function createTypeReferenceDirectiveResolutionCache(
}
}

export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache, mode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations | undefined {
export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache, mode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations | undefined {
const containingDirectory = getDirectoryPath(containingFile);
const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
if (!perFolderCache) return undefined;
return perFolderCache.get(moduleName, mode);
}

export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
if (redirectedReference) {
compilerOptions = redirectedReference.commandLine.options;
Expand Down Expand Up @@ -1312,7 +1313,7 @@ export enum NodeResolutionFeatures {

function node16ModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions,
host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference,
resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
return nodeNextModuleNameResolverWorker(
NodeResolutionFeatures.Node16Default,
moduleName,
Expand All @@ -1327,7 +1328,7 @@ 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 {
resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
return nodeNextModuleNameResolverWorker(
NodeResolutionFeatures.NodeNextDefault,
moduleName,
Expand All @@ -1344,7 +1345,7 @@ const jsOnlyExtensions = [Extensions.JavaScript];
const tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
const tsPlusJsonExtensions = [...tsExtensions, Extensions.Json];
const tsconfigExtensions = [Extensions.TSConfig];
function nodeNextModuleNameResolverWorker(features: NodeResolutionFeatures, moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
function nodeNextModuleNameResolverWorker(features: NodeResolutionFeatures, moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
const containingDirectory = getDirectoryPath(containingFile);

// es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features
Expand Down
8 changes: 4 additions & 4 deletions src/compiler/moduleSpecifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
ModuleSpecifierResolutionHost, NodeFlags, NodeModulePathParts, normalizePath, Path, pathContainsNodeModules,
pathIsBareSpecifier, pathIsRelative, PropertyAccessExpression, removeFileExtension, removeSuffix, resolvePath,
ScriptKind, some, SourceFile, startsWith, startsWithDirectory, stringContains, StringLiteral, Symbol, SymbolFlags,
toPath, tryGetExtensionFromPath, tryParsePatterns, TypeChecker, UserPreferences,
toPath, tryGetExtensionFromPath, tryParsePatterns, TypeChecker, UserPreferences, ResolutionMode,
} from "./_namespaces/ts";

// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
Expand Down Expand Up @@ -322,7 +322,7 @@ function getInfo(importingSourceFileName: Path, host: ModuleSpecifierResolutionH
return { getCanonicalFileName, importingSourceFileName, sourceDirectory };
}

function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: SourceFile["impliedNodeFormat"], { ending, relativePreference }: Preferences): string {
function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: ResolutionMode, { ending, relativePreference }: Preferences): string {
const { baseUrl, paths, rootDirs } = compilerOptions;
const { sourceDirectory, getCanonicalFileName } = info;
const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
Expand Down Expand Up @@ -589,7 +589,7 @@ function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol, checker: TypeCh
}
}

function getAllowedEndings(preferredEnding: Ending, compilerOptions: CompilerOptions, importMode: SourceFile["impliedNodeFormat"]) {
function getAllowedEndings(preferredEnding: Ending, compilerOptions: CompilerOptions, importMode: ResolutionMode) {
if (getEmitModuleResolutionKind(compilerOptions) >= ModuleResolutionKind.Node16 && importMode === ModuleKind.ESNext) {
return [Ending.JsExtension];
}
Expand Down Expand Up @@ -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?: ResolutionMode): string | undefined {
if (!host.fileExists || !host.readFile) {
return undefined;
}
Expand Down
Loading