-
Notifications
You must be signed in to change notification settings - Fork 15.3k
Expand file tree
/
Copy pathprogram.go
More file actions
2484 lines (2209 loc) · 101 KB
/
Copy pathprogram.go
File metadata and controls
2484 lines (2209 loc) · 101 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package compiler
import (
"context"
"fmt"
"io"
"maps"
"slices"
"strings"
"sync"
"sync/atomic"
"github.com/microsoft/TypeScript/tsc/internal/ast"
"github.com/microsoft/TypeScript/tsc/internal/binder"
"github.com/microsoft/TypeScript/tsc/internal/checker"
"github.com/microsoft/TypeScript/tsc/internal/collections"
"github.com/microsoft/TypeScript/tsc/internal/contentmapper"
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/diagnostics"
"github.com/microsoft/TypeScript/tsc/internal/json"
"github.com/microsoft/TypeScript/tsc/internal/locale"
"github.com/microsoft/TypeScript/tsc/internal/module"
"github.com/microsoft/TypeScript/tsc/internal/modulespecifiers"
"github.com/microsoft/TypeScript/tsc/internal/outputpaths"
"github.com/microsoft/TypeScript/tsc/internal/packagejson"
"github.com/microsoft/TypeScript/tsc/internal/parser"
"github.com/microsoft/TypeScript/tsc/internal/printer"
"github.com/microsoft/TypeScript/tsc/internal/scanner"
"github.com/microsoft/TypeScript/tsc/internal/sourcemap"
"github.com/microsoft/TypeScript/tsc/internal/spanmap"
"github.com/microsoft/TypeScript/tsc/internal/symlinks"
"github.com/microsoft/TypeScript/tsc/internal/tracing"
"github.com/microsoft/TypeScript/tsc/internal/tsoptions"
"github.com/microsoft/TypeScript/tsc/internal/tspath"
)
type ProgramOptions struct {
Host CompilerHost
Config *tsoptions.ParsedCommandLine
UseSourceOfProjectReference bool
SingleThreaded core.Tristate
CreateCheckerPool func(*Program) CheckerPool
TypingsLocation string
ProjectName string
Tracing *tracing.Tracing
CreateModuleResolver func(options module.ResolverOptions) module.Resolver
// SkipModuleResolution avoids all module and type reference resolution while
// still collecting import metadata needed for emit.
SkipModuleResolution bool
}
func (p *ProgramOptions) canUseProjectReferenceSource() bool {
return p.UseSourceOfProjectReference && !p.Config.CompilerOptions().DisableSourceOfProjectReferenceRedirect.IsTrue()
}
type lazyValue[T any] struct {
value *T
once sync.Once
initialized atomic.Bool
}
func (l *lazyValue[T]) getValue(compute func() *T) *T {
l.once.Do(func() {
if l.value == nil {
l.value = compute()
}
l.initialized.Store(true)
})
return l.value
}
func (l *lazyValue[T]) tryReuse(from *lazyValue[T]) {
if from.initialized.Load() {
l.value = from.value
l.initialized.Store(true)
}
}
type packageNamesInfo struct {
resolved *collections.Set[string]
unresolved *collections.Set[string]
deepImportPackages *collections.Set[string]
}
type Program struct {
opts ProgramOptions
checkerPool CheckerPool // always set; used as fallback for project system pools
// compilerCheckerPool is set only when the built-in compiler checker pool is in use
// (i.e. CreateCheckerPool was not provided). It enables grouped parallel iteration,
// non-exclusive access for emit, and direct global diagnostics collection.
compilerCheckerPool *checkerPool
comparePathsOptions tspath.ComparePathsOptions
processedFiles
usesUriStyleNodeCoreModules core.Tristate
commonSourceDirectory string
commonSourceDirectoryOnce sync.Once
declarationDiagnosticCache collections.SyncMap[*ast.SourceFile, []*ast.Diagnostic]
programDiagnostics []*ast.Diagnostic
hasEmitBlockingDiagnostics collections.Set[tspath.Path]
contentMapperOptionDiagnostics []*ast.Diagnostic
sourceFilesToEmitOnce sync.Once
sourceFilesToEmit []*ast.SourceFile
// Cached unresolved imports for ATA
unresolvedImports lazyValue[collections.Set[string]]
knownSymlinks lazyValue[symlinks.KnownSymlinks]
// Used by auto-imports
packageNames lazyValue[packageNamesInfo]
// Used by workspace/symbol
hasTSFileOnce sync.Once
hasTSFile bool
// Cached map of package names to whether they bundle types
packagesMapOnce sync.Once
packagesMap map[string]bool
}
// FileExists implements checker.Program.
func (p *Program) FileExists(path string) bool {
return p.Host().FS().FileExists(path)
}
// GetCurrentDirectory implements checker.Program.
func (p *Program) GetCurrentDirectory() string {
return p.Host().GetCurrentDirectory()
}
func (p *Program) ContentMapperProject() contentmapper.Project {
return p.opts.Host.ContentMapperProject()
}
// GetGlobalTypingsCacheLocation implements checker.Program.
func (p *Program) GetGlobalTypingsCacheLocation() string {
return p.opts.TypingsLocation
}
// GetNearestAncestorDirectoryWithPackageJson implements checker.Program.
func (p *Program) GetNearestAncestorDirectoryWithPackageJson(dirname string) string {
scoped := p.resolver.GetPackageScopeForPath(dirname)
if scoped != nil && scoped.Exists() {
return scoped.PackageDirectory
}
return ""
}
// GetPackageJsonInfo implements checker.Program.
func (p *Program) GetPackageJsonInfo(pkgJsonPath string) *packagejson.InfoCacheEntry {
directory := tspath.GetDirectoryPath(pkgJsonPath)
scoped := p.resolver.GetPackageScopeForPath(directory)
if scoped != nil && scoped.Exists() && scoped.PackageDirectory == directory {
return scoped
}
return nil
}
// PackageJsonCacheEntries iterates on all package json cache entries.
func (p *Program) PackageJsonCacheEntries(f func(key tspath.Path, value *packagejson.InfoCacheEntry) bool) {
p.resolver.PackageJsonCacheEntries(f)
}
// GetRedirectTargets returns the list of file paths that redirect to the given path.
// These are files from the same package (same name@version) installed in different locations.
func (p *Program) GetRedirectTargets(path tspath.Path) []string {
return p.redirectTargetsMap[path]
}
// gets the original file that was included in program
// this returns original source file name when including output of project reference
// otherwise same name
// Equivalent to originalFileName on SourceFile in Strada
func (p *Program) GetSourceOfProjectReferenceIfOutputIncluded(file ast.HasFileName) string {
if source, ok := p.outputFileToProjectReferenceSource[file.Path()]; ok {
return source
}
return file.FileName()
}
// GetProjectReferenceFromSource implements checker.Program.
func (p *Program) GetProjectReferenceFromSource(path tspath.Path) *tsoptions.SourceOutputAndProjectReference {
return p.projectReferenceFileMapper.getProjectReferenceFromSource(path)
}
// IsSourceFromProjectReference implements checker.Program.
func (p *Program) IsSourceFromProjectReference(path tspath.Path) bool {
return p.projectReferenceFileMapper.isSourceFromProjectReference(path)
}
func (p *Program) GetProjectReferenceFromOutputDts(path tspath.Path) *tsoptions.SourceOutputAndProjectReference {
return p.projectReferenceFileMapper.getProjectReferenceFromOutputDts(path)
}
func (p *Program) GetResolvedProjectReferenceFor(path tspath.Path) (*tsoptions.ParsedCommandLine, bool) {
return p.projectReferenceFileMapper.getResolvedReferenceFor(path)
}
func (p *Program) GetRedirectForResolution(file ast.HasFileName) *tsoptions.ParsedCommandLine {
redirect, _ := p.projectReferenceFileMapper.getRedirectForResolution(file)
return redirect
}
func (p *Program) GetParseFileRedirect(fileName string) string {
return p.projectReferenceFileMapper.getParseFileRedirect(ast.NewHasFileName(fileName, p.toPath(fileName)))
}
func (p *Program) GetResolvedProjectReferences() []*tsoptions.ParsedCommandLine {
return p.projectReferenceFileMapper.getResolvedProjectReferences()
}
func (p *Program) RangeResolvedProjectReference(f func(path tspath.Path, config *tsoptions.ParsedCommandLine, parent *tsoptions.ParsedCommandLine, index int) bool) bool {
return p.projectReferenceFileMapper.rangeResolvedProjectReference(f)
}
func (p *Program) RangeResolvedProjectReferenceInChildConfig(
childConfig *tsoptions.ParsedCommandLine,
f func(path tspath.Path, config *tsoptions.ParsedCommandLine, parent *tsoptions.ParsedCommandLine, index int) bool,
) bool {
return p.projectReferenceFileMapper.rangeResolvedProjectReferenceInChildConfig(childConfig, f)
}
// UseCaseSensitiveFileNames implements checker.Program.
func (p *Program) UseCaseSensitiveFileNames() bool {
return p.Host().FS().UseCaseSensitiveFileNames()
}
func (p *Program) UsesUriStyleNodeCoreModules() core.Tristate {
return p.usesUriStyleNodeCoreModules
}
var _ checker.Program = (*Program)(nil)
/** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
func (p *Program) GetSourceFileFromReference(origin *ast.SourceFile, ref *ast.FileReference) *ast.SourceFile {
// TODO: The module loader in corsa is fairly different than strada, it should probably be able to expose this functionality at some point,
// rather than redoing the logic approximately here, since most of the related logic now lives in module.Resolver
// Still, without the failed lookup reporting that only the loader does, this isn't terribly complicated
fileName := tspath.ResolvePath(tspath.GetDirectoryPath(origin.FileName()), ref.FileName)
supportedExtensionsBase := tsoptions.GetSupportedExtensions(p.Options(), p.CommandLine().ContentMapperExtensions())
supportedExtensions := tsoptions.GetSupportedExtensionsWithJsonIfResolveJsonModule(p.Options(), supportedExtensionsBase)
allowNonTsExtensions := p.Options().AllowNonTsExtensions.IsTrue()
if tspath.HasExtension(fileName) {
if !allowNonTsExtensions {
canonicalFileName := tspath.GetCanonicalFileName(fileName, p.UseCaseSensitiveFileNames())
supported := false
for _, group := range supportedExtensions {
if tspath.FileExtensionIsOneOf(canonicalFileName, group) {
supported = true
break
}
}
if !supported {
return nil // unsupported extensions are forced to fail
}
}
return p.GetSourceFileForResolvedModule(fileName)
}
if allowNonTsExtensions {
extensionless := p.GetSourceFileForResolvedModule(fileName)
if extensionless != nil {
return extensionless
}
}
// Only try adding extensions from the first supported group (which should be .ts/.tsx/.d.ts)
for _, ext := range supportedExtensions[0] {
result := p.GetSourceFileForResolvedModule(fileName + ext)
if result != nil {
return result
}
}
return nil
}
func NewProgram(opts ProgramOptions) *Program {
p := &Program{opts: opts}
if p.opts.Tracing != nil {
defer p.opts.Tracing.Push(tracing.PhaseProgram, "createProgram", map[string]any{"configFilePath": opts.Config.CompilerOptions().ConfigFilePath}, true)()
}
p.processedFiles = processAllProgramFiles(p.opts, p.SingleThreaded())
p.initCheckerPool()
p.verifyCompilerOptions()
p.collectContentMapperOptionDiagnostics()
return p
}
// Return an updated program for which it is known that only the file with the given path has changed.
// In addition to a new program, return a boolean indicating whether the data of the old program was reused.
// createCheckerPool, if non-nil, overrides the CreateCheckerPool stored in the old program's options,
// ensuring each caller uses a fresh closure and avoiding data races on captured variables.
// The returned *ast.SourceFile is the changed file as acquired through newHost; it is nil
// only if the host cannot locate the file (e.g. it was deleted). Callers that manage
// host-side parse caches must release this exact pointer when the old program could not be
// reused, since it was acquired speculatively before that decision was made.
func (p *Program) UpdateProgram(
changedFilePath tspath.Path,
newHost CompilerHost,
createCheckerPool func(*Program) CheckerPool,
createModuleResolver func(module.ResolverOptions) module.Resolver,
) (*Program, *ast.SourceFile, bool) {
if result, newFile, reused := p.ReuseProgram(changedFilePath, newHost, createCheckerPool, createModuleResolver); reused {
return result, newFile, true
} else {
newOpts := p.opts
newOpts.Host = newHost
if createCheckerPool != nil {
newOpts.CreateCheckerPool = createCheckerPool
}
if createModuleResolver != nil {
newOpts.CreateModuleResolver = createModuleResolver
}
return NewProgram(newOpts), newFile, false
}
}
// ReuseProgram attempts to produce a new program by replacing only
// changedFilePath in place, reusing the rest of p. It returns
// (newProgram, newFile, true) on success, or (nil, newFile, false) when the
// file cannot be replaced in place. Unlike UpdateProgram, it never constructs a
// full fallback program, so callers that build their own fallback (e.g. with a
// different host) do not pay for a discarded program build.
func (p *Program) ReuseProgram(
changedFilePath tspath.Path,
newHost CompilerHost,
createCheckerPool func(*Program) CheckerPool,
createModuleResolver func(module.ResolverOptions) module.Resolver,
) (*Program, *ast.SourceFile, bool) {
newOpts := p.opts
newOpts.Host = newHost
if createCheckerPool != nil {
newOpts.CreateCheckerPool = createCheckerPool
}
if createModuleResolver != nil {
newOpts.CreateModuleResolver = createModuleResolver
}
oldFile := p.filesByPath[changedFilePath]
var newFile *ast.SourceFile
var oldSupplementalFiles []*ast.SourceFile
var newSupplementalFiles []*ast.SourceFile
if oldFile.ContentMapper() != "" {
// Content-mapped files are produced by running an external transform, which a plain reparse can't
// reproduce. Re-run the transform through the host; any failure (or a missing file) falls back to
// a full rebuild so the file loader's failure policy runs.
mapper := newOpts.Config.GetContentMapperForFileName(oldFile.FileName())
var err error
files, transformErr := newHost.GetContentMappedSourceFiles(oldFile.ParseOptions(), mapper)
newFile, err = files.Canonical, transformErr
if err != nil {
return nil, nil, false
}
oldSupplementalFiles = oldFile.SupplementalSourceFiles()
newSupplementalFiles = files.Supplemental
} else {
newFile = newHost.GetSourceFile(oldFile.ParseOptions())
}
// If this file is part of a package redirect group (same package installed in multiple
// node_modules locations), we need to rebuild the program because the redirect targets
// might need recalculation.
_, inRedirectFiles := p.redirectFilesByPath[changedFilePath]
_, isRedirectTarget := p.redirectTargetsMap[changedFilePath]
if inRedirectFiles || isRedirectTarget {
return nil, newFile, false
}
if !p.canReplaceFileInProgram(oldFile, newFile) {
return nil, newFile, false
}
// Cloning does not recompute synthetic helper or JSX-runtime import bookkeeping. Fall back to a full
// build whenever either version requires those imports.
if p.importHelpersImportSpecifiers[oldFile.Path()] != nil || p.needsImportHelpersImportSpecifier(newFile) {
return nil, newFile, false
}
if p.jsxRuntimeImportSpecifiers[oldFile.Path()] != nil || p.jsxRuntimeImportSpecifier(newFile) != "" {
return nil, newFile, false
}
if len(oldSupplementalFiles) != len(newSupplementalFiles) {
return nil, newFile, false
}
for i, oldSupplemental := range oldSupplementalFiles {
newSupplemental := newSupplementalFiles[i]
if oldSupplemental.Path() != newSupplemental.Path() ||
!p.canReplaceFileInProgram(oldSupplemental, newSupplemental) {
return nil, newFile, false
}
if p.importHelpersImportSpecifiers[oldSupplemental.Path()] != nil || p.needsImportHelpersImportSpecifier(newSupplemental) {
return nil, newFile, false
}
if p.jsxRuntimeImportSpecifiers[oldSupplemental.Path()] != nil || p.jsxRuntimeImportSpecifier(newSupplemental) != "" {
return nil, newFile, false
}
}
// TODO: reverify compiler options when config has changed?
result := &Program{
opts: newOpts,
comparePathsOptions: p.comparePathsOptions,
processedFiles: p.processedFiles,
usesUriStyleNodeCoreModules: p.usesUriStyleNodeCoreModules,
programDiagnostics: p.programDiagnostics,
hasEmitBlockingDiagnostics: p.hasEmitBlockingDiagnostics,
contentMapperOptionDiagnostics: slices.Clone(p.contentMapperOptionDiagnostics),
}
result.unresolvedImports.tryReuse(&p.unresolvedImports)
result.knownSymlinks.tryReuse(&p.knownSymlinks)
result.packageNames.tryReuse(&p.packageNames)
result.initCheckerPool()
index := core.FindIndex(result.files, func(file *ast.SourceFile) bool { return file.Path() == newFile.Path() })
result.files = slices.Clone(result.files)
result.files[index] = newFile
result.filesByPath = maps.Clone(result.filesByPath)
result.filesByPath[newFile.Path()] = newFile
if len(oldSupplementalFiles) != 0 {
for i, oldSupplemental := range oldSupplementalFiles {
newSupplemental := newSupplementalFiles[i]
supplementalIndex := core.FindIndex(result.files, func(file *ast.SourceFile) bool { return file == oldSupplemental })
result.files[supplementalIndex] = newSupplemental
result.filesByPath[newSupplemental.Path()] = newSupplemental
}
}
updateFileIncludeProcessor(result)
return result, newFile, true
}
func (p *Program) initCheckerPool() {
if !p.finishedProcessing {
panic("Program must finish processing files before initializing checker pool")
}
if p.opts.CreateCheckerPool != nil {
p.checkerPool = p.opts.CreateCheckerPool(p)
} else {
pool := newCheckerPoolWithTracing(p, p.opts.Tracing)
p.checkerPool = pool
p.compilerCheckerPool = pool
}
}
// GetCheckerPool returns the checker pool associated with this program.
func (p *Program) GetCheckerPool() CheckerPool {
return p.checkerPool
}
func (p *Program) canReplaceFileInProgram(file1 *ast.SourceFile, file2 *ast.SourceFile) bool {
return file2 != nil &&
file1.ParseOptions() == file2.ParseOptions() &&
file1.ScriptKind == file2.ScriptKind &&
ast.IsExternalOrCommonJSModule(file1) == ast.IsExternalOrCommonJSModule(file2) &&
file1.UsesUriStyleNodeCoreModules == file2.UsesUriStyleNodeCoreModules &&
slices.EqualFunc(file1.Imports(), file2.Imports(), func(n1 *ast.Node, n2 *ast.Node) bool {
return equalModuleSpecifiers(n1, n2) &&
p.GetModeForUsageLocation(file1, n1) == p.GetModeForUsageLocation(file2, n2)
}) &&
slices.EqualFunc(file1.ModuleAugmentations, file2.ModuleAugmentations, equalModuleAugmentationNames) &&
slices.Equal(file1.AmbientModuleNames, file2.AmbientModuleNames) &&
slices.EqualFunc(file1.ReferencedFiles, file2.ReferencedFiles, equalFileReferences) &&
slices.EqualFunc(file1.TypeReferenceDirectives, file2.TypeReferenceDirectives, equalFileReferences) &&
slices.EqualFunc(file1.LibReferenceDirectives, file2.LibReferenceDirectives, equalFileReferences) &&
equalCheckJSDirectives(file1.CheckJsDirective, file2.CheckJsDirective)
}
func (p *Program) needsImportHelpersImportSpecifier(file *ast.SourceFile) bool {
redirect, _ := p.projectReferenceFileMapper.getRedirectForResolution(file)
optionsForFile := module.GetCompilerOptionsWithRedirect(p.opts.Config.CompilerOptions(), redirect)
if !optionsForFile.ImportHelpers.IsTrue() {
return false
}
isJavaScriptFile := ast.IsSourceFileJS(file)
isExternalModuleFile := ast.IsExternalModule(file)
if !isJavaScriptFile && (file.IsDeclarationFile || (!optionsForFile.GetIsolatedModules() && !isExternalModuleFile)) {
return false
}
return true
}
func (p *Program) jsxRuntimeImportSpecifier(file *ast.SourceFile) string {
if !ast.IsSourceFileJS(file) && file.ScriptKind != core.ScriptKindTSX {
return ""
}
redirect, _ := p.projectReferenceFileMapper.getRedirectForResolution(file)
optionsForFile := module.GetCompilerOptionsWithRedirect(p.opts.Config.CompilerOptions(), redirect)
return ast.GetJSXRuntimeImport(ast.GetJSXImplicitImportBase(optionsForFile, file), optionsForFile)
}
func equalModuleSpecifiers(n1 *ast.Node, n2 *ast.Node) bool {
return n1.Kind == n2.Kind && (!ast.IsStringLiteral(n1) || n1.Text() == n2.Text())
}
func equalModuleAugmentationNames(n1 *ast.Node, n2 *ast.Node) bool {
return n1.Kind == n2.Kind && n1.Text() == n2.Text()
}
func equalFileReferences(f1 *ast.FileReference, f2 *ast.FileReference) bool {
return f1.FileName == f2.FileName && f1.ResolutionMode == f2.ResolutionMode && f1.Preserve == f2.Preserve
}
func equalCheckJSDirectives(d1 *ast.CheckJsDirective, d2 *ast.CheckJsDirective) bool {
return d1 == nil && d2 == nil || d1 != nil && d2 != nil && d1.Enabled == d2.Enabled
}
func (p *Program) SourceFiles() []*ast.SourceFile { return p.files }
func (p *Program) DuplicateSourceFiles() []*DuplicateSourceFile { return p.duplicateSourceFiles }
func (p *Program) Options() *core.CompilerOptions { return p.opts.Config.CompilerOptions() }
// GetContentMapper returns the content mapper that produced the given source file, or nil if the
// file was not produced by a content mapper.
func (p *Program) GetContentMapper(file *ast.SourceFile) *contentmapper.Mapper {
if file.ContentMapper() == "" {
return nil
}
mapper := p.opts.Config.GetContentMapperForFileName(file.FileName())
if mapper != nil && mapper.Identity() == file.ContentMapper() {
return mapper
}
return nil
}
func (p *Program) ContentMapperExtensions() []string { return p.opts.Config.ContentMapperExtensions() }
func (p *Program) CommandLine() *tsoptions.ParsedCommandLine { return p.opts.Config }
func (p *Program) Host() CompilerHost { return p.opts.Host }
func (p *Program) Tracing() *tracing.Tracing { return p.opts.Tracing }
func (p *Program) GetConfigFileParsingDiagnostics() []*ast.Diagnostic {
return slices.Clip(p.opts.Config.GetConfigFileParsingDiagnostics())
}
// GetUnresolvedImports returns the unresolved imports for this program.
// The result is cached and computed only once.
func (p *Program) GetUnresolvedImports() *collections.Set[string] {
return p.unresolvedImports.getValue(p.extractUnresolvedImports)
}
func (p *Program) extractUnresolvedImports() *collections.Set[string] {
unresolvedSet := &collections.Set[string]{}
for _, sourceFile := range p.files {
unresolvedImports := p.extractUnresolvedImportsFromSourceFile(sourceFile)
for _, imp := range unresolvedImports {
unresolvedSet.Add(imp)
}
}
return unresolvedSet
}
func (p *Program) extractUnresolvedImportsFromSourceFile(file *ast.SourceFile) []string {
var unresolvedImports []string
resolvedModules := p.resolvedModules[file.Path()]
for cacheKey, resolution := range resolvedModules {
resolved := resolution.IsResolved()
if (!resolved || !tspath.ExtensionIsOneOf(resolution.Extension, tspath.SupportedTSExtensionsWithJsonFlat)) &&
!tspath.IsExternalModuleNameRelative(cacheKey.Name) {
unresolvedImports = append(unresolvedImports, cacheKey.Name)
}
}
return unresolvedImports
}
func (p *Program) SingleThreaded() bool {
return p.opts.SingleThreaded.DefaultIfUnknown(p.Options().SingleThreaded).IsTrue()
}
func (p *Program) BindSourceFiles() {
wg := core.NewWorkGroup(p.SingleThreaded())
for _, file := range p.files {
if !file.IsBound() {
wg.Queue(func() {
if p.opts.Tracing != nil {
defer p.opts.Tracing.Push(tracing.PhaseBind, "bindSourceFile", map[string]any{"path": string(file.Path())}, true)()
}
binder.BindSourceFile(file)
})
}
}
wg.RunAndWait()
}
// Return the type checker associated with the program.
func (p *Program) GetTypeChecker(ctx context.Context) (*checker.Checker, func()) {
if p.compilerCheckerPool != nil {
return p.compilerCheckerPool.getCheckerNonExclusive()
}
return p.checkerPool.GetChecker(ctx, nil)
}
func (p *Program) ForEachCheckerParallel(cb func(idx int, c *checker.Checker)) {
if p.compilerCheckerPool != nil {
p.compilerCheckerPool.forEachCheckerParallel(cb)
}
}
// Return a checker for the given file. We may have multiple checkers in concurrent scenarios and this
// method returns the checker that was tasked with checking the file. Note that it isn't possible to mix
// types obtained from different checkers, so only non-type data (such as diagnostics or string
// representations of types) should be obtained from checkers returned by this method.
func (p *Program) GetTypeCheckerForFile(ctx context.Context, file *ast.SourceFile) (*checker.Checker, func()) {
if p.compilerCheckerPool != nil {
return p.compilerCheckerPool.getCheckerForFileNonExclusive(file)
}
return p.checkerPool.GetChecker(ctx, file)
}
// Return a checker for the given file, locked to the current thread to prevent data races from multiple threads
// accessing the same checker. The lock will be released when the `done` function is called.
func (p *Program) GetTypeCheckerForFileExclusive(ctx context.Context, file *ast.SourceFile) (*checker.Checker, func()) {
if p.compilerCheckerPool != nil {
return p.compilerCheckerPool.getCheckerForFileExclusive(ctx, file)
}
return p.checkerPool.GetChecker(ctx, file)
}
func (p *Program) GetResolvedModule(file ast.HasFileName, moduleReference string, mode core.ResolutionMode) *module.ResolvedModule {
if resolutions, ok := p.resolvedModules[file.Path()]; ok {
if resolved, ok := resolutions[module.ModeAwareCacheKey{Name: moduleReference, Mode: mode}]; ok {
return resolved
}
}
return nil
}
func (p *Program) GetResolvedModuleFromModuleSpecifier(file ast.HasFileName, moduleSpecifier *ast.StringLiteralLike) *module.ResolvedModule {
if !ast.IsStringLiteralLike(moduleSpecifier) {
panic("moduleSpecifier must be a StringLiteralLike")
}
mode := p.GetModeForUsageLocation(file, moduleSpecifier)
return p.GetResolvedModule(file, moduleSpecifier.Text(), mode)
}
func (p *Program) GetResolvedModules() map[tspath.Path]module.ModeAwareCache[*module.ResolvedModule] {
return p.resolvedModules
}
func (p *Program) ModuleResolutionError() error {
return p.moduleResolutionError
}
// GetPackagesMap returns a lazily-cached map of package names to whether they bundle types.
// This is used by incremental diagnostic repopulation.
func (p *Program) GetPackagesMap() map[string]bool {
p.packagesMapOnce.Do(func() {
p.packagesMap = make(map[string]bool)
for _, resolvedModulesInFile := range p.resolvedModules {
for _, mod := range resolvedModulesInFile {
if mod.PackageId.Name != "" {
p.packagesMap[mod.PackageId.Name] = p.packagesMap[mod.PackageId.Name] || mod.Extension == tspath.ExtensionDts
}
}
}
})
return p.packagesMap
}
// collectDiagnostics collects diagnostics from a single file or all files.
// If sourceFile is non-nil, returns diagnostics for just that file.
// If sourceFile is nil, returns diagnostics for all files in the program.
func (p *Program) collectDiagnostics(ctx context.Context, sourceFile *ast.SourceFile, concurrent bool, collect func(context.Context, *ast.SourceFile) []*ast.Diagnostic) []*ast.Diagnostic {
var result []*ast.Diagnostic
if sourceFile != nil {
result = collect(ctx, sourceFile)
} else {
diagnostics := p.collectDiagnosticsFromFiles(ctx, p.files, concurrent, collect)
result = slices.Concat(diagnostics...)
}
return filterAndSortDiagnostics(result)
}
// getWorkerContext returns the context for the per-file workers of a whole-program operation.
// Workers that run on their own goroutines must not act as the request itself,
// or the checker pool would let all of them reuse the one checker the request
// holds at the same time (see core.WithoutRequestID). Single-threaded workers
// run on the caller's goroutine, so they keep the request's identity.
func getWorkerContext(ctx context.Context, singleThreaded bool) context.Context {
if singleThreaded {
return ctx
}
return core.WithoutRequestID(ctx)
}
func (p *Program) collectDiagnosticsFromFiles(ctx context.Context, sourceFiles []*ast.SourceFile, concurrent bool, collect func(context.Context, *ast.SourceFile) []*ast.Diagnostic) [][]*ast.Diagnostic {
diagnostics := make([][]*ast.Diagnostic, len(sourceFiles))
singleThreaded := !concurrent || p.SingleThreaded()
wg := core.NewWorkGroup(singleThreaded)
workerCtx := getWorkerContext(ctx, singleThreaded)
for i, file := range sourceFiles {
wg.Queue(func() {
diagnostics[i] = collect(workerCtx, file)
})
}
wg.RunAndWait()
return diagnostics
}
// collectCheckerDiagnostics collects diagnostics from a single file or all files,
// using a callback that receives the checker for each file. When the checker pool
// supports grouped iteration (compiler pool), files are grouped by checker and
// processed in parallel with one task per checker, reducing contention and improving
// cache locality. Otherwise, falls back to per-file concurrent collection.
func (p *Program) collectCheckerDiagnostics(ctx context.Context, sourceFile *ast.SourceFile, collect func(context.Context, *checker.Checker, *ast.SourceFile) []*ast.Diagnostic) []*ast.Diagnostic {
if sourceFile != nil {
if p.SkipTypeChecking(sourceFile, false) {
return nil
}
c, done := p.GetTypeCheckerForFileExclusive(ctx, sourceFile)
result := collect(ctx, c, sourceFile)
done()
return filterAndSortDiagnostics(result)
}
return filterAndSortDiagnostics(slices.Concat(p.collectCheckerDiagnosticsFromFiles(ctx, p.files, collect)...))
}
func filterAndSortDiagnostics(diags []*ast.Diagnostic) []*ast.Diagnostic {
return SortAndDeduplicateDiagnostics(core.Filter(diags, func(diag *ast.Diagnostic) bool {
file := diag.File()
if !diag.ReportsUnnecessary() || file == nil || file.SpanMap() == nil || diag.Source() != "" {
return true
}
_, fidelity := file.SpanMap().VirtualToOriginalSpan(diag.Loc())
return fidelity != spanmap.FidelityNone
}))
}
// collectCheckerDiagnosticsFromFiles collects checker diagnostics for a list of files.
func (p *Program) collectCheckerDiagnosticsFromFiles(ctx context.Context, sourceFiles []*ast.SourceFile, collect func(context.Context, *checker.Checker, *ast.SourceFile) []*ast.Diagnostic) [][]*ast.Diagnostic {
diagnostics := make([][]*ast.Diagnostic, len(sourceFiles))
if p.compilerCheckerPool != nil {
p.compilerCheckerPool.forEachCheckerGroupDo(ctx, sourceFiles, p.SingleThreaded(), func(c *checker.Checker, fileIndex int, file *ast.SourceFile) {
diagnostics[fileIndex] = collect(ctx, c, file)
})
} else {
wg := core.NewWorkGroup(p.SingleThreaded())
workerCtx := getWorkerContext(ctx, p.SingleThreaded())
for i, file := range sourceFiles {
if p.SkipTypeChecking(file, false) {
continue
}
wg.Queue(func() {
c, done := p.checkerPool.GetChecker(workerCtx, file)
diagnostics[i] = collect(workerCtx, c, file)
done()
})
}
wg.RunAndWait()
}
return diagnostics
}
func (p *Program) GetSyntacticDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.collectDiagnostics(ctx, sourceFile, false /*concurrent*/, func(_ context.Context, file *ast.SourceFile) []*ast.Diagnostic {
diags := core.Concatenate(file.Diagnostics(), file.JSDiagnostics())
// For JS files that won't be checked by the checker (no checkJs/ts-check), we need
// program-level syntactic checks that require compiler options. This mirrors Strada's
// getJSSyntacticDiagnosticsForFile in program.ts.
if ast.IsSourceFileJS(file) && !ast.IsCheckJSEnabledForFile(file, p.Options()) {
diags = append(diags, getAdditionalJSSyntacticDiagnostics(file, p.Options())...)
}
return diags
})
}
// getAdditionalJSSyntacticDiagnostics produces option-dependent syntactic diagnostics for JS files
// that aren't covered by the parser or the checker. In Strada, the equivalent logic lives in
// getJSSyntacticDiagnosticsForFile in program.ts. In Corsa, most of that function's checks were
// moved into the parser (checkJSSyntax/checkJSDecoratorSyntax), but checks that depend on compiler
// options can't live in the parser and must remain here. The checker handles these for checked files,
// but doesn't run on unchecked JS files (no checkJs/ts-check).
func getAdditionalJSSyntacticDiagnostics(file *ast.SourceFile, options *core.CompilerOptions) []*ast.Diagnostic {
if options.ExperimentalDecorators.IsTrue() {
return nil
}
var diags []*ast.Diagnostic
// Parameter decorators are only valid with experimentalDecorators. Without it,
// the checker would report this, but the checker doesn't run on unchecked JS files.
var walk ast.Visitor
walk = func(node *ast.Node) bool {
if node.SubtreeFacts()&ast.SubtreeContainsDecorators == 0 {
return false
}
if node.Kind == ast.KindParameter && ast.HasDecorators(node) {
decorator := core.Find(node.ModifierNodes(), ast.IsDecorator)
if decorator != nil {
diags = append(diags, ast.NewDiagnostic(file, decorator.Loc, diagnostics.Decorators_are_not_valid_here))
}
}
node.ForEachChild(walk)
return false
}
file.AsNode().ForEachChild(walk)
return diags
}
func (p *Program) GetBindDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
if sourceFile != nil {
binder.BindSourceFile(sourceFile)
} else {
p.BindSourceFiles()
}
return p.collectDiagnostics(ctx, sourceFile, false /*concurrent*/, func(_ context.Context, file *ast.SourceFile) []*ast.Diagnostic {
return file.BindDiagnostics()
})
}
func (p *Program) GetSemanticDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.collectCheckerDiagnostics(ctx, sourceFile, p.getSemanticDiagnosticsWithChecker)
}
// GetSemanticDiagnosticsForIncremental includes newly discovered globals in each
// file's cached diagnostics and leaves noEmit filtering to the builder.
func (p *Program) GetSemanticDiagnosticsForIncremental(ctx context.Context, sourceFiles []*ast.SourceFile) map[*ast.SourceFile][]*ast.Diagnostic {
allDiags := p.collectCheckerDiagnosticsFromFiles(ctx, sourceFiles, func(ctx context.Context, c *checker.Checker, file *ast.SourceFile) []*ast.Diagnostic {
return p.getBindAndCheckDiagnosticsWithChecker(ctx, c, file, true /*includeDeferredGlobals*/)
})
result := make(map[*ast.SourceFile][]*ast.Diagnostic, len(sourceFiles))
for i, diags := range allDiags {
result[sourceFiles[i]] = filterAndSortDiagnostics(diags)
}
return result
}
func (p *Program) GetSuggestionDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.collectCheckerDiagnostics(ctx, sourceFile, p.getSuggestionDiagnosticsWithChecker)
}
func (p *Program) GetProgramDiagnostics() []*ast.Diagnostic {
return SortAndDeduplicateDiagnostics(slices.Concat(
p.programDiagnostics,
p.contentMapperDiagnostics,
p.contentMapperOptionDiagnostics,
p.includeProcessor.getDiagnostics(p).GetGlobalDiagnostics(),
))
}
func (p *Program) collectContentMapperOptionDiagnostics() {
project := p.ContentMapperProject()
if project == nil {
return
}
optionDiagnostics := project.Diagnostics()
p.contentMapperOptionDiagnostics = core.Map(optionDiagnostics, func(diagnostic contentmapper.OptionDiagnostic) *ast.Diagnostic {
file, loc := tsoptions.GetContentMapperOptionDiagnosticLocation(p.opts.Config, diagnostic.Mapper, diagnostic.Path)
return ast.NewExternalDiagnostic(file, loc, diagnostic.Source, diagnostics.CategoryError, diagnostic.Code, diagnostic.MessageText)
})
}
func (p *Program) GetIncludeProcessorDiagnostics(sourceFile *ast.SourceFile) []*ast.Diagnostic {
if p.SkipTypeChecking(sourceFile, false) {
return nil
}
filtered, _ := p.getDiagnosticsWithPrecedingDirectives(sourceFile, p.includeProcessor.getDiagnostics(p).GetDiagnosticsForFile(sourceFile))
return filtered
}
func (p *Program) SkipTypeChecking(sourceFile *ast.SourceFile, ignoreNoCheck bool) bool {
return (!ignoreNoCheck && p.Options().NoCheck.IsTrue()) ||
p.Options().SkipLibCheck.IsTrue() && sourceFile.IsDeclarationFile ||
p.Options().SkipDefaultLibCheck.IsTrue() && p.IsSourceFileDefaultLibrary(sourceFile.Path()) ||
p.IsSourceFromProjectReference(sourceFile.Path()) ||
!p.canIncludeBindAndCheckDiagnostics(sourceFile)
}
func (p *Program) canIncludeBindAndCheckDiagnostics(sourceFile *ast.SourceFile) bool {
if sourceFile.CheckJsDirective != nil && !sourceFile.CheckJsDirective.Enabled {
return false
}
if sourceFile.ScriptKind == core.ScriptKindTS || sourceFile.ScriptKind == core.ScriptKindTSX {
return true
}
isJS := sourceFile.ScriptKind == core.ScriptKindJS || sourceFile.ScriptKind == core.ScriptKindJSX
isCheckJS := isJS && ast.IsCheckJSEnabledForFile(sourceFile, p.Options())
isPlainJS := ast.IsPlainJSFile(sourceFile, p.Options().CheckJs)
// By default, only type-check .ts, .tsx, plain JS, and checked JS
// - plain JS: .js files with no // ts-check and checkJs: undefined
// - check JS: .js files with either // ts-check or checkJs: true
return isPlainJS || isCheckJS
}
func (p *Program) getSourceFilesToEmit(targetSourceFiles []*ast.SourceFile, forceDtsEmit bool, forceJsEmit bool) []*ast.SourceFile {
if targetSourceFiles == nil && !forceDtsEmit && !forceJsEmit {
p.sourceFilesToEmitOnce.Do(func() {
p.sourceFilesToEmit = getSourceFilesToEmit(p, nil, false, false)
})
return p.sourceFilesToEmit
}
return getSourceFilesToEmit(p, targetSourceFiles, forceDtsEmit, forceJsEmit)
}
func (p *Program) verifyCompilerOptions() {
options := p.Options()
sourceFile := core.Memoize(func() *ast.SourceFile {
configFile := p.opts.Config.ConfigFile
if configFile == nil {
return nil
}
return configFile.SourceFile
})
configFilePath := core.Memoize(func() string {
file := sourceFile()
if file != nil {
return file.FileName()
}
return ""
})
getCompilerOptionsPropertySyntax := core.Memoize(func() *ast.PropertyAssignment {
return tsoptions.ForEachTsConfigPropArray(sourceFile(), "compilerOptions", core.Identity)
})
getCompilerOptionsObjectLiteralSyntax := core.Memoize(func() *ast.ObjectLiteralExpression {
compilerOptionsProperty := getCompilerOptionsPropertySyntax()
if compilerOptionsProperty != nil &&
compilerOptionsProperty.Initializer != nil &&
ast.IsObjectLiteralExpression(compilerOptionsProperty.Initializer) {
return compilerOptionsProperty.Initializer.AsObjectLiteralExpression()
}
return nil
})
createOptionDiagnosticInObjectLiteralSyntax := func(objectLiteral *ast.ObjectLiteralExpression, onKey bool, key1 string, key2 string, message *diagnostics.Message, args ...any) *ast.Diagnostic {
diag := tsoptions.ForEachPropertyAssignment(objectLiteral, key1, func(property *ast.PropertyAssignment) *ast.Diagnostic {
return tsoptions.CreateDiagnosticForNodeInSourceFile(sourceFile(), core.IfElse(onKey, property.Name(), property.Initializer), message, args...)
}, key2)
if diag != nil {
p.programDiagnostics = append(p.programDiagnostics, diag)
}
return diag
}
createCompilerOptionsDiagnostic := func(message *diagnostics.Message, args ...any) *ast.Diagnostic {
compilerOptionsProperty := getCompilerOptionsPropertySyntax()
var diag *ast.Diagnostic
if compilerOptionsProperty != nil {
diag = tsoptions.CreateDiagnosticForNodeInSourceFile(sourceFile(), compilerOptionsProperty.Name(), message, args...)
} else {
diag = ast.NewCompilerDiagnostic(message, args...)
}
p.programDiagnostics = append(p.programDiagnostics, diag)
return diag
}
createDiagnosticForOption := func(onKey bool, option1 string, option2 string, message *diagnostics.Message, args ...any) *ast.Diagnostic {
diag := createOptionDiagnosticInObjectLiteralSyntax(getCompilerOptionsObjectLiteralSyntax(), onKey, option1, option2, message, args...)
if diag == nil {
diag = createCompilerOptionsDiagnostic(message, args...)
}
return diag
}
createDiagnosticForOptionName := func(message *diagnostics.Message, option1 string, option2 string, args ...any) {
newArgs := make([]any, 0, len(args)+2)
newArgs = append(newArgs, option1, option2)
newArgs = append(newArgs, args...)
createDiagnosticForOption(true /*onKey*/, option1, option2, message, newArgs...)
}
createOptionValueDiagnostic := func(option1 string, message *diagnostics.Message, args ...any) {
createDiagnosticForOption(false /*onKey*/, option1, "", message, args...)
}
createRemovedOptionDiagnostic := func(name string, value string, useInstead string) {
var message *diagnostics.Message
var args []any
if value == "" {
message = diagnostics.Option_0_has_been_removed_Please_remove_it_from_your_configuration
args = []any{name}
} else {
message = diagnostics.Option_0_1_has_been_removed_Please_remove_it_from_your_configuration
args = []any{name, value}
}
diag := createDiagnosticForOption(value == "", name, "", message, args...)
if useInstead != "" {
diag.AddMessageChain(ast.NewCompilerDiagnostic(diagnostics.Use_0_instead, useInstead))
}
}
// Removed in TS7
if options.BaseUrl != "" {
// BaseUrl will have been turned absolute by this point.
var useInstead string
if configFilePath() != "" {
relative := tspath.GetRelativePathFromFile(configFilePath(), options.BaseUrl, p.comparePathsOptions)
if !(strings.HasPrefix(relative, "./") || strings.HasPrefix(relative, "../")) {
relative = "./" + relative
}