-
Notifications
You must be signed in to change notification settings - Fork 941
Expand file tree
/
Copy pathfilesparser.go
More file actions
500 lines (445 loc) · 17.4 KB
/
filesparser.go
File metadata and controls
500 lines (445 loc) · 17.4 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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package compiler
import (
"math"
"slices"
"sync"
"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/collections"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/diagnostics"
"github.com/microsoft/typescript-go/internal/module"
"github.com/microsoft/typescript-go/internal/tsoptions"
"github.com/microsoft/typescript-go/internal/tspath"
)
type parseTask struct {
normalizedFilePath string
path tspath.Path
file *ast.SourceFile
libFile *LibFile
redirectedParseTask *parseTask
subTasks []*parseTask
loaded bool
startedSubTasks bool
isForAutomaticTypeDirective bool
includeReason *FileIncludeReason
metadata ast.SourceFileMetaData
resolutionsInFile module.ModeAwareCache[*module.ResolvedModule]
resolutionsTrace []module.DiagAndArgs
typeResolutionsInFile module.ModeAwareCache[*module.ResolvedTypeReferenceDirective]
typeResolutionsTrace []module.DiagAndArgs
resolutionDiagnostics []*ast.Diagnostic
processingDiagnostics []*processingDiagnostic
importHelpersImportSpecifier *ast.Node
jsxRuntimeImportSpecifier *jsxRuntimeImportSpecifier
increaseDepth bool
elideOnDepth bool
loadedTask *parseTask
allIncludeReasons []*FileIncludeReason
}
func (t *parseTask) FileName() string {
return t.normalizedFilePath
}
func (t *parseTask) Path() tspath.Path {
return t.path
}
func (t *parseTask) load(loader *fileLoader) {
t.loaded = true
if t.isForAutomaticTypeDirective {
t.loadAutomaticTypeDirectives(loader)
return
}
redirect := loader.projectReferenceFileMapper.getParseFileRedirect(t)
if redirect != "" {
t.redirect(loader, redirect)
return
}
if tspath.HasExtension(t.normalizedFilePath) {
compilerOptions := loader.opts.Config.CompilerOptions()
allowNonTsExtensions := compilerOptions.AllowNonTsExtensions.IsTrue()
if !allowNonTsExtensions {
canonicalFileName := tspath.GetCanonicalFileName(t.normalizedFilePath, loader.opts.Host.FS().UseCaseSensitiveFileNames())
supported := false
for _, ext := range loader.supportedExtensions {
if tspath.FileExtensionIs(canonicalFileName, ext) {
supported = true
break
}
}
if !supported {
if tspath.HasJSFileExtension(canonicalFileName) {
t.processingDiagnostics = append(t.processingDiagnostics, &processingDiagnostic{
kind: processingDiagnosticKindExplainingFileInclude,
data: &includeExplainingDiagnostic{
diagnosticReason: t.includeReason,
message: diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option,
args: []any{t.normalizedFilePath},
},
})
}
return
}
}
}
loader.totalFileCount.Add(1)
if t.libFile != nil {
loader.libFileCount.Add(1)
}
t.metadata = loader.loadSourceFileMetaData(t.normalizedFilePath)
file := loader.parseSourceFile(t)
if file == nil {
return
}
t.file = file
t.subTasks = make([]*parseTask, 0, len(file.ReferencedFiles)+len(file.Imports())+len(file.ModuleAugmentations))
for index, ref := range file.ReferencedFiles {
resolvedPath := loader.resolveTripleslashPathReference(ref.FileName, file.FileName(), index)
t.addSubTask(resolvedPath, nil)
}
compilerOptions := loader.opts.Config.CompilerOptions()
loader.resolveTypeReferenceDirectives(t)
if compilerOptions.NoLib != core.TSTrue {
for index, lib := range file.LibReferenceDirectives {
includeReason := &FileIncludeReason{
kind: fileIncludeKindLibReferenceDirective,
data: &referencedFileData{
file: t.path,
index: index,
},
}
if name, ok := tsoptions.GetLibFileName(lib.FileName); ok {
libFile := loader.pathForLibFile(name)
t.addSubTask(resolvedRef{
fileName: libFile.path,
includeReason: includeReason,
}, libFile)
} else {
t.processingDiagnostics = append(t.processingDiagnostics, &processingDiagnostic{
kind: processingDiagnosticKindUnknownReference,
data: includeReason,
})
}
}
}
loader.resolveImportsAndModuleAugmentations(t)
}
func (t *parseTask) redirect(loader *fileLoader, fileName string) {
t.redirectedParseTask = &parseTask{
normalizedFilePath: tspath.NormalizePath(fileName),
libFile: t.libFile,
includeReason: t.includeReason,
}
// increaseDepth and elideOnDepth are not copied to redirects, otherwise their depth would be double counted.
t.subTasks = []*parseTask{t.redirectedParseTask}
}
func (t *parseTask) loadAutomaticTypeDirectives(loader *fileLoader) {
toParseTypeRefs, typeResolutionsInFile, typeResolutionsTrace := loader.resolveAutomaticTypeDirectives(t.normalizedFilePath)
t.typeResolutionsInFile = typeResolutionsInFile
t.typeResolutionsTrace = typeResolutionsTrace
for _, typeResolution := range toParseTypeRefs {
t.addSubTask(typeResolution, nil)
}
}
type resolvedRef struct {
fileName string
increaseDepth bool
elideOnDepth bool
includeReason *FileIncludeReason
}
func (t *parseTask) addSubTask(ref resolvedRef, libFile *LibFile) {
normalizedFilePath := tspath.NormalizePath(ref.fileName)
subTask := &parseTask{
normalizedFilePath: normalizedFilePath,
libFile: libFile,
increaseDepth: ref.increaseDepth,
elideOnDepth: ref.elideOnDepth,
includeReason: ref.includeReason,
}
t.subTasks = append(t.subTasks, subTask)
}
type filesParser struct {
wg core.WorkGroup
taskDataByPath collections.SyncMap[tspath.Path, *parseTaskData]
maxDepth int
}
type parseTaskData struct {
// map of tasks by file casing
tasks map[string]*parseTask
mu sync.Mutex
lowestDepth int
startedSubTasks bool
}
func (w *filesParser) parse(loader *fileLoader, tasks []*parseTask) {
w.start(loader, tasks, 0)
w.wg.RunAndWait()
}
func (w *filesParser) start(loader *fileLoader, tasks []*parseTask, depth int) {
for i, task := range tasks {
task.path = loader.toPath(task.normalizedFilePath)
data, loaded := w.taskDataByPath.LoadOrStore(task.path, &parseTaskData{
tasks: map[string]*parseTask{task.normalizedFilePath: task},
lowestDepth: math.MaxInt,
})
w.wg.Queue(func() {
data.mu.Lock()
defer data.mu.Unlock()
startSubtasks := false
if loaded {
if existingTask, ok := data.tasks[task.normalizedFilePath]; ok {
tasks[i].loadedTask = existingTask
} else {
data.tasks[task.normalizedFilePath] = task
// This is new task for file name - so load subtasks if there was loading for any other casing
startSubtasks = data.startedSubTasks
}
}
currentDepth := core.IfElse(task.increaseDepth, depth+1, depth)
if currentDepth < data.lowestDepth {
// If we're seeing this task at a lower depth than before,
// reprocess its subtasks to ensure they are loaded.
data.lowestDepth = currentDepth
startSubtasks = true
data.startedSubTasks = true
}
if task.elideOnDepth && currentDepth > w.maxDepth {
return
}
for _, taskByFileName := range data.tasks {
loadSubTasks := startSubtasks
if !taskByFileName.loaded {
taskByFileName.load(loader)
if taskByFileName.redirectedParseTask != nil {
// Always load redirected task
loadSubTasks = true
data.startedSubTasks = true
}
}
if !taskByFileName.startedSubTasks && loadSubTasks {
taskByFileName.startedSubTasks = true
w.start(loader, taskByFileName.subTasks, data.lowestDepth)
}
}
})
}
}
func (w *filesParser) getProcessedFiles(loader *fileLoader) processedFiles {
totalFileCount := int(loader.totalFileCount.Load())
libFileCount := int(loader.libFileCount.Load())
var missingFiles []string
files := make([]*ast.SourceFile, 0, totalFileCount-libFileCount)
libFiles := make([]*ast.SourceFile, 0, totalFileCount) // totalFileCount here since we append files to it later to construct the final list
filesByPath := make(map[tspath.Path]*ast.SourceFile, totalFileCount)
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
var tasksSeenByNameIgnoreCase map[string]*parseTask
if loader.comparePathsOptions.UseCaseSensitiveFileNames {
tasksSeenByNameIgnoreCase = make(map[string]*parseTask, totalFileCount)
}
includeProcessor := &includeProcessor{
fileIncludeReasons: make(map[tspath.Path][]*FileIncludeReason, totalFileCount),
}
var outputFileToProjectReferenceSource map[tspath.Path]string
if !loader.opts.canUseProjectReferenceSource() {
outputFileToProjectReferenceSource = make(map[tspath.Path]string, totalFileCount)
}
resolvedModules := make(map[tspath.Path]module.ModeAwareCache[*module.ResolvedModule], totalFileCount+1)
typeResolutionsInFile := make(map[tspath.Path]module.ModeAwareCache[*module.ResolvedTypeReferenceDirective], totalFileCount)
sourceFileMetaDatas := make(map[tspath.Path]ast.SourceFileMetaData, totalFileCount)
var jsxRuntimeImportSpecifiers map[tspath.Path]*jsxRuntimeImportSpecifier
var importHelpersImportSpecifiers map[tspath.Path]*ast.Node
var sourceFilesFoundSearchingNodeModules collections.Set[tspath.Path]
libFilesMap := make(map[tspath.Path]*LibFile, libFileCount)
var sourceFileToPackageName map[tspath.Path]string
var redirectTargetsMap map[tspath.Path][]string
var deduplicatedPathMap map[tspath.Path]tspath.Path
var packageIdToCanonicalPath map[module.PackageId]tspath.Path
if !loader.opts.Config.CompilerOptions().DisablePackageDeduplication.IsTrue() {
sourceFileToPackageName = make(map[tspath.Path]string, totalFileCount)
redirectTargetsMap = make(map[tspath.Path][]string)
deduplicatedPathMap = make(map[tspath.Path]tspath.Path)
packageIdToCanonicalPath = make(map[module.PackageId]tspath.Path)
}
var collectFiles func(tasks []*parseTask, seen map[*parseTaskData]string)
collectFiles = func(tasks []*parseTask, seen map[*parseTaskData]string) {
for _, task := range tasks {
includeReason := task.includeReason
// Exclude automatic type directive tasks from include reason processing,
// as these are internal implementation details and should not contribute
// to the reasons for including files.
if task.redirectedParseTask == nil && !task.isForAutomaticTypeDirective {
if task.loadedTask != nil {
task = task.loadedTask
}
w.addIncludeReason(includeProcessor, task, includeReason)
}
data, _ := w.taskDataByPath.Load(task.path)
if !task.loaded {
continue
}
// ensure we only walk each task once
if checkedName, ok := seen[data]; ok {
if !loader.opts.Config.CompilerOptions().ForceConsistentCasingInFileNames.IsFalse() {
// Check if it differs only in drive letters its ok to ignore that error:
checkedAbsolutePath := tspath.GetNormalizedAbsolutePathWithoutRoot(checkedName, loader.comparePathsOptions.CurrentDirectory)
inputAbsolutePath := tspath.GetNormalizedAbsolutePathWithoutRoot(task.normalizedFilePath, loader.comparePathsOptions.CurrentDirectory)
if checkedAbsolutePath != inputAbsolutePath {
includeProcessor.addProcessingDiagnosticsForFileCasing(task.path, checkedName, task.normalizedFilePath, includeReason)
}
}
continue
} else {
seen[data] = task.normalizedFilePath
}
if tasksSeenByNameIgnoreCase != nil {
pathLowerCase := tspath.ToFileNameLowerCase(string(task.path))
if taskByIgnoreCase, ok := tasksSeenByNameIgnoreCase[pathLowerCase]; ok {
includeProcessor.addProcessingDiagnosticsForFileCasing(taskByIgnoreCase.path, taskByIgnoreCase.normalizedFilePath, task.normalizedFilePath, includeReason)
} else {
tasksSeenByNameIgnoreCase[pathLowerCase] = task
}
}
for _, trace := range task.typeResolutionsTrace {
loader.opts.Host.Trace(trace.Message, trace.Args...)
}
for _, trace := range task.resolutionsTrace {
loader.opts.Host.Trace(trace.Message, trace.Args...)
}
if packageIdToCanonicalPath != nil {
for _, resolution := range task.resolutionsInFile {
if !resolution.IsResolved() {
continue
}
pkgId := resolution.PackageId
if pkgId.Name == "" {
continue
}
resolvedPath := loader.toPath(resolution.ResolvedFileName)
packageName := pkgId.PackageName()
if canonical, exists := packageIdToCanonicalPath[pkgId]; exists {
if _, alreadyRecorded := sourceFileToPackageName[resolvedPath]; !alreadyRecorded {
sourceFileToPackageName[resolvedPath] = packageName
if resolvedPath != canonical {
deduplicatedPathMap[resolvedPath] = canonical
redirectTargetsMap[canonical] = append(redirectTargetsMap[canonical], resolution.ResolvedFileName)
}
}
} else {
packageIdToCanonicalPath[pkgId] = resolvedPath
sourceFileToPackageName[resolvedPath] = packageName
deduplicatedPathMap[resolvedPath] = resolvedPath
}
}
}
if subTasks := task.subTasks; len(subTasks) > 0 {
collectFiles(subTasks, seen)
}
// Exclude automatic type directive tasks from include reason processing,
// as these are internal implementation details and should not contribute
// to the reasons for including files.
if task.redirectedParseTask != nil {
if !loader.opts.canUseProjectReferenceSource() {
outputFileToProjectReferenceSource[task.redirectedParseTask.path] = task.FileName()
}
continue
}
if task.isForAutomaticTypeDirective {
typeResolutionsInFile[task.path] = task.typeResolutionsInFile
continue
}
file := task.file
path := task.path
if len(task.processingDiagnostics) > 0 {
includeProcessor.processingDiagnostics = append(includeProcessor.processingDiagnostics, task.processingDiagnostics...)
}
if file == nil {
// !!! sheetal file preprocessing diagnostic explaining getSourceFileFromReferenceWorker
missingFiles = append(missingFiles, task.normalizedFilePath)
continue
}
if task.libFile != nil {
libFiles = append(libFiles, file)
libFilesMap[path] = task.libFile
} else {
files = append(files, file)
}
filesByPath[path] = file
resolvedModules[path] = task.resolutionsInFile
typeResolutionsInFile[path] = task.typeResolutionsInFile
sourceFileMetaDatas[path] = task.metadata
if task.jsxRuntimeImportSpecifier != nil {
if jsxRuntimeImportSpecifiers == nil {
jsxRuntimeImportSpecifiers = make(map[tspath.Path]*jsxRuntimeImportSpecifier, totalFileCount)
}
jsxRuntimeImportSpecifiers[path] = task.jsxRuntimeImportSpecifier
}
if task.importHelpersImportSpecifier != nil {
if importHelpersImportSpecifiers == nil {
importHelpersImportSpecifiers = make(map[tspath.Path]*ast.Node, totalFileCount)
}
importHelpersImportSpecifiers[path] = task.importHelpersImportSpecifier
}
if data.lowestDepth > 0 {
sourceFilesFoundSearchingNodeModules.Add(path)
}
}
}
collectFiles(loader.rootTasks, make(map[*parseTaskData]string, totalFileCount))
loader.sortLibs(libFiles)
allFiles := append(libFiles, files...)
keys := slices.Collect(loader.pathForLibFileResolutions.Keys())
slices.Sort(keys)
for _, key := range keys {
value, _ := loader.pathForLibFileResolutions.Load(key)
resolvedModules[key] = module.ModeAwareCache[*module.ResolvedModule]{
module.ModeAwareCacheKey{Name: value.libraryName, Mode: core.ModuleKindCommonJS}: value.resolution,
}
for _, trace := range value.trace {
loader.opts.Host.Trace(trace.Message, trace.Args...)
}
}
if deduplicatedPathMap != nil {
for duplicatePath, canonicalPath := range deduplicatedPathMap {
if duplicatePath != canonicalPath {
if canonicalFile, ok := filesByPath[canonicalPath]; ok {
filesByPath[duplicatePath] = canonicalFile
}
}
}
allFiles = slices.DeleteFunc(allFiles, func(f *ast.SourceFile) bool {
if canonicalPath, ok := deduplicatedPathMap[f.Path()]; ok {
return f.Path() != canonicalPath
}
return false
})
}
return processedFiles{
finishedProcessing: true,
resolver: loader.resolver,
files: allFiles,
filesByPath: filesByPath,
projectReferenceFileMapper: loader.projectReferenceFileMapper,
resolvedModules: resolvedModules,
typeResolutionsInFile: typeResolutionsInFile,
sourceFileMetaDatas: sourceFileMetaDatas,
jsxRuntimeImportSpecifiers: jsxRuntimeImportSpecifiers,
importHelpersImportSpecifiers: importHelpersImportSpecifiers,
sourceFilesFoundSearchingNodeModules: sourceFilesFoundSearchingNodeModules,
libFiles: libFilesMap,
missingFiles: missingFiles,
includeProcessor: includeProcessor,
outputFileToProjectReferenceSource: outputFileToProjectReferenceSource,
sourceFileToPackageName: sourceFileToPackageName,
redirectTargetsMap: redirectTargetsMap,
deduplicatedPathMap: deduplicatedPathMap,
}
}
func (w *filesParser) addIncludeReason(includeProcessor *includeProcessor, task *parseTask, reason *FileIncludeReason) {
if task.redirectedParseTask != nil {
w.addIncludeReason(includeProcessor, task.redirectedParseTask, reason)
} else if task.loaded {
if existing, ok := includeProcessor.fileIncludeReasons[task.path]; ok {
includeProcessor.fileIncludeReasons[task.path] = append(existing, reason)
} else {
includeProcessor.fileIncludeReasons[task.path] = []*FileIncludeReason{reason}
}
}
}