forked from microsoft/typescript-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.go
More file actions
1730 lines (1510 loc) · 69.4 KB
/
program.go
File metadata and controls
1730 lines (1510 loc) · 69.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
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"
"github.com/go-json-experiment/json"
"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/binder"
"github.com/microsoft/typescript-go/internal/checker"
"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/modulespecifiers"
"github.com/microsoft/typescript-go/internal/outputpaths"
"github.com/microsoft/typescript-go/internal/parser"
"github.com/microsoft/typescript-go/internal/printer"
"github.com/microsoft/typescript-go/internal/scanner"
"github.com/microsoft/typescript-go/internal/sourcemap"
"github.com/microsoft/typescript-go/internal/tsoptions"
"github.com/microsoft/typescript-go/internal/tspath"
)
type ProgramOptions struct {
Host CompilerHost
Config *tsoptions.ParsedCommandLine
UseSourceOfProjectReference bool
SingleThreaded core.Tristate
CreateCheckerPool func(*Program) CheckerPool
TypingsLocation string
ProjectName string
JSDocParsingMode ast.JSDocParsingMode
}
func (p *ProgramOptions) canUseProjectReferenceSource() bool {
return p.UseSourceOfProjectReference && !p.Config.CompilerOptions().DisableSourceOfProjectReferenceRedirect.IsTrue()
}
type Program struct {
opts ProgramOptions
checkerPool 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]
sourceFilesToEmitOnce sync.Once
sourceFilesToEmit []*ast.SourceFile
// Cached unresolved imports for ATA
unresolvedImportsOnce sync.Once
unresolvedImports *collections.Set[string]
}
// 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()
}
// GetGlobalTypingsCacheLocation implements checker.Program.
func (p *Program) GetGlobalTypingsCacheLocation() string {
return "" // !!! see src/tsserver/nodeServer.ts for strada's node-specific implementation
}
// 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) modulespecifiers.PackageJsonInfo {
scoped := p.resolver.GetPackageScopeForPath(pkgJsonPath)
if scoped != nil && scoped.Exists() && scoped.PackageDirectory == tspath.GetDirectoryPath(pkgJsonPath) {
return scoped
}
return nil
}
// GetRedirectTargets implements checker.Program.
func (p *Program) GetRedirectTargets(path tspath.Path) []string {
return nil // !!! TODO: project references support
}
// 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) ForEachResolvedProjectReference(
fn func(path tspath.Path, config *tsoptions.ParsedCommandLine, parent *tsoptions.ParsedCommandLine, index int),
) {
p.projectReferenceFileMapper.forEachResolvedProjectReference(fn)
}
// UseCaseSensitiveFileNames implements checker.Program.
func (p *Program) UseCaseSensitiveFileNames() bool {
return p.Host().FS().UseCaseSensitiveFileNames()
}
func (p *Program) UsesUriStyleNodeCoreModules() bool {
return p.usesUriStyleNodeCoreModules.IsTrue()
}
func (p *Program) IsNodeSourceFile(path tspath.Path) bool {
return p.Host().IsNodeSourceFile(path)
}
func (p *Program) GetDenoForkContextInfo() ast.DenoForkContextInfo {
return p.Host().GetDenoForkContextInfo()
}
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(), nil /*extraFileExtensions*/)
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.GetSourceFile(fileName)
}
if allowNonTsExtensions {
extensionless := p.GetSourceFile(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.GetSourceFile(fileName + ext)
if result != nil {
return result
}
}
return nil
}
func NewProgram(opts ProgramOptions) *Program {
p := &Program{opts: opts}
p.initCheckerPool()
p.processedFiles = processAllProgramFiles(p.opts, p.SingleThreaded())
p.verifyCompilerOptions()
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.
func (p *Program) UpdateProgram(changedFilePath tspath.Path, newHost CompilerHost) (*Program, bool) {
oldFile := p.filesByPath[changedFilePath]
newOpts := p.opts
newOpts.Host = newHost
newFile := newHost.GetSourceFile(oldFile.ParseOptions())
if !canReplaceFileInProgram(oldFile, newFile) {
return NewProgram(newOpts), 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,
unresolvedImports: p.unresolvedImports,
}
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
updateFileIncludeProcessor(result)
return result, true
}
func (p *Program) initCheckerPool() {
if p.opts.CreateCheckerPool != nil {
p.checkerPool = p.opts.CreateCheckerPool(p)
} else {
p.checkerPool = newCheckerPool(core.IfElse(p.SingleThreaded(), 1, 4), p)
}
}
func canReplaceFileInProgram(file1 *ast.SourceFile, file2 *ast.SourceFile) bool {
return file2 != nil &&
file1.ParseOptions() == file2.ParseOptions() &&
file1.UsesUriStyleNodeCoreModules == file2.UsesUriStyleNodeCoreModules &&
slices.EqualFunc(file1.Imports(), file2.Imports(), equalModuleSpecifiers) &&
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 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) Options() *core.CompilerOptions { return p.opts.Config.CompilerOptions() }
func (p *Program) CommandLine() *tsoptions.ParsedCommandLine { return p.opts.Config }
func (p *Program) Host() CompilerHost { return p.opts.Host }
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] {
p.unresolvedImportsOnce.Do(func() {
if p.unresolvedImports == nil {
p.unresolvedImports = p.extractUnresolvedImports()
}
})
return p.unresolvedImports
}
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() {
binder.BindSourceFile(file)
})
}
}
wg.RunAndWait()
}
func (p *Program) CheckSourceFiles(ctx context.Context, files []*ast.SourceFile) {
wg := core.NewWorkGroup(p.SingleThreaded())
checkers, done := p.checkerPool.GetAllCheckers(ctx)
defer done()
for _, checker := range checkers {
wg.Queue(func() {
for file := range p.checkerPool.Files(checker) {
if files == nil || slices.Contains(files, file) {
checker.CheckSourceFile(ctx, file)
}
}
})
}
wg.RunAndWait()
}
// Return the type checker associated with the program.
func (p *Program) GetTypeChecker(ctx context.Context) (*checker.Checker, func()) {
return p.checkerPool.GetChecker(ctx)
}
func (p *Program) GetTypeCheckers(ctx context.Context) ([]*checker.Checker, func()) {
return p.checkerPool.GetAllCheckers(ctx)
}
// 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()) {
return p.checkerPool.GetCheckerForFile(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) GetSyntacticDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.getDiagnosticsHelper(ctx, sourceFile, false /*ensureBound*/, false /*ensureChecked*/, p.getSyntacticDiagnosticsForFile)
}
func (p *Program) GetBindDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.getDiagnosticsHelper(ctx, sourceFile, true /*ensureBound*/, false /*ensureChecked*/, p.getBindDiagnosticsForFile)
}
func (p *Program) GetSemanticDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.getDiagnosticsHelper(ctx, sourceFile, true /*ensureBound*/, true /*ensureChecked*/, p.getSemanticDiagnosticsForFile)
}
func (p *Program) GetSemanticDiagnosticsNoFilter(ctx context.Context, sourceFiles []*ast.SourceFile) map[*ast.SourceFile][]*ast.Diagnostic {
p.BindSourceFiles()
p.CheckSourceFiles(ctx, sourceFiles)
if ctx.Err() != nil {
return nil
}
result := make(map[*ast.SourceFile][]*ast.Diagnostic, len(sourceFiles))
for _, file := range sourceFiles {
result[file] = SortAndDeduplicateDiagnostics(p.getSemanticDiagnosticsForFileNotFilter(ctx, file))
}
return result
}
func (p *Program) GetSuggestionDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.getDiagnosticsHelper(ctx, sourceFile, true /*ensureBound*/, true /*ensureChecked*/, p.getSuggestionDiagnosticsForFile)
}
func (p *Program) GetProgramDiagnostics() []*ast.Diagnostic {
return SortAndDeduplicateDiagnostics(slices.Concat(
p.programDiagnostics,
p.includeProcessor.getDiagnostics(p).GetGlobalDiagnostics()))
}
func (p *Program) GetIncludeProcessorDiagnostics(sourceFile *ast.SourceFile) []*ast.Diagnostic {
if checker.SkipTypeChecking(sourceFile, p.Options(), p, false) {
return nil
}
filtered, _ := p.getDiagnosticsWithPrecedingDirectives(sourceFile, p.includeProcessor.getDiagnostics(p).GetDiagnosticsForFile(sourceFile.FileName()))
return filtered
}
func (p *Program) getSourceFilesToEmit(targetSourceFile *ast.SourceFile, forceDtsEmit bool) []*ast.SourceFile {
if targetSourceFile == nil && !forceDtsEmit {
p.sourceFilesToEmitOnce.Do(func() {
p.sourceFilesToEmit = getSourceFilesToEmit(p, nil, false)
})
return p.sourceFilesToEmit
}
return getSourceFilesToEmit(p, targetSourceFile, forceDtsEmit)
}
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
}
suggestion := tspath.CombinePaths(relative, "*")
useInstead = fmt.Sprintf(`"paths": {"*": [%s]}`, core.Must(json.Marshal(suggestion)))
}
createRemovedOptionDiagnostic("baseUrl", "", useInstead)
}
if options.OutFile != "" {
createRemovedOptionDiagnostic("outFile", "", "")
}
// if options.Target == core.ScriptTargetES3 {
// createRemovedOptionDiagnostic("target", "ES3", "")
// }
// if options.Target == core.ScriptTargetES5 {
// createRemovedOptionDiagnostic("target", "ES5", "")
// }
if options.Module == core.ModuleKindAMD {
createRemovedOptionDiagnostic("module", "AMD", "")
}
if options.Module == core.ModuleKindSystem {
createRemovedOptionDiagnostic("module", "System", "")
}
if options.Module == core.ModuleKindUMD {
createRemovedOptionDiagnostic("module", "UMD", "")
}
if options.StrictPropertyInitialization.IsTrue() && !options.GetStrictOptionValue(options.StrictNullChecks) {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks")
}
if options.ExactOptionalPropertyTypes.IsTrue() && !options.GetStrictOptionValue(options.StrictNullChecks) {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "exactOptionalPropertyTypes", "strictNullChecks")
}
if options.IsolatedDeclarations.IsTrue() {
if options.GetAllowJS() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "isolatedDeclarations")
}
if !options.GetEmitDeclarations() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "isolatedDeclarations", "declaration", "composite")
}
}
if options.InlineSourceMap.IsTrue() {
if options.SourceMap.IsTrue() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")
}
if options.MapRoot != "" {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")
}
}
if options.Composite.IsTrue() {
if options.Declaration.IsFalse() {
createDiagnosticForOptionName(diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration", "")
}
if options.Incremental.IsFalse() {
createDiagnosticForOptionName(diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration", "")
}
}
p.verifyProjectReferences()
if options.Composite.IsTrue() {
var rootPaths collections.Set[tspath.Path]
for _, fileName := range p.opts.Config.FileNames() {
rootPaths.Add(p.toPath(fileName))
}
for _, file := range p.files {
if sourceFileMayBeEmitted(file, p, false) && !rootPaths.Has(file.Path()) {
p.includeProcessor.addProcessingDiagnostic(&processingDiagnostic{
kind: processingDiagnosticKindExplainingFileInclude,
data: &includeExplainingDiagnostic{
file: file.Path(),
message: diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern,
args: []any{file.FileName(), configFilePath()},
},
})
}
}
}
forEachOptionPathsSyntax := func(callback func(*ast.PropertyAssignment) *ast.Diagnostic) *ast.Diagnostic {
return tsoptions.ForEachPropertyAssignment(getCompilerOptionsObjectLiteralSyntax(), "paths", callback)
}
createDiagnosticForOptionPaths := func(onKey bool, key string, message *diagnostics.Message, args ...any) *ast.Diagnostic {
diag := forEachOptionPathsSyntax(func(pathProp *ast.PropertyAssignment) *ast.Diagnostic {
if ast.IsObjectLiteralExpression(pathProp.Initializer) {
return createOptionDiagnosticInObjectLiteralSyntax(pathProp.Initializer.AsObjectLiteralExpression(), onKey, key, "", message, args...)
}
return nil
})
if diag == nil {
diag = createCompilerOptionsDiagnostic(message, args...)
}
return diag
}
createDiagnosticForOptionPathKeyValue := func(key string, valueIndex int, message *diagnostics.Message, args ...any) *ast.Diagnostic {
diag := forEachOptionPathsSyntax(func(pathProp *ast.PropertyAssignment) *ast.Diagnostic {
if ast.IsObjectLiteralExpression(pathProp.Initializer) {
return tsoptions.ForEachPropertyAssignment(pathProp.Initializer.AsObjectLiteralExpression(), key, func(keyProps *ast.PropertyAssignment) *ast.Diagnostic {
initializer := keyProps.Initializer
if ast.IsArrayLiteralExpression(initializer) {
elements := initializer.AsArrayLiteralExpression().Elements
if elements != nil && len(elements.Nodes) > valueIndex {
diag := tsoptions.CreateDiagnosticForNodeInSourceFile(sourceFile(), elements.Nodes[valueIndex], message, args...)
p.programDiagnostics = append(p.programDiagnostics, diag)
return diag
}
}
return nil
})
}
return nil
})
if diag == nil {
diag = createCompilerOptionsDiagnostic(message, args...)
}
return diag
}
for key, value := range options.Paths.Entries() {
// !!! This code does not handle cases where where the path mappings have the wrong types,
// as that information is mostly lost during the parsing process.
if !hasZeroOrOneAsteriskCharacter(key) {
createDiagnosticForOptionPaths(true /*onKey*/, key, diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)
}
if value == nil {
createDiagnosticForOptionPaths(false /*onKey*/, key, diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)
} else if len(value) == 0 {
createDiagnosticForOptionPaths(false /*onKey*/, key, diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)
}
for i, subst := range value {
if !hasZeroOrOneAsteriskCharacter(subst) {
createDiagnosticForOptionPathKeyValue(key, i, diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key)
}
if !tspath.PathIsRelative(subst) && !tspath.PathIsAbsolute(subst) {
createDiagnosticForOptionPathKeyValue(key, i, diagnostics.Non_relative_paths_are_not_allowed_Did_you_forget_a_leading_Slash)
}
}
}
if options.SourceMap.IsFalseOrUnknown() && options.InlineSourceMap.IsFalseOrUnknown() {
if options.InlineSources.IsTrue() {
createDiagnosticForOptionName(diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources", "")
}
if options.SourceRoot != "" {
createDiagnosticForOptionName(diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot", "")
}
}
if options.MapRoot != "" && !(options.SourceMap.IsTrue() || options.DeclarationMap.IsTrue()) {
// Error to specify --mapRoot without --sourcemap
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap")
}
if options.DeclarationDir != "" {
if !options.GetEmitDeclarations() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite")
}
}
if options.DeclarationMap.IsTrue() && !options.GetEmitDeclarations() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite")
}
if options.Lib != nil && options.NoLib.IsTrue() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")
}
languageVersion := options.GetEmitScriptTarget()
firstNonAmbientExternalModuleSourceFile := core.Find(p.files, func(f *ast.SourceFile) bool { return ast.IsExternalModule(f) && !f.IsDeclarationFile })
if options.IsolatedModules.IsTrue() || options.VerbatimModuleSyntax.IsTrue() {
if options.Module == core.ModuleKindNone && languageVersion < core.ScriptTargetES2015 && options.IsolatedModules.IsTrue() {
// !!!
// createDiagnosticForOptionName(diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target")
}
if options.PreserveConstEnums.IsFalse() {
createDiagnosticForOptionName(diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled, core.IfElse(options.VerbatimModuleSyntax.IsTrue(), "verbatimModuleSyntax", "isolatedModules"), "preserveConstEnums")
}
} else if firstNonAmbientExternalModuleSourceFile != nil && languageVersion < core.ScriptTargetES2015 && options.Module == core.ModuleKindNone {
// !!!
}
if options.OutDir != "" ||
options.RootDir != "" ||
options.SourceRoot != "" ||
options.MapRoot != "" ||
(options.GetEmitDeclarations() && options.DeclarationDir != "") {
// !!! sheetal checkSourceFilesBelongToPath - for root Dir and configFile - explaining why file is in the program
dir := p.CommonSourceDirectory()
if options.OutDir != "" && dir == "" && core.Some(p.files, func(f *ast.SourceFile) bool { return tspath.GetRootLength(f.FileName()) > 1 }) {
createDiagnosticForOptionName(diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir", "")
}
}
if options.CheckJs.IsTrue() && !options.GetAllowJS() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")
}
if options.EmitDeclarationOnly.IsTrue() {
if !options.GetEmitDeclarations() {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite")
}
}
// !!! emitDecoratorMetadata
if options.JsxFactory != "" {
if options.ReactNamespace != "" {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")
}
if options.Jsx == core.JsxEmitReactJSX || options.Jsx == core.JsxEmitReactJSXDev {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFactory", tsoptions.InverseJsxOptionMap.GetOrZero(options.Jsx))
}
if parser.ParseIsolatedEntityName(options.JsxFactory) == nil {
createOptionValueDiagnostic("jsxFactory", diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.JsxFactory)
}
} else if options.ReactNamespace != "" && !scanner.IsIdentifierText(options.ReactNamespace, core.LanguageVariantStandard) {
createOptionValueDiagnostic("reactNamespace", diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.ReactNamespace)
}
if options.JsxFragmentFactory != "" {
if options.JsxFactory == "" {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory")
}
if options.Jsx == core.JsxEmitReactJSX || options.Jsx == core.JsxEmitReactJSXDev {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFragmentFactory", tsoptions.InverseJsxOptionMap.GetOrZero(options.Jsx))
}
if parser.ParseIsolatedEntityName(options.JsxFragmentFactory) == nil {
createOptionValueDiagnostic("jsxFragmentFactory", diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.JsxFragmentFactory)
}
}
if options.ReactNamespace != "" {
if options.Jsx == core.JsxEmitReactJSX || options.Jsx == core.JsxEmitReactJSXDev {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "reactNamespace", tsoptions.InverseJsxOptionMap.GetOrZero(options.Jsx))
}
}
if options.JsxImportSource != "" {
if options.Jsx == core.JsxEmitReact {
createDiagnosticForOptionName(diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxImportSource", tsoptions.InverseJsxOptionMap.GetOrZero(options.Jsx))
}
}
moduleKind := options.GetEmitModuleKind()
if options.AllowImportingTsExtensions.IsTrue() && !(options.NoEmit.IsTrue() || options.EmitDeclarationOnly.IsTrue() || options.RewriteRelativeImportExtensions.IsTrue()) {
createOptionValueDiagnostic("allowImportingTsExtensions", diagnostics.Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set)
}
moduleResolution := options.GetModuleResolutionKind()
if options.ResolvePackageJsonExports.IsTrue() && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution) {
createDiagnosticForOptionName(diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonExports", "")
}
if options.ResolvePackageJsonImports.IsTrue() && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution) {
createDiagnosticForOptionName(diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonImports", "")
}
if options.CustomConditions != nil && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution) {
createDiagnosticForOptionName(diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "customConditions", "")
}
// !!! Reenable once we don't map old moduleResolution kinds to bundler.
// if moduleResolution == core.ModuleResolutionKindBundler && !emitModuleKindIsNonNodeESM(moduleKind) && moduleKind != core.ModuleKindPreserve {
// createOptionValueDiagnostic("moduleResolution", diagnostics.Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later, "bundler")
// }
if core.ModuleKindNode16 <= moduleKind && moduleKind <= core.ModuleKindNodeNext &&
!(core.ModuleResolutionKindNode16 <= moduleResolution && moduleResolution <= core.ModuleResolutionKindNodeNext) {
moduleKindName := moduleKind.String()
var moduleResolutionName string
if v, ok := core.ModuleKindToModuleResolutionKind[moduleKind]; ok {
moduleResolutionName = v.String()
} else {
moduleResolutionName = "Node16"
}
createOptionValueDiagnostic("moduleResolution", diagnostics.Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1, moduleResolutionName, moduleKindName)
} else if core.ModuleResolutionKindNode16 <= moduleResolution && moduleResolution <= core.ModuleResolutionKindNodeNext &&
!(core.ModuleKindNode16 <= moduleKind && moduleKind <= core.ModuleKindNodeNext) {
moduleResolutionName := moduleResolution.String()
createOptionValueDiagnostic("module", diagnostics.Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1, moduleResolutionName, moduleResolutionName)
}
// !!! The below needs filesByName, which is not equivalent to p.filesByPath.
// If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
if !options.NoEmit.IsTrue() && !options.SuppressOutputPathCheck.IsTrue() {
var emitFilesSeen collections.Set[string]
// Verify that all the emit files are unique and don't overwrite input files
verifyEmitFilePath := func(emitFileName string) {
if emitFileName != "" {
emitFilePath := p.toPath(emitFileName)
// Report error if the output overwrites input file
if _, ok := p.filesByPath[emitFilePath]; ok {
diag := ast.NewCompilerDiagnostic(diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName)
if configFilePath() == "" {
// The program is from either an inferred project or an external project
diag.AddMessageChain(ast.NewCompilerDiagnostic(diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig))
}
p.blockEmittingOfFile(emitFileName, diag)
}
var emitFileKey string
if !p.Host().FS().UseCaseSensitiveFileNames() {
emitFileKey = tspath.ToFileNameLowerCase(string(emitFilePath))
} else {
emitFileKey = string(emitFilePath)
}
// Report error if multiple files write into same file
if emitFilesSeen.Has(emitFileKey) {
// Already seen the same emit file - report error
p.blockEmittingOfFile(emitFileName, ast.NewCompilerDiagnostic(diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName))
} else {
emitFilesSeen.Add(emitFileKey)
}
}
}
outputpaths.ForEachEmittedFile(p, options, func(emitFileNames *outputpaths.OutputPaths, sourceFile *ast.SourceFile) bool {
verifyEmitFilePath(emitFileNames.JsFilePath())
verifyEmitFilePath(emitFileNames.SourceMapFilePath())
verifyEmitFilePath(emitFileNames.DeclarationFilePath())
verifyEmitFilePath(emitFileNames.DeclarationMapPath())
return false
}, p.getSourceFilesToEmit(nil, false), false)
verifyEmitFilePath(p.opts.Config.GetBuildInfoFileName())
}
}
func (p *Program) blockEmittingOfFile(emitFileName string, diag *ast.Diagnostic) {
p.hasEmitBlockingDiagnostics.Add(p.toPath(emitFileName))
p.programDiagnostics = append(p.programDiagnostics, diag)
}
func (p *Program) IsEmitBlocked(emitFileName string) bool {
return p.hasEmitBlockingDiagnostics.Has(p.toPath(emitFileName))
}
func (p *Program) verifyProjectReferences() {
buildInfoFileName := core.IfElse(!p.Options().SuppressOutputPathCheck.IsTrue(), p.opts.Config.GetBuildInfoFileName(), "")
createDiagnosticForReference := func(config *tsoptions.ParsedCommandLine, index int, message *diagnostics.Message, args ...any) {
diag := tsoptions.CreateDiagnosticAtReferenceSyntax(config, index, message, args...)
if diag == nil {
diag = ast.NewCompilerDiagnostic(message, args...)
}
p.programDiagnostics = append(p.programDiagnostics, diag)
}
p.ForEachResolvedProjectReference(func(path tspath.Path, config *tsoptions.ParsedCommandLine, parent *tsoptions.ParsedCommandLine, index int) {
ref := parent.ProjectReferences()[index]
// !!! Deprecated in 5.0 and removed since 5.5
// verifyRemovedProjectReference(ref, parent, index);
if config == nil {
createDiagnosticForReference(parent, index, diagnostics.File_0_not_found, ref.Path)
return
}
refOptions := config.CompilerOptions()
if !refOptions.Composite.IsTrue() || refOptions.NoEmit.IsTrue() {
if len(parent.FileNames()) > 0 {
if !refOptions.Composite.IsTrue() {
createDiagnosticForReference(parent, index, diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.Path)
}
if refOptions.NoEmit.IsTrue() {
createDiagnosticForReference(parent, index, diagnostics.Referenced_project_0_may_not_disable_emit, ref.Path)
}
}
}
if buildInfoFileName != "" && buildInfoFileName == config.GetBuildInfoFileName() {
createDiagnosticForReference(parent, index, diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoFileName, ref.Path)
p.hasEmitBlockingDiagnostics.Add(p.toPath(buildInfoFileName))
}
})
}
func hasZeroOrOneAsteriskCharacter(str string) bool {
seenAsterisk := false
for _, ch := range str {
if ch == '*' {
if !seenAsterisk {
seenAsterisk = true
} else {
// have already seen asterisk
return false
}
}
}
return true
}
func moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution core.ModuleResolutionKind) bool {
return moduleResolution >= core.ModuleResolutionKindNode16 && moduleResolution <= core.ModuleResolutionKindNodeNext ||
moduleResolution == core.ModuleResolutionKindBundler
}
func emitModuleKindIsNonNodeESM(moduleKind core.ModuleKind) bool {
return moduleKind >= core.ModuleKindES2015 && moduleKind <= core.ModuleKindESNext
}
func (p *Program) GetGlobalDiagnostics(ctx context.Context) []*ast.Diagnostic {
if len(p.files) == 0 {
return nil
}
var globalDiagnostics []*ast.Diagnostic
checkers, done := p.checkerPool.GetAllCheckers(ctx)
defer done()
for _, checker := range checkers {
globalDiagnostics = append(globalDiagnostics, checker.GetGlobalDiagnostics()...)
}
return SortAndDeduplicateDiagnostics(globalDiagnostics)
}
func (p *Program) GetDeclarationDiagnostics(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {
return p.getDiagnosticsHelper(ctx, sourceFile, true /*ensureBound*/, true /*ensureChecked*/, p.getDeclarationDiagnosticsForFile)
}
func (p *Program) GetOptionsDiagnostics(ctx context.Context) []*ast.Diagnostic {
return SortAndDeduplicateDiagnostics(append(p.GetGlobalDiagnostics(ctx), p.getOptionsDiagnosticsOfConfigFile()...))
}
func (p *Program) getOptionsDiagnosticsOfConfigFile() []*ast.Diagnostic {
// todo update p.configParsingDiagnostics when updateAndGetProgramDiagnostics is implemented
if p.Options() == nil || p.Options().ConfigFilePath == "" {
return nil
}
return p.GetConfigFileParsingDiagnostics() // TODO: actually call getDiagnosticsHelper on config path
}
func (p *Program) getSyntacticDiagnosticsForFile(ctx context.Context, sourceFile *ast.SourceFile) []*ast.Diagnostic {