Skip to content
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

fix(rosetta): cache source file parses #3163

Merged
merged 4 commits into from
Nov 12, 2021
Merged
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
23 changes: 19 additions & 4 deletions packages/jsii-rosetta/lib/typescript/ts-compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import * as ts from 'typescript';
export class TypeScriptCompiler {
private readonly realHost = ts.createCompilerHost(STANDARD_COMPILER_OPTIONS, true);

/**
* A compiler-scoped cache to avoid having to re-parse the same library files for every compilation
*/
private readonly fileCache = new Map<string, ts.SourceFile | undefined>();

public createInMemoryCompilerHost(
sourcePath: string,
sourceContents: string,
Expand All @@ -15,10 +20,20 @@ export class TypeScriptCompiler {
...realHost,
fileExists: (filePath) => filePath === sourcePath || realHost.fileExists(filePath),
getCurrentDirectory: currentDirectory != null ? () => currentDirectory : realHost.getCurrentDirectory,
getSourceFile: (fileName, languageVersion, onError, shouldCreateNewSourceFile) =>
fileName === sourcePath
? sourceFile
: realHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile),
getSourceFile: (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {
if (fileName === sourcePath) {
return sourceFile;
}

const existing = this.fileCache.get(fileName);
if (existing) {
return existing;
}

const parsed = realHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
this.fileCache.set(fileName, parsed);
return parsed;
},
readFile: (filePath) => (filePath === sourcePath ? sourceContents : realHost.readFile(filePath)),
writeFile: () => void undefined,
};
Expand Down