Skip to content

Fix auto-imports of redirected packages while making ExportInfoMap smaller? #52718

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
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
28 changes: 15 additions & 13 deletions src/compiler/moduleSpecifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,35 +242,30 @@ function getModuleSpecifierWorker(

/** @internal */
export function tryGetModuleSpecifiersFromCache(
moduleSymbol: Symbol,
moduleSourceFile: SourceFile,
importingSourceFile: SourceFile,
host: ModuleSpecifierResolutionHost,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): readonly string[] | undefined {
return tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol,
moduleSourceFile,
importingSourceFile,
host,
userPreferences,
options)[0];
}

function tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol: Symbol,
moduleSourceFile: SourceFile,
importingSourceFile: SourceFile,
host: ModuleSpecifierResolutionHost,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): readonly [specifiers?: readonly string[], moduleFile?: SourceFile, modulePaths?: readonly ModulePath[], cache?: ModuleSpecifierCache] {
const moduleSourceFile = getSourceFileOfModule(moduleSymbol);
if (!moduleSourceFile) {
return emptyArray as [];
}

): readonly [specifiers?: readonly string[], modulePaths?: readonly ModulePath[], cache?: ModuleSpecifierCache] {
const cache = host.getModuleSpecifierCache?.();
const cached = cache?.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options);
return [cached?.moduleSpecifiers, moduleSourceFile, cached?.modulePaths, cache];
return [cached?.moduleSpecifiers, cached?.modulePaths, cache];
}

