/
documentRegistry.ts
412 lines (379 loc) · 21 KB
/
documentRegistry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import {
arrayFrom,
CompilerOptions,
createGetCanonicalFileName,
createLanguageServiceSourceFile,
CreateSourceFileOptions,
Debug,
ensureScriptKind,
firstDefinedIterator,
forEachEntry,
getEmitScriptTarget,
getImpliedNodeFormatForFile,
getKeyForCompilerOptions,
getOrUpdate,
getSetExternalModuleIndicator,
getSnapshotText,
identity,
IScriptSnapshot,
isDeclarationFileName,
JSDocParsingMode,
MinimalResolutionCacheHost,
Path,
ResolutionMode,
ScriptKind,
ScriptTarget,
SourceFile,
sourceFileAffectingCompilerOptions,
toPath,
tracing,
updateLanguageServiceSourceFile,
} from "./_namespaces/ts";
/**
* The document registry represents a store of SourceFile objects that can be shared between
* multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST)
* of files in the context.
* SourceFile objects account for most of the memory usage by the language service. Sharing
* the same DocumentRegistry instance between different instances of LanguageService allow
* for more efficient memory utilization since all projects will share at least the library
* file (lib.d.ts).
*
* A more advanced use of the document registry is to serialize sourceFile objects to disk
* and re-hydrate them when needed.
*
* To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it
* to all subsequent createLanguageService calls.
*/
export interface DocumentRegistry {
/**
* Request a stored SourceFile with a given fileName and compilationSettings.
* The first call to acquire will call createLanguageServiceSourceFile to generate
* the SourceFile if was not found in the registry.
*
* @param fileName The name of the file requested
* @param compilationSettingsOrHost Some compilation settings like target affects the
* shape of a the resulting SourceFile. This allows the DocumentRegistry to store
* multiple copies of the same file for different compilation settings. A minimal
* resolution cache is needed to fully define a source file's shape when
* the compilation settings include `module: node16`+, so providing a cache host
* object should be preferred. A common host is a language service `ConfiguredProject`.
* @param scriptSnapshot Text of the file. Only used if the file was not found
* in the registry and a new one was created.
* @param version Current version of the file. Only used if the file was not found
* in the registry and a new one was created.
*/
acquireDocument(
fileName: string,
compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost,
scriptSnapshot: IScriptSnapshot,
version: string,
scriptKind?: ScriptKind,
sourceFileOptions?: CreateSourceFileOptions | ScriptTarget,
): SourceFile;
acquireDocumentWithKey(
fileName: string,
path: Path,
compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost,
key: DocumentRegistryBucketKey,
scriptSnapshot: IScriptSnapshot,
version: string,
scriptKind?: ScriptKind,
sourceFileOptions?: CreateSourceFileOptions | ScriptTarget,
): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
* to get an updated SourceFile.
*
* @param fileName The name of the file requested
* @param compilationSettingsOrHost Some compilation settings like target affects the
* shape of a the resulting SourceFile. This allows the DocumentRegistry to store
* multiple copies of the same file for different compilation settings. A minimal
* resolution cache is needed to fully define a source file's shape when
* the compilation settings include `module: node16`+, so providing a cache host
* object should be preferred. A common host is a language service `ConfiguredProject`.
* @param scriptSnapshot Text of the file.
* @param version Current version of the file.
*/
updateDocument(
fileName: string,
compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost,
scriptSnapshot: IScriptSnapshot,
version: string,
scriptKind?: ScriptKind,
sourceFileOptions?: CreateSourceFileOptions | ScriptTarget,
): SourceFile;
updateDocumentWithKey(
fileName: string,
path: Path,
compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost,
key: DocumentRegistryBucketKey,
scriptSnapshot: IScriptSnapshot,
version: string,
scriptKind?: ScriptKind,
sourceFileOptions?: CreateSourceFileOptions | ScriptTarget,
): SourceFile;
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
/** @internal */
getDocumentRegistryBucketKeyWithMode(key: DocumentRegistryBucketKey, mode: ResolutionMode): DocumentRegistryBucketKeyWithMode;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
* Note: It is not allowed to call release on a SourceFile that was not acquired from
* this registry originally.
*
* @param fileName The name of the file to be released
* @param compilationSettings The compilation settings used to acquire the file
* @param scriptKind The script kind of the file to be released
*
* @deprecated pass scriptKind and impliedNodeFormat for correctness
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind?: ScriptKind): void;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
* Note: It is not allowed to call release on a SourceFile that was not acquired from
* this registry originally.
*
* @param fileName The name of the file to be released
* @param compilationSettings The compilation settings used to acquire the file
* @param scriptKind The script kind of the file to be released
* @param impliedNodeFormat The implied source file format of the file to be released
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind, impliedNodeFormat: ResolutionMode): void; // eslint-disable-line @typescript-eslint/unified-signatures
/**
* @deprecated pass scriptKind for and impliedNodeFormat correctness */
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind?: ScriptKind): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind, impliedNodeFormat: ResolutionMode): void; // eslint-disable-line @typescript-eslint/unified-signatures
reportStats(): string;
/** @internal */ getBuckets(): Map<DocumentRegistryBucketKeyWithMode, Map<Path, BucketEntry>>;
}
/** @internal */
export interface ExternalDocumentCache {
setDocument(key: DocumentRegistryBucketKeyWithMode, path: Path, sourceFile: SourceFile): void;
getDocument(key: DocumentRegistryBucketKeyWithMode, path: Path): SourceFile | undefined;
}
export type DocumentRegistryBucketKey = string & { __bucketKey: any; };
/** @internal */
export interface DocumentRegistryEntry {
sourceFile: SourceFile;
// The number of language services that this source file is referenced in. When no more
// language services are referencing the file, then the file can be removed from the
// registry.
languageServiceRefCount: number;
}
/** @internal */
export type BucketEntry = DocumentRegistryEntry | Map<ScriptKind, DocumentRegistryEntry>;
/** @internal */
export function isDocumentRegistryEntry(entry: BucketEntry): entry is DocumentRegistryEntry {
return !!(entry as DocumentRegistryEntry).sourceFile;
}
export function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string, jsDocParsingMode?: JSDocParsingMode): DocumentRegistry {
return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, jsDocParsingMode);
}
/** @internal */
export type DocumentRegistryBucketKeyWithMode = string & { __documentRegistryBucketKeyWithMode: any; };
/** @internal */
export function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boolean, currentDirectory = "", jsDocParsingMode?: JSDocParsingMode, externalCache?: ExternalDocumentCache): DocumentRegistry {
// Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
// for those settings.
const buckets = new Map<DocumentRegistryBucketKeyWithMode, Map<Path, BucketEntry>>();
const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames);
function reportStats() {
const bucketInfoArray = arrayFrom(buckets.keys()).filter(name => name && name.charAt(0) === "_").map(name => {
const entries = buckets.get(name)!;
const sourceFiles: { name: string; scriptKind: ScriptKind; refCount: number; }[] = [];
entries.forEach((entry, name) => {
if (isDocumentRegistryEntry(entry)) {
sourceFiles.push({
name,
scriptKind: entry.sourceFile.scriptKind,
refCount: entry.languageServiceRefCount,
});
}
else {
entry.forEach((value, scriptKind) => sourceFiles.push({ name, scriptKind, refCount: value.languageServiceRefCount }));
}
});
sourceFiles.sort((x, y) => y.refCount - x.refCount);
return {
bucket: name,
sourceFiles,
};
});
return JSON.stringify(bucketInfoArray, undefined, 2);
}
function getCompilationSettings(settingsOrHost: CompilerOptions | MinimalResolutionCacheHost) {
if (typeof settingsOrHost.getCompilationSettings === "function") {
return (settingsOrHost as MinimalResolutionCacheHost).getCompilationSettings();
}
return settingsOrHost as CompilerOptions;
}
function acquireDocument(fileName: string, compilationSettings: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, languageVersionOrOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile {
const path = toPath(fileName, currentDirectory, getCanonicalFileName);
const key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings));
return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions);
}
function acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, languageVersionOrOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile {
return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind, languageVersionOrOptions);
}
function updateDocument(fileName: string, compilationSettings: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, languageVersionOrOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile {
const path = toPath(fileName, currentDirectory, getCanonicalFileName);
const key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings));
return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions);
}
function updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, languageVersionOrOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile {
return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind, languageVersionOrOptions);
}
function getDocumentRegistryEntry(bucketEntry: BucketEntry, scriptKind: ScriptKind | undefined) {
const entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided"));
Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, `Script kind should match provided ScriptKind:${scriptKind} and sourceFile.scriptKind: ${entry?.sourceFile.scriptKind}, !entry: ${!entry}`);
return entry;
}
function acquireOrUpdateDocument(
fileName: string,
path: Path,
compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost,
key: DocumentRegistryBucketKey,
scriptSnapshot: IScriptSnapshot,
version: string,
acquiring: boolean,
scriptKind: ScriptKind | undefined,
languageVersionOrOptions: CreateSourceFileOptions | ScriptTarget | undefined,
): SourceFile {
scriptKind = ensureScriptKind(fileName, scriptKind);
const compilationSettings = getCompilationSettings(compilationSettingsOrHost);
const host: MinimalResolutionCacheHost | undefined = compilationSettingsOrHost === compilationSettings ? undefined : compilationSettingsOrHost as MinimalResolutionCacheHost;
const scriptTarget = scriptKind === ScriptKind.JSON ? ScriptTarget.JSON : getEmitScriptTarget(compilationSettings);
const sourceFileOptions: CreateSourceFileOptions = typeof languageVersionOrOptions === "object" ?
languageVersionOrOptions :
{
languageVersion: scriptTarget,
impliedNodeFormat: host && getImpliedNodeFormatForFile(path, host.getCompilerHost?.()?.getModuleResolutionCache?.()?.getPackageJsonInfoCache(), host, compilationSettings),
setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings),
jsDocParsingMode,
};
sourceFileOptions.languageVersion = scriptTarget;
Debug.assertEqual(jsDocParsingMode, sourceFileOptions.jsDocParsingMode);
const oldBucketCount = buckets.size;
const keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat);
const bucket = getOrUpdate(buckets, keyWithMode, () => new Map());
if (tracing) {
if (buckets.size > oldBucketCount) {
// It is interesting, but not definitively problematic if a build requires multiple document registry buckets -
// perhaps they are for two projects that don't have any overlap.
// Bonus: these events can help us interpret the more interesting event below.
tracing.instant(tracing.Phase.Session, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode });
}
// It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations.
// If this occurs unexpectedly, the fix is likely to synchronize the project settings.
// Skip .d.ts files to reduce noise (should also cover most of node_modules).
const otherBucketKey = !isDeclarationFileName(path) &&
forEachEntry(buckets, (bucket, bucketKey) => bucketKey !== keyWithMode && bucket.has(path) && bucketKey);
if (otherBucketKey) {
tracing.instant(tracing.Phase.Session, "documentRegistryBucketOverlap", { path, key1: otherBucketKey, key2: keyWithMode });
}
}
const bucketEntry = bucket.get(path);
let entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind);
if (!entry && externalCache) {
const sourceFile = externalCache.getDocument(keyWithMode, path);
if (sourceFile && sourceFile.scriptKind === scriptKind && sourceFile.text === getSnapshotText(scriptSnapshot)) {
Debug.assert(acquiring);
entry = {
sourceFile,
languageServiceRefCount: 0,
};
setBucketEntry();
}
}
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
const sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, sourceFileOptions, version, /*setNodeParents*/ false, scriptKind);
if (externalCache) {
externalCache.setDocument(keyWithMode, path, sourceFile);
}
entry = {
sourceFile,
languageServiceRefCount: 1,
};
setBucketEntry();
}
else {
// We have an entry for this file. However, it may be for a different version of
// the script snapshot. If so, update it appropriately. Otherwise, we can just
// return it as is.
if (entry.sourceFile.version !== version) {
entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot));
if (externalCache) {
externalCache.setDocument(keyWithMode, path, entry.sourceFile);
}
}
// If we're acquiring, then this is the first time this LS is asking for this document.
// Increase our ref count so we know there's another LS using the document. If we're
// not acquiring, then that means the LS is 'updating' the file instead, and that means
// it has already acquired the document previously. As such, we do not need to increase
// the ref count.
if (acquiring) {
entry.languageServiceRefCount++;
}
}
Debug.assert(entry.languageServiceRefCount !== 0);
return entry.sourceFile;
function setBucketEntry() {
if (!bucketEntry) {
bucket.set(path, entry);
}
else if (isDocumentRegistryEntry(bucketEntry)) {
const scriptKindMap = new Map<ScriptKind, DocumentRegistryEntry>();
scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry);
scriptKindMap.set(scriptKind!, entry);
bucket.set(path, scriptKindMap);
}
else {
bucketEntry.set(scriptKind!, entry);
}
}
}
function releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind?: ScriptKind, impliedNodeFormat?: ResolutionMode): void {
const path = toPath(fileName, currentDirectory, getCanonicalFileName);
const key = getKeyForCompilationSettings(compilationSettings);
return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat);
}
function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind?: ScriptKind, impliedNodeFormat?: ResolutionMode): void {
const bucket = Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat)));
const bucketEntry = bucket.get(path)!;
const entry = getDocumentRegistryEntry(bucketEntry, scriptKind)!;
entry.languageServiceRefCount--;
Debug.assert(entry.languageServiceRefCount >= 0);
if (entry.languageServiceRefCount === 0) {
if (isDocumentRegistryEntry(bucketEntry)) {
bucket.delete(path);
}
else {
bucketEntry.delete(scriptKind!);
if (bucketEntry.size === 1) {
bucket.set(path, firstDefinedIterator(bucketEntry.values(), identity)!);
}
}
}
}
return {
acquireDocument,
acquireDocumentWithKey,
updateDocument,
updateDocumentWithKey,
releaseDocument,
releaseDocumentWithKey,
getKeyForCompilationSettings,
getDocumentRegistryBucketKeyWithMode,
reportStats,
getBuckets: () => buckets,
};
}
function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey {
return getKeyForCompilerOptions(settings, sourceFileAffectingCompilerOptions) as DocumentRegistryBucketKey;
}
function getDocumentRegistryBucketKeyWithMode(key: DocumentRegistryBucketKey, mode: ResolutionMode) {
return (mode ? `${key}|${mode}` : key) as DocumentRegistryBucketKeyWithMode;
}