8000 [WIP] Caching resolutions in buildInfo and reusing them by sheetalkamat · Pull Request #50007 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content

[WIP] Caching resolutions in buildInfo and reusing them #50007

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
wants to merge 31 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
3172629
Add new option to cacheResolution (No actual functionality yet)
sheetalkamat Jun 30, 2022
e1600ab
Add baselining of modules and type refs
sheetalkamat Dec 9, 2022
666eece
Add tests
sheetalkamat Jul 1, 2022
1eeea26
Store resolved module and type reference resolution cache in buildinfo
sheetalkamat Jul 7, 2022
76100d7
Read reusable module cache information from the buildinfo
sheetalkamat Jul 8, 2022
4bc74b9
Add reusing cache stub
sheetalkamat Jul 8, 2022
23cfc79
Buildinfo resolutions actually reused
sheetalkamat Jul 18, 2022
0132dc0
Handle project reference redirects for the module and type reference …
sheetalkamat Jul 22, 2022
d55ab98
Test for module resolutions from different directories
sheetalkamat Jul 22, 2022
ce07d0e
Handle resolutions that would be same in ancestor directory and can b…
sheetalkamat Jul 23, 2022
959206d
Do not store failed lookups with cacheResolution option if it is reso…
sheetalkamat Jul 25, 2022
0446430
Add tests where module resolution caches should reuse the resolutions…
8000 sheetalkamat Jul 25, 2022
207226a
Reusing resolutions in tsserver scenario
sheetalkamat Jul 25, 2022
591960e
Set old program build info as a location to look for from module reso…
sheetalkamat Jul 25, 2022
71ebed9
Modify resolution cache to update on program creation completion
sheetalkamat Nov 29, 2022
4d127fa
Remove files that are not in program from cache of unresolved imports
sheetalkamat Jul 27, 2022
feb3220
Tests for unresolved imports from multiple places
sheetalkamat Jul 27, 2022
84cda33
More tests for cache reuse directory structure
sheetalkamat Jul 27, 2022
2219b5d
Start using cache as perDirectory lookup
sheetalkamat Nov 16, 2022
6261b6c
Add tests where cache resoluition is incorrectly used because of not …
sheetalkamat Jul 27, 2022
e1ed9ea
Store package json hash in buildinfo
sheetalkamat Nov 29, 2022
7de4780
Use the hashes to verify the affecting location before using the reso…
sheetalkamat Jul 28, 2022
5c11252
Add tests for package json edits
sheetalkamat Aug 2, 2022
e21738c
Store package.json for the directories in buildinfo
sheetalkamat Aug 2, 2022
be5ecb2
During cacheResolutions dont watch failed lookups and dont look at th…
sheetalkamat Aug 3, 2022
78e215f
Dont store package json path if its found in same directory
sheetalkamat Aug 4, 2022
1e123ec
Cache packagejson scopes per directory
sheetalkamat Dec 9, 2022
81a1af9
Dont store isExternalLibraryImport in the buildInfo
sheetalkamat Dec 9, 2022
3115572
Store resolvedFileName as fileId instead of structure if thats the on…
sheetalkamat Dec 10, 2022
2bb56da
Always respect preserveSymlinks
sheetalkamat Dec 10, 2022
b179c7c
Dont store originalPath as separate, instead store originalPath || re…
sheetalkamat Dec 10, 2022
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
Prev Previous commit
Next Next commit
Use the hashes to verify the affecting location before using the reso…
…lution
  • Loading branch information
sheetalkamat committed Dec 9, 2022
commit 7de47805fe56a512a9594d0e5d6f6fe71940446e
54 changes: 48 additions & 6 deletions src/compiler/builder.ts
629A
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
emitSkippedWithNoDiagnostics,
emptyArray,
ensurePathIsNonModuleName,
every,
Extension,
extensionFromPath,
filterSemanticDiagnostics,
Expand Down Expand Up @@ -75,6 +76,7 @@ import {
OldBuildInfoProgramHost,
outFile,
PackageJsonInfo,
PackageJsonInfoCache,
Path,
PerDirectoryAndNonRelativeNameCache,
Program,
Expand Down Expand Up @@ -180,7 +182,7 @@ export interface ReusableBuilderProgramState extends BuilderState {
cacheResolutions?: {
modules: PerDirectoryAndNonRelativeNameCache<ResolvedModuleWithFailedLookupLocations> | undefined;
typeRefs: PerDirectoryAndNonRelativeNameCache<ResolvedTypeReferenceDirectiveWithFailedLookupLocations> | undefined;
packageJsonCache: Map<Path, PackageJsonInfo | boolean> | undefined;
packageJsonCache: PackageJsonInfoCache | undefined;
};
resuableCacheResolutions?: {
cache: ProgramBuildInfoCacheResolutions;
Expand Down Expand Up @@ -1457,11 +1459,10 @@ function getCacheResolutions(state: BuilderProgramState) {
const containingPath = toPath(state.program!.getAutomaticTypeDirectiveContainingFile(), state.program!.getCurrentDirectory(), state.program!.getCanonicalFileName);
typeRefs = toPerDirectoryAndNonRelativeNameCache(state, typeRefs, getOriginalOrResolvedTypeReferenceFileName, state.program!.getAutomaticTypeDirectiveResolutions(), containingPath);
}
const packageJsonMap = state.program!.getModuleResolutionCache()?.getPackageJsonInfoCache().getInternalMap();
return state.cacheResolutions = {
modules,
typeRefs,
packageJsonCache: packageJsonMap && new Map(packageJsonMap),
packageJsonCache: state.program!.getModuleResolutionCache()?.getPackageJsonInfoCache().clone(),
};
}

Expand Down Expand Up @@ -2119,6 +2120,7 @@ export function createOldBuildInfoProgram(
): OldBuildInfoProgram | undefined {
if (!cacheResolutions && !resuableCacheResolutions) return undefined;
const fileExistsMap = new Map<string, boolean>();
const affectingLoationsSameMap = new Map<string, boolean>();

type Resolution = ResolvedModuleWithFailedLookupLocations & ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
type ResolutionEntry = [name: string, resolutionId: ProgramBuildInfoResolutionId, mode: ResolutionMode];
Expand All @@ -2128,6 +2130,7 @@ export function createOldBuildInfoProgram(
}
const reusableResolvedModules = intializeReusableResolutionsCache(resuableCacheResolutions?.cache.modules);
const reusableResolvedTypeRefs = intializeReusableResolutionsCache(resuableCacheResolutions?.cache.typeRefs);
let decodedHashes: Map<ProgramBuildInfoAbsoluteFileId, string | undefined> | undefined;
let resolutions: (Resolution | false)[] | undefined;
let originalPathOrResolvedFileNames: string[] | undefined;
let resolutionEntries: ResolutionEntry[] | undefined;
Expand Down Expand Up @@ -2165,6 +2168,25 @@ export function createOldBuildInfoProgram(
return result;
}

function affectingLocationsSame(
fileName: string,
expected: PackageJsonInfo | boolean | string | undefined
): boolean {
let result = affectingLoationsSameMap.get(fileName);
if (result !== undefined) return result;
const packageJsonInfo = host.getPackageJsonInfo(fileName);
const currentText = typeof packageJsonInfo === "object" ? packageJsonInfo.contents.packageJsonText : undefined;
if (isString(expected)) {
result = !!currentText && (host.createHash ?? generateDjb2Hash)(currentText) === expected;
}
else {
const expectedText = typeof expected === "object" ? expected.contents.packageJsonText : undefined;
result = currentText === expectedText;
}
affectingLoationsSameMap.set(fileName, result);
return result;
}

function getResolvedFromCache<T extends ResolvedModuleWithFailedLookupLocations | ResolvedTypeReferenceDirectiveWithFailedLookupLocations>(
cache: PerDirectoryAndNonRelativeNameCache<T> | undefined,
getResolvedFileName: (resolution: T) => string | undefined,
Expand All @@ -2182,7 +2204,13 @@ export function createOldBuildInfoProgram(
if (fromCache) {
// TODO:: symlinks
const resolvedFileName = getResolvedFileName(fromCache);
return resolvedFileName && fileExists(resolvedFileName) ? fromCache : undefined;
return resolvedFileName && fileExists(resolvedFileName) && every(
fromCache.affectingLocations,
fileName => affectingLocationsSame(
fileName,
cacheResolutions!.packageJsonCache?.getPackageJsonInfo(fileName)
)
) ? fromCache : undefined;
}
if (!reusableResolutionsCache) return undefined;
if (!reusableResolutionsCache.decoded) {
Expand Down Expand Up @@ -2269,6 +2297,15 @@ export function createOldBuildInfoProgram(
));
}

function toAffectingFileLocation(fileId: ProgramBuildInfoAbsoluteFileId) {
if (!decodedHashes && resuableCacheResolutions!.cache.hash) {
decodedHashes = arrayToMap(resuableCacheResolutions!.cache.hash, hash => isArray(hash) ? hash[0] : hash, hash => isArray(hash) ? hash[1] : undefined);
}
const hash = decodedHashes?.get(fileId);
const file = resuableCacheResolutions!.getProgramBuildInfoFilePathDecoder().toFileAbsolutePath(fileId);
return affectingLocationsSame(file, hash) ? file : undefined;
}

function toResolution(resolutionId: ProgramBuildInfoResolutionId): Resolution | undefined {
const existing = resolutions?.[resolutionId - 1];
if (existing !== undefined) return existing || undefined;
Expand All @@ -2277,13 +2314,18 @@ export function createOldBuildInfoProgram(
const resolvedFileName = resuableCacheResolutions!.getProgramBuildInfoFilePathDecoder().toFileAbsolutePath(
resolution.resolvedModule?.resolvedFileName || resolution.resolvedTypeReferenceDirective!.resolvedFileName
);
if (fileExists(resolvedFileName)) {
let affectingLocations: string[] | undefined;
if (fileExists(resolvedFileName) && every(resolution.affectingLocations, fileId => {
const file = toAffectingFileLocation(fileId);
if (file) (affectingLocations ??= []).push(file);
return !!file;
})) {
// Type Ref doesnt need extension
const extenstion = resolution.resolvedModule ? extensionFromPath(resolvedFileName) : undefined!;
return resolutions[resolutionId - 1] = {
resolvedModule: toResolved(resolution.resolvedModule, resolvedFileName, extenstion),
resolvedTypeReferenceDirective: toResolved(resolution.resolvedTypeReferenceDirective, resolvedFileName, extenstion),
affectingLocations: resolution.affectingLocations?.map(resuableCacheResolutions!.getProgramBuildInfoFilePathDecoder().toFileAbsolutePath),
affectingLocations,
resolutionDiagnostics: resolution.resolutionDiagnostics?.length ? convertToDiagnostics(resolution.resolutionDiagnostics, /*newProgram*/ undefined!) as Diagnostic[] : undefined
};
}
Expand Down
9 changes: 6 additions & 3 deletions src/compiler/moduleNameResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,7 @@ export interface PackageJsonInfoCache {
/** @internal */ setPackageJsonInfo(packageJsonPath: string, info: PackageJsonInfo | boolean): void;
/** @internal */ entries(): [Path, PackageJsonInfo | boolean][];
/** @internal */ getInternalMap(): Map<Path, PackageJsonInfo | boolean> | undefined;
/** @internal */ clone(): PackageJsonInfoCache;
clear(): void;
}

Expand Down Expand Up @@ -884,9 +885,8 @@ function createCacheWithRedirects<K, V>(ownOptions: CompilerOptions | undefined)
}
}

function createPackageJsonInfoCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): PackageJsonInfoCache {
let cache: Map<Path, PackageJsonInfo | boolean> | undefined;
return { getPackageJsonInfo, setPackageJsonInfo, clear, entries, getInternalMap };
function createPackageJsonInfoCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, cache?: Map<Path, PackageJsonInfo | boolean>): PackageJsonInfoCache {
return { getPackageJsonInfo, setPackageJsonInfo, clear, entries, getInternalMap, clone };
function getPackageJsonInfo(packageJsonPath: string) {
return cache?.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName));
}
Expand All @@ -903,6 +903,9 @@ function createPackageJsonInfoCache(currentDirectory: string, getCanonicalFileNa
function getInternalMap() {
return cache;
}
function clone() {
return createPackageJsonInfoCache(currentDirectory, getCanonicalFileName, cache && new Map(cache));
}
}

function getOrCreateCache<K, V>(cacheWithRedirects: CacheWithRedirects<K, V>, redirectedReference: ResolvedProjectReference | undefined, key: K, create: () => V): V {
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ import {
getNormalizedPathComponents,
getOutputDeclarationFileName,
getOutputPathsForBundle,
getPackageJsonInfo,
getPackageScopeForPath,
getPathFromPathComponents,
getPositionOfLineAndCharacter,
Expand Down Expand Up @@ -1580,9 +1581,12 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
let o F438 ldProgram = typeof oldProgramOrOldBuildInfoProgramConstructor === "object" ? oldProgramOrOldBuildInfoProgramConstructor : undefined;
let oldBuildInfoProgram: OldBuildInfoProgram | undefined;
if (!oldProgram && typeof oldProgramOrOldBuildInfoProgramConstructor === "function") {
const state = getTemporaryModuleResolutionState(moduleResolutionCache?.getPackageJsonInfoCache(), host, options);
oldBuildInfoProgram = oldProgramOrOldBuildInfoProgramConstructor({
fileExists: fileName => host.fileExists(fileName),
getCompilerOptions: () => options,
createHash: maybeBind(host, host.createHash),
getPackageJsonInfo: fileName => getPackageJsonInfo(getDirectoryPath(fileName), /*onlyRecordFailures*/ false, state),
});
if (oldBuildInfoProgram) {
moduleResolutionCache?.setOldResolutionCache({
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6985,6 +6985,8 @@ export interface OldBuildInfoProgram {
export interface OldBuildInfoProgramHost {
fileExists(fileName: string): boolean;
getCompilerOptions(): CompilerOptions;
createHash?(data: string): string;
getPackageJsonInfo(fileName: string): PackageJsonInfo | undefined;
}

/** @internal */
Expand Down
6 changes: 2 additions & 4 deletions src/testRunner/unittests/tsbuild/cacheResolutions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ describe("unittests:: tsbuild:: cacheResolutions::", () => {
appendText(fs, "/src/project/randomFileForImport.ts", `export const y = 10;`);
},
discrepancyExplanation: () => [
`Affected locations are not checked which results in using incorrect resolution`
`Clean build doesnt emit files so it doesnt have emit signatures and latestChangedDtsFile`,
`Incremental build has this information from previous pass`,
]
},
{
Expand All @@ -56,9 +57,6 @@ describe("unittests:: tsbuild:: cacheResolutions::", () => {
fs.writeFileSync("/src/project/node_modules/pkg1/require1.d.ts", getPkgImportContent("Require", 1));
appendText(fs, "/src/project/randomFileForImport.ts", `export const z = 10;`);
},
discrepancyExplanation: () => [
`Affected locations are not checked which results in using incorrect resolution`
]
},
]
});
Expand Down
6 changes: 0 additions & 6 deletions src/testRunner/unittests/tsc/cacheResolutions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,10 @@ describe("unittests:: tsc:: cacheResolutions::", () => {
{
caption: "modify package.json and that should re-resolve",
edit: fs => replaceText(fs, "/src/project/node_modules/pkg1/package.json", "./require.js", "./require1.js"),
discrepancyExplanation: () => [
`Affected locations are not checked which results in using incorrect resolution`
]
},
{
caption: "write file not resolved by import",
edit: fs => fs.writeFileSync("/src/project/node_modules/pkg1/require1.d.ts", getPkgImportContent("Require", 1)),
discrepancyExplanation: () => [
`Affected locations are not checked which results in using incorrect resolution`
]
},
{
caption: "delete file with imports",
Expand Down
Loading
0