/**
Expand All @@ -289,6 +284,7 @@ export function getModuleSpecifiers(
): readonly string[] {
return getModuleSpecifiersWithCacheInfo(
moduleSymbol,
getSourceFileOfModule(moduleSymbol),
checker,
compilerOptions,
importingSourceFile,
Expand All @@ -301,6 +297,7 @@ export function getModuleSpecifiers(
/** @internal */
export function getModuleSpecifiersWithCacheInfo(
moduleSymbol: Symbol,
moduleSourceFile: SourceFile | undefined,
checker: TypeChecker,
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile,
Expand All @@ -310,11 +307,16 @@ export function getModuleSpecifiersWithCacheInfo(
): { moduleSpecifiers: readonly string[], computedWithoutCache: boolean } {
let computedWithoutCache = false;
const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
if (ambient) return { moduleSpecifiers: [ambient], computedWithoutCache };
if (ambient) {
return { moduleSpecifiers: [ambient], computedWithoutCache };
}
if (!moduleSourceFile) {
return { moduleSpecifiers: emptyArray, computedWithoutCache };
}

// eslint-disable-next-line prefer-const
let [specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol,
let [specifiers, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker(
moduleSourceFile,
importingSourceFile,
host,
userPreferences,
Expand Down
25 changes: 15 additions & 10 deletions src/services/codefixes/importFixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -564,11 +564,11 @@ function getSingleExportInfoForSymbol(symbol: Symbol, moduleSymbol: Symbol, prog
function getInfoWithChecker(checker: TypeChecker, isFromPackageJson: boolean): SymbolExportInfo | undefined {
const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions);
if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) {
return { symbol: defaultInfo.symbol, moduleSymbol, moduleFileName: undefined, exportKind: defaultInfo.exportKind, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
return { symbol: defaultInfo.symbol, moduleSymbol, moduleFile: undefined, exportKind: defaultInfo.exportKind, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
}
const named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol);
if (named && skipAlias(named, checker) === symbol) {
return { symbol: named, moduleSymbol, moduleFileName: undefined, exportKind: ExportKind.Named, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
return { symbol: named, moduleSymbol, moduleFile: undefined, exportKind: ExportKind.Named, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
}
}
}
Expand Down Expand Up @@ -800,13 +800,18 @@ function getNewImportFixes(
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution);
const getModuleSpecifiers = fromCacheOnly
? (moduleSymbol: Symbol) => ({ moduleSpecifiers: moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false })
: (moduleSymbol: Symbol, checker: TypeChecker) => moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences);
? (moduleSourceFile: SourceFile | undefined) => ({
moduleSpecifiers: moduleSourceFile && moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSourceFile, sourceFile, moduleSpecifierResolutionHost, preferences),
computedWithoutCache: false,
})
: (moduleSourceFile: SourceFile | undefined, moduleSymbol: Symbol, checker: TypeChecker) => {
return moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, moduleSourceFile, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences);
};

let computedWithoutCacheCount = 0;
const fixes = flatMap(exportInfo, (exportInfo, i) => {
const checker = getChecker(exportInfo.isFromPackageJson);
const { computedWithoutCache, moduleSpecifiers } = getModuleSpecifiers(exportInfo.moduleSymbol, checker);
const { computedWithoutCache, moduleSpecifiers } = getModuleSpecifiers(exportInfo.moduleFile, exportInfo.moduleSymbol, checker);
const importedSymbolHasValueMeaning = !!(exportInfo.targetFlags & SymbolFlags.Value);
const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ true, exportInfo.symbol, exportInfo.targetFlags, checker, compilerOptions);
computedWithoutCacheCount += computedWithoutCache ? 1 : 0;
Expand Down Expand Up @@ -969,11 +974,11 @@ function compareModuleSpecifiers(
// this if we're in a resolution mode where you can't drop trailing "/index" from paths).
function isFixPossiblyReExportingImportingFile(fix: ImportFixWithModuleSpecifier, importingFile: SourceFile, compilerOptions: CompilerOptions, toPath: (fileName: string) => Path): boolean {
if (fix.isReExport &&
fix.exportInfo?.moduleFileName &&
fix.exportInfo?.moduleFile &&
getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node10 &&
isIndexFileName(fix.exportInfo.moduleFileName)
isIndexFileName(fix.exportInfo.moduleFile.fileName)
) {
const reExportDir = toPath(getDirectoryPath(fix.exportInfo.moduleFileName));
const reExportDir = toPath(getDirectoryPath(fix.exportInfo.moduleFile.fileName));
return startsWith((importingFile.path), reExportDir);
}
return false;
Expand All @@ -995,7 +1000,7 @@ function getFixesInfoForUMDImport({ sourceFile, program, host, preferences }: Co
if (!umdSymbol) return undefined;
const symbol = checker.getAliasedSymbol(umdSymbol);
const symbolName = umdSymbol.name;
const exportInfo: readonly SymbolExportInfo[] = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: undefined, exportKind: ExportKind.UMD, targetFlags: symbol.flags, isFromPackageJson: false }];
const exportInfo: readonly SymbolExportInfo[] = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFile: undefined, exportKind: ExportKind.UMD, targetFlags: symbol.flags, isFromPackageJson: false }];
const useRequire = shouldUseRequire(sourceFile, program);
// `usagePosition` is undefined because `token` may not actually be a usage of the symbol we're importing.
// For example, we might need to import `React` in order to use an arbitrary JSX tag. We could send a position
Expand Down Expand Up @@ -1148,7 +1153,7 @@ function getExportInfos(
!toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)
) {
const checker = program.getTypeChecker();
originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, moduleFileName: toFile?.fileName, exportKind, targetFlags: skipAlias(exportedSymbol, checker).flags, isFromPackageJson });
originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, moduleFile: toFile, exportKind, targetFlags: skipAlias(exportedSymbol, checker).flags, isFromPackageJson });
}
}
forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, (moduleSymbol, sourceFile, program, isFromPackageJson) => {
Expand Down
13 changes: 6 additions & 7 deletions src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3118,10 +3118,10 @@ function getCompletionData(
symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(SymbolOriginInfoKind.SymbolMemberNoExport) };
}
else {
const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? getSourceFileOfModule(moduleSymbol)?.fileName : undefined;
const moduleFile = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? getSourceFileOfModule(moduleSymbol) : undefined;
const { moduleSpecifier } = (importSpecifierResolver ||= codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)).getModuleSpecifierForBestExportInfo([{
exportKind: ExportKind.Named,
moduleFileName: fileName,
moduleFile,
isFromPackageJson: false,
moduleSymbol,
symbol: firstAccessibleSymbol,
Expand All @@ -3135,7 +3135,7 @@ function getCompletionData(
isDefaultExport: false,
symbolName: firstAccessibleSymbol.name,
exportName: firstAccessibleSymbol.name,
fileName,
fileName: moduleFile?.fileName,
moduleSpecifier,
};
symbolToOriginInfoMap[index] = origin;
Expand Down Expand Up @@ -3470,7 +3470,7 @@ function getCompletionData(
symbolName,
exportMapKey,
exportName: exportInfo.exportKind === ExportKind.ExportEquals ? InternalSymbolName.ExportEquals : exportInfo.symbol.name,
fileName: exportInfo.moduleFileName,
fileName: exportInfo.moduleFile?.fileName,
isDefaultExport,
moduleSymbol: exportInfo.moduleSymbol,
isFromPackageJson: exportInfo.isFromPackageJson,
Expand All @@ -3485,8 +3485,7 @@ function getCompletionData(
);

function isImportableExportInfo(info: SymbolExportInfo) {
const moduleFile = tryCast(info.moduleSymbol.valueDeclaration, isSourceFile);
if (!moduleFile) {
if (!info.moduleFile) {
const moduleName = stripQuotes(info.moduleSymbol.name);
if (JsTyping.nodeCoreModules.has(moduleName) && startsWith(moduleName, "node:") !== shouldUseUriStyleNodeCoreModules(sourceFile, program)) {
return false;
Expand All @@ -3498,7 +3497,7 @@ function getCompletionData(
return isImportableFile(
info.isFromPackageJson ? packageJsonAutoImportProvider! : program,
sourceFile,
moduleFile,
info.moduleFile,
preferences,
packageJsonFilter,
getModuleSpecifierResolutionHost(info.isFromPackageJson),
Expand Down
16 changes: 8 additions & 8 deletions src/services/exportInfoMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export interface SymbolExportInfo {
readonly symbol: Symbol;
readonly moduleSymbol: Symbol;
/** Set if `moduleSymbol` is an external module, not an ambient module */
moduleFileName: string | undefined;
moduleFile: SourceFile | undefined;
exportKind: ExportKind;
targetFlags: SymbolFlags;
/** True if export was only found via the package.json AutoImportProvider (for telemetry). */
Expand Down Expand Up @@ -273,13 +273,13 @@ export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost):

function rehydrateCachedInfo(info: CachedSymbolExportInfo): SymbolExportInfo {
if (info.symbol && info.moduleSymbol) return info as SymbolExportInfo;
const { id, exportKind, targetFlags, isFromPackageJson, moduleFileName } = info;
const { id, exportKind, targetFlags, isFromPackageJson, moduleFile } = info;
const [cachedSymbol, cachedModuleSymbol] = symbols.get(id) || emptyArray;
if (cachedSymbol && cachedModuleSymbol) {
return {
symbol: cachedSymbol,
moduleSymbol: cachedModuleSymbol,
moduleFileName,
moduleFile,
exportKind,
targetFlags,
isFromPackageJson,
Expand All @@ -299,7 +299,7 @@ export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost):
return {
symbol,
moduleSymbol,
moduleFileName,
moduleFile,
exportKind,
targetFlags,
isFromPackageJson,
Expand Down Expand Up @@ -340,11 +340,11 @@ export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost):
}

function isNotShadowedByDeeperNodeModulesPackage(info: SymbolExportInfo, packageName: string | undefined) {
if (!packageName || !info.moduleFileName) return true;
if (!packageName || !info.moduleFile) return true;
const typingsCacheLocation = host.getGlobalTypingsCacheLocation();
if (typingsCacheLocation && startsWith(info.moduleFileName, typingsCacheLocation)) return true;
if (typingsCacheLocation && startsWith(info.moduleFile.fileName, typingsCacheLocation)) return true;
const packageDeepestNodeModulesPath = packages.get(packageName);
return !packageDeepestNodeModulesPath || startsWith(info.moduleFileName, packageDeepestNodeModulesPath);
return !packageDeepestNodeModulesPath || startsWith(info.moduleFile.fileName, packageDeepestNodeModulesPath);
}
}

Expand Down Expand Up @@ -444,7 +444,7 @@ function forEachExternalModule(checker: TypeChecker, allSourceFiles: readonly So
}
}
for (const sourceFile of allSourceFiles) {
if (isExternalOrCommonJsModule(sourceFile) && !isExcluded?.(sourceFile.fileName)) {
if (!sourceFile.redirectInfo && isExternalOrCommonJsModule(sourceFile) && !isExcluded?.(sourceFile.fileName)) {
cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
}
}
Expand Down
76 changes: 76 additions & 0 deletions tests/cases/fourslash/server/autoImportRedirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/// <reference path="../fourslash.ts" />

// @Filename: /tsconfig.json
//// {
//// "compilerOptions": {
//// "module": "commonjs"
//// }
//// }

// @Filename: /node_modules/foo/package.json
//// {
//// "name": "foo",
//// "version": "1.0.0"
//// }

// @Filename: /node_modules/foo/index.d.ts
//// import "duplicate";
//// export declare const foo: number;

// @Filename: /node_modules/foo/node_modules/duplicate/package.json
//// {
//// "name": "duplicate",
//// "version": "1.0.0"
//// }

// @Filename: /node_modules/foo/node_modules/duplicate/index.d.ts
//// export declare const duplicate: number;

// @Filename: /node_modules/bar/package.json
//// {
//// "name": "bar",
//// "version": "1.0.0"
//// }

// @Filename: /node_modules/bar/index.d.ts
//// import "duplicate";
//// export declare const bar: number;

// @Filename: /node_modules/bar/node_modules/duplicate/package.json
//// {
//// "name": "duplicate",
//// "version": "1.0.0"
//// }

// @Filename: /node_modules/bar/node_modules/duplicate/index.d.ts
//// export declare const duplicate: number;

// This seems far-fetched but I don't know how else to test this

// @link: /node_modules/bar/node_modules/duplicate -> /node_modules/duplicate

// @Filename: /utils.ts
//// import {} from "duplicate";

// @Filename: /index.ts
//// import { foo } from "foo";
//// import { bar } from "bar";
//// duplicate/**/

goTo.file("/index.ts");
verify.completions({
marker: "",
includes: [{
name: "duplicate",
source: "duplicate",
sourceDisplay: "duplicate",
hasAction: true,
sortText: completion.SortText.AutoImportSuggestions
}],
preferences: {
includeCompletionsForModuleExports: true,
allowIncompleteCompletions: true
}
});

verify.importFixModuleSpecifiers("", ["duplicate"]);