-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathProjectIndexer.ts
More file actions
246 lines (236 loc) · 7.77 KB
/
Copy pathProjectIndexer.ts
File metadata and controls
246 lines (236 loc) · 7.77 KB
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
import * as path from 'path'
import ProgressBar from 'progress'
import * as ts from 'typescript'
import { GlobalCache, ProjectOptions } from './CommandLineOptions'
import { FileIndexer } from './FileIndexer'
import { Input } from './Input'
import { Packages } from './Packages'
import * as scip from './scip'
import { ScipSymbol } from './ScipSymbol'
function createCompilerHost(
cache: GlobalCache,
compilerOptions: ts.CompilerOptions,
projectOptions: ProjectOptions
): ts.CompilerHost {
const host = ts.createCompilerHost(compilerOptions)
if (!projectOptions.globalCaches) {
return host
}
const hostCopy = { ...host }
host.getParsedCommandLine = (fileName: string) => {
if (!hostCopy.getParsedCommandLine) {
return undefined
}
const fromCache = cache.parsedCommandLines.get(fileName)
if (fromCache !== undefined) {
return fromCache
}
const result = hostCopy.getParsedCommandLine(fileName)
if (result !== undefined) {
// Don't cache undefined results even if they could be cached
// theoretically. The big performance gains from this cache come from
// caching non-undefined results.
cache.parsedCommandLines.set(fileName, result)
}
return result
}
host.getSourceFile = (
fileName,
languageVersion,
onError,
shouldCreateNewSourceFile
) => {
const fromCache = cache.sources.get(fileName)
if (fromCache !== undefined) {
const [sourceFile, cachedLanguageVersion] = fromCache
if (isSameLanguageVersion(languageVersion, cachedLanguageVersion)) {
return sourceFile
}
}
const result = hostCopy.getSourceFile(
fileName,
languageVersion,
onError,
shouldCreateNewSourceFile
)
if (result !== undefined) {
// Don't cache undefined results even if they could be cached
// theoretically. The big performance gains from this cache come from
// caching non-undefined results.
cache.sources.set(fileName, [result, languageVersion])
}
return result
}
return host
}
export class ProjectIndexer {
private program: ts.Program
private checker: ts.TypeChecker
private symbolCache: Map<ts.Node, ScipSymbol> = new Map()
private hasConstructor: Map<ts.ClassDeclaration, boolean> = new Map()
private packages: Packages
private indexedFiles: Set<string>
constructor(
public readonly config: ts.ParsedCommandLine,
public readonly options: ProjectOptions,
cache: GlobalCache
) {
const host = createCompilerHost(cache, config.options, options)
this.program = ts.createProgram(config.fileNames, config.options, host)
this.checker = this.program.getTypeChecker()
this.packages = new Packages(options.projectRoot)
this.indexedFiles = cache.indexedFiles
}
public index(): void {
const startTimestamp = Date.now()
const sourceFiles = this.program.getSourceFiles()
const filesToIndex: ts.SourceFile[] = []
let projectFileCount = 0
// Visit every sourceFile in the program
for (const sourceFile of sourceFiles) {
const includes = this.config.fileNames.includes(sourceFile.fileName)
if (!includes) {
continue
}
projectFileCount++
if (this.indexedFiles.has(sourceFile.fileName)) {
continue
}
filesToIndex.push(sourceFile)
}
if (filesToIndex.length === 0) {
if (projectFileCount > 0) {
// Every source belongs to a project that was indexed earlier. SCIP
// requires document paths to be unique across a complete index.
return
}
throw new Error(
`no indexable files in project '${this.options.projectDisplayName}'`
)
}
const jobs: ProgressBar | undefined = this.options.progressBar
? new ProgressBar(
` ${this.options.projectDisplayName} [:bar] :current/:total :title`,
{
total: filesToIndex.length,
renderThrottle: 100,
incomplete: '_',
complete: '#',
width: 20,
clear: true,
stream: process.stderr,
}
)
: undefined
let lastWrite = startTimestamp
for (const [index, sourceFile] of filesToIndex.entries()) {
const title = path.relative(this.options.cwd, sourceFile.fileName)
jobs?.tick({ title })
if (!this.options.progressBar) {
const now = Date.now()
const elapsed = now - lastWrite
if (elapsed > 1000 && index > 2) {
lastWrite = now
process.stdout.write('.')
}
}
const document = new scip.scip.Document({
language: languageForFileName(sourceFile.fileName),
relative_path: path.relative(this.options.cwd, sourceFile.fileName),
occurrences: [],
})
const input = new Input(sourceFile.fileName, sourceFile.getText())
const visitor = new FileIndexer(
this.checker,
this.options,
input,
document,
this.symbolCache,
this.hasConstructor,
this.packages,
sourceFile
)
try {
visitor.index()
} catch (error) {
console.error(
`unexpected error indexing project root '${this.options.cwd}'`,
error
)
}
if (visitor.document.occurrences.length > 0) {
this.options.writeIndex(
new scip.scip.Index({
documents: [visitor.document],
})
)
// Only suppress the file in later overlapping projects after its
// document has actually been emitted. If indexing or emission fails,
// another project that includes the file can still retry it.
this.indexedFiles.add(sourceFile.fileName)
}
}
jobs?.terminate()
const elapsed = Date.now() - startTimestamp
if (!this.options.progressBar && lastWrite > startTimestamp) {
process.stdout.write('\n')
}
console.log(
`+ ${this.options.projectDisplayName} (${prettyMilliseconds(elapsed)})`
)
}
}
export function languageForFileName(fileName: string): string {
// Document.language uses the exact names from SCIP's Language enum, not the
// lowercase language identifiers used by editors.
const extension = path.extname(fileName).toLowerCase()
if (extension === '.tsx') return 'TypeScriptReact'
if (extension === '.ts' || extension === '.mts' || extension === '.cts') {
return 'TypeScript'
}
if (extension === '.jsx') return 'JavaScriptReact'
if (extension === '.js' || extension === '.mjs' || extension === '.cjs') {
return 'JavaScript'
}
if (extension === '.json') return 'JSON'
return ''
}
export function prettyMilliseconds(milliseconds: number): string {
let ms = Math.floor(milliseconds)
let result = ''
if (ms >= 1000 * 60) {
const minutes = Math.floor(ms / (1000 * 60))
if (minutes !== 0) {
result += `${minutes}m `
ms -= minutes * 1000 * 60
}
}
if (result !== '' || ms >= 1000) {
const seconds = Math.floor(ms / 1000)
result += `${seconds}s `
ms -= seconds * 1000
}
result += `${ms}ms`
return result.trim()
}
function isSameLanguageVersion(
a: ts.ScriptTarget | ts.CreateSourceFileOptions,
b: ts.ScriptTarget | ts.CreateSourceFileOptions
): boolean {
if (typeof a === 'number' && typeof b === 'number') {
return a === b
}
if (typeof a === 'number' || typeof b === 'number') {
// Different shape: one is ts.ScriptTarget, the other is
// ts.CreateSourceFileOptions
return false
}
return (
a.languageVersion === b.languageVersion &&
a.impliedNodeFormat === b.impliedNodeFormat
// Ignore setExternalModuleIndicator even if that increases the risk of a
// false positive. A local experiment revealed that we never get a cache hit
// if we compare setExternalModuleIndicator since it's function with a
// unique reference on every `CompilerHost.getSourceFile` callback.
)
}