-
Notifications
You must be signed in to change notification settings - Fork 578
/
Copy pathtsconfigparsing.go
1556 lines (1465 loc) · 62.1 KB
/
tsconfigparsing.go
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 tsoptions
import (
"fmt"
"reflect"
"regexp"
"slices"
"strings"
"github.com/dlclark/regexp2"
"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/collections"
"github.com/microsoft/typescript-go/internal/compiler/diagnostics"
"github.com/microsoft/typescript-go/internal/compiler/module"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/jsnum"
"github.com/microsoft/typescript-go/internal/parser"
"github.com/microsoft/typescript-go/internal/scanner"
"github.com/microsoft/typescript-go/internal/tspath"
"github.com/microsoft/typescript-go/internal/vfs"
)
type extendsResult struct {
options *core.CompilerOptions
// watchOptions compiler.WatchOptions
watchOptionsCopied bool
include []any
exclude []any
files []any
compileOnSave bool
extendedSourceFiles core.Set[string]
}
var compilerOptionsDeclaration = &CommandLineOption{
Name: "compilerOptions",
Kind: CommandLineOptionTypeObject,
ElementOptions: commandLineCompilerOptionsMap,
}
var compileOnSaveCommandLineOption = &CommandLineOption{
Name: "compileOnSave",
Kind: CommandLineOptionTypeBoolean,
DefaultValueDescription: false,
}
var extendsOptionDeclaration = &CommandLineOption{
Name: "extends",
Kind: CommandLineOptionTypeListOrElement,
Category: diagnostics.File_Management,
ElementOptions: map[string]*CommandLineOption{
"extends": {Name: "extends", Kind: CommandLineOptionTypeString},
},
}
var tsconfigRootOptionsMap = &CommandLineOption{
Name: "undefined", // should never be needed since this is root
Kind: CommandLineOptionTypeObject,
ElementOptions: commandLineOptionsToMap([]*CommandLineOption{
compilerOptionsDeclaration,
extendsOptionDeclaration,
{
Name: "references",
Kind: CommandLineOptionTypeList, // should be a list of projectReference
// Category: diagnostics.Projects,
},
{
Name: "files",
Kind: CommandLineOptionTypeList,
// Category: diagnostics.File_Management,
},
{
Name: "include",
Kind: CommandLineOptionTypeList,
// Category: diagnostics.File_Management,
// DefaultValueDescription: diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk,
},
{
Name: "exclude",
Kind: CommandLineOptionTypeList,
// Category: diagnostics.File_Management,
// DefaultValueDescription: diagnostics.Node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified,
},
compileOnSaveCommandLineOption,
}),
}
type configFileSpecs struct {
filesSpecs any
// Present to report errors (user specified specs), validatedIncludeSpecs are used for file name matching
includeSpecs any
// Present to report errors (user specified specs), validatedExcludeSpecs are used for file name matching
excludeSpecs any
validatedFilesSpec []string
validatedIncludeSpecs []string
validatedExcludeSpecs []string
isDefaultIncludeSpec bool
}
type fileExtensionInfo struct {
extension string
isMixedContent bool
scriptKind core.ScriptKind
}
type ExtendedConfigCacheEntry struct {
extendedResult *TsConfigSourceFile
extendedConfig *parsedTsconfig
}
type parsedTsconfig struct {
raw any
options *core.CompilerOptions
// watchOptions *compiler.WatchOptions
// typeAcquisition *compiler.TypeAcquisition
// Note that the case of the config path has not yet been normalized, as no files have been imported into the project yet
extendedConfigPath any
}
func parseOwnConfigOfJsonSourceFile(
sourceFile *ast.SourceFile,
host ParseConfigHost,
basePath string,
configFileName string,
) (*parsedTsconfig, []*ast.Diagnostic) {
options := getDefaultCompilerOptions(configFileName)
// var typeAcquisition *compiler.TypeAcquisition
// var watchOptions *compiler.WatchOptions
var extendedConfigPath any
var rootCompilerOptions []*ast.PropertyName
var errors []*ast.Diagnostic
onPropertySet := func(
keyText string,
value any,
propertyAssignment *ast.PropertyAssignment,
parentOption *CommandLineOption, // TsConfigOnlyOption,
option *CommandLineOption,
) (any, []*ast.Diagnostic) {
// Ensure value is verified except for extends which is handled in its own way for error reporting
var propertySetErrors []*ast.Diagnostic
if option != nil && option != extendsOptionDeclaration {
value, propertySetErrors = convertJsonOption(option, value, basePath, propertyAssignment, propertyAssignment.Initializer, sourceFile)
}
if parentOption != nil && parentOption.Name != "undefined" && value != nil {
if option != nil && option.Name != "" {
propertySetErrors = append(propertySetErrors, ParseCompilerOptions(option.Name, value, options)...)
} else if keyText != "" {
if parentOption.ElementOptions != nil {
// !!! TODO: support suggestion
propertySetErrors = append(propertySetErrors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment.Name(), diagnostics.Unknown_compiler_option_0, keyText))
} else {
// errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.Unknown_compiler_option_0_Did_you_mean_1, keyText, core.FindKey(parentOption.ElementOptions, keyText)))
}
}
} else if parentOption == tsconfigRootOptionsMap {
if option == extendsOptionDeclaration {
configPath, err := getExtendsConfigPathOrArray(value, host, basePath, configFileName, propertyAssignment, propertyAssignment.Initializer, sourceFile)
extendedConfigPath = configPath
propertySetErrors = append(propertySetErrors, err...)
} else if option == nil {
if keyText == "excludes" {
propertySetErrors = append(propertySetErrors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment.Name(), diagnostics.Unknown_option_excludes_Did_you_mean_exclude))
}
if core.Find(OptionsDeclarations, func(option *CommandLineOption) bool { return option.Name == keyText }) != nil {
rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.Name())
}
}
}
return value, propertySetErrors
}
json, err := convertConfigFileToObject(
sourceFile,
&jsonConversionNotifier{
tsconfigRootOptionsMap,
onPropertySet,
},
)
errors = append(errors, err...)
// if len(rootCompilerOptions) != 0 && json != nil && json.CompilerOptions != nil {
// errors = append(errors, ast.NewDiagnostic(sourceFile, rootCompilerOptions[0], diagnostics.X_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file))
// }
return &parsedTsconfig{
raw: json,
options: options,
// watchOptions: watchOptions,
// typeAcquisition: typeAcquisition,
extendedConfigPath: extendedConfigPath,
}, errors
}
type TsConfigSourceFile struct {
extendedSourceFiles []string
configFileSpecs *configFileSpecs
SourceFile *ast.SourceFile
}
func tsconfigToSourceFile(tsconfigSourceFile *TsConfigSourceFile) *ast.SourceFile {
if tsconfigSourceFile == nil {
return nil
}
return tsconfigSourceFile.SourceFile
}
func NewTsconfigSourceFileFromFilePath(configFileName string, configPath tspath.Path, configSourceText string) *TsConfigSourceFile {
sourceFile := parser.ParseJSONText(configFileName, configPath, configSourceText)
return &TsConfigSourceFile{
SourceFile: sourceFile,
}
}
type jsonConversionNotifier struct {
rootOptions *CommandLineOption
onPropertySet func(keyText string, value any, propertyAssignment *ast.PropertyAssignment, parentOption *CommandLineOption, option *CommandLineOption) (any, []*ast.Diagnostic)
}
func convertConfigFileToObject(
sourceFile *ast.SourceFile,
jsonConversionNotifier *jsonConversionNotifier,
) (any, []*ast.Diagnostic) {
var rootExpression *ast.Expression
if len(sourceFile.Statements.Nodes) > 0 {
rootExpression = sourceFile.Statements.Nodes[0].AsExpressionStatement().Expression
}
if rootExpression != nil && rootExpression.Kind != ast.KindObjectLiteralExpression {
baseFileName := "tsconfig.json"
if tspath.GetBaseFileName(sourceFile.FileName()) == "jsconfig.json" {
baseFileName = "jsconfig.json"
}
errors := []*ast.Diagnostic{ast.NewCompilerDiagnostic(diagnostics.The_root_value_of_a_0_file_must_be_an_object, baseFileName)}
// Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by
// synthesizing a top-level array literal expression. There's a reasonable chance the first element of that
// array is a well-formed configuration object, made into an array element by stray characters.
if ast.IsArrayLiteralExpression(rootExpression) {
firstObject := core.Find(rootExpression.AsArrayLiteralExpression().Elements.Nodes, ast.IsObjectLiteralExpression)
if firstObject != nil {
return convertToJson(sourceFile, firstObject, true /*returnValue*/, jsonConversionNotifier)
}
}
return &collections.OrderedMap[string, any]{}, errors
}
return convertToJson(sourceFile, rootExpression, true, jsonConversionNotifier)
}
var orderedMapType = reflect.TypeFor[*collections.OrderedMap[string, any]]()
func isCompilerOptionsValue(option *CommandLineOption, value any) bool {
if option != nil {
if value == nil {
return !option.DisallowNullOrUndefined()
}
if option.Kind == "list" {
return reflect.TypeOf(value).Kind() == reflect.Slice
}
if option.Kind == "listOrElement" {
if reflect.TypeOf(value).Kind() == reflect.Slice {
return true
} else {
return isCompilerOptionsValue(option.Elements(), value)
}
}
if option.Kind == "string" {
return reflect.TypeOf(value).Kind() == reflect.String
}
if option.Kind == "boolean" {
return reflect.TypeOf(value).Kind() == reflect.Bool
}
if option.Kind == "number" {
return reflect.TypeOf(value).Kind() == reflect.Float64
}
if option.Kind == "object" {
return reflect.TypeOf(value) == orderedMapType
}
if option.Kind == "enum" && reflect.TypeOf(value).Kind() == reflect.String {
return true
}
}
return false
}
func validateJsonOptionValue(
opt *CommandLineOption,
val any,
valueExpression *ast.Expression,
sourceFile *ast.SourceFile,
) (any, []*ast.Diagnostic) {
if val == nil {
return nil, nil
}
errors := []*ast.Diagnostic{}
if opt.extraValidation {
diag := specToDiagnostic(val.(string), false)
if diag != nil {
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, diag))
return nil, errors
}
}
return val, nil
}
func convertJsonOptionOfListType(
option *CommandLineOption,
values any,
basePath string,
propertyAssignment *ast.PropertyAssignment,
valueExpression *ast.Node,
sourceFile *ast.SourceFile,
) ([]any, []*ast.Diagnostic) {
var expression *ast.Node
var errors []*ast.Diagnostic
if values, ok := values.([]any); ok {
mappedValues := core.MapIndex(values, func(v any, index int) any {
if valueExpression != nil {
expression = valueExpression.AsArrayLiteralExpression().Elements.Nodes[index]
}
result, err := convertJsonOption(option.Elements(), v, basePath, propertyAssignment, expression, sourceFile)
errors = append(errors, err...)
return result
})
filteredValues := mappedValues
if !option.listPreserveFalsyValues {
filteredValues = core.Filter(mappedValues, func(v any) bool {
return (v != nil && v != false && v != 0 && v != "")
})
}
return filteredValues, errors
}
return nil, errors
}
const configDirTemplate = "${configDir}"
func startsWithConfigDirTemplate(value any) bool {
str, ok := value.(string)
if !ok {
return false
}
return strings.HasPrefix(strings.ToLower(str), strings.ToLower(configDirTemplate))
}
func normalizeNonListOptionValue(option *CommandLineOption, basePath string, value any) any {
if option.isFilePath {
value = tspath.NormalizeSlashes(value.(string))
if !startsWithConfigDirTemplate(value) {
value = tspath.GetNormalizedAbsolutePath(value.(string), basePath)
}
if value == "" {
value = "."
}
}
return value
}
func convertJsonOption(
opt *CommandLineOption,
value any,
basePath string,
propertyAssignment *ast.PropertyAssignment,
valueExpression *ast.Expression,
sourceFile *ast.SourceFile,
) (any, []*ast.Diagnostic) {
if opt.IsCommandLineOnly {
var nodeValue *ast.Node
if propertyAssignment != nil {
nodeValue = propertyAssignment.Name()
}
if sourceFile == nil && nodeValue == nil {
return nil, []*ast.Diagnostic{ast.NewCompilerDiagnostic(diagnostics.Option_0_can_only_be_specified_on_command_line, opt.Name)}
} else {
return nil, []*ast.Diagnostic{createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnostics.Option_0_can_only_be_specified_on_command_line, opt.Name)}
}
}
if isCompilerOptionsValue(opt, value) {
switch opt.Kind {
case CommandLineOptionTypeList:
return convertJsonOptionOfListType(opt, value, basePath, propertyAssignment, valueExpression, sourceFile) // as ArrayLiteralExpression | undefined
case CommandLineOptionTypeListOrElement:
if reflect.TypeOf(value).Kind() == reflect.Slice {
return convertJsonOptionOfListType(opt, value, basePath, propertyAssignment, valueExpression, sourceFile)
} else {
return convertJsonOption(opt.Elements(), value, basePath, propertyAssignment, valueExpression, sourceFile)
}
case CommandLineOptionTypeEnum:
return convertJsonOptionOfEnumType(opt, value.(string), valueExpression, sourceFile)
}
validatedValue, errors := validateJsonOptionValue(opt, value, valueExpression, sourceFile)
if len(errors) > 0 || validatedValue == nil {
return validatedValue, errors
} else {
return normalizeNonListOptionValue(opt, basePath, validatedValue), errors
}
} else {
return nil, []*ast.Diagnostic{createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.Name, getCompilerOptionValueTypeString(opt))}
}
}
func getExtendsConfigPathOrArray(
value CompilerOptionsValue,
host ParseConfigHost,
basePath string,
configFileName string,
propertyAssignment *ast.PropertyAssignment,
valueExpression *ast.Expression,
sourceFile *ast.SourceFile,
) ([]string, []*ast.Diagnostic) {
var extendedConfigPathArray []string
newBase := basePath
if configFileName != "" {
newBase = directoryOfCombinedPath(configFileName, basePath)
}
if reflect.TypeOf(value).Kind() == reflect.String {
val, err := getExtendsConfigPath(value.(string), host, newBase, valueExpression, sourceFile)
if val != "" {
extendedConfigPathArray = append(extendedConfigPathArray, val)
}
return extendedConfigPathArray, err
}
var errors []*ast.Diagnostic
if reflect.TypeOf(value).Kind() == reflect.Slice {
for index, fileName := range value.([]any) {
var expression *ast.Expression = nil
if valueExpression != nil {
expression = valueExpression.AsArrayLiteralExpression().Elements.Nodes[index]
}
if reflect.TypeOf(fileName).Kind() == reflect.String {
val, err := getExtendsConfigPath(fileName.(string), host, newBase, expression, sourceFile)
if val != "" {
extendedConfigPathArray = append(extendedConfigPathArray, val)
}
errors = append(errors, err...)
} else {
_, err := convertJsonOption(extendsOptionDeclaration.Elements(), value, basePath, propertyAssignment, expression, sourceFile)
errors = append(errors, err...)
}
}
} else {
_, errors = convertJsonOption(extendsOptionDeclaration, value, basePath, propertyAssignment, valueExpression, sourceFile)
}
return extendedConfigPathArray, errors
}
func getExtendsConfigPath(
extendedConfig string,
host ParseConfigHost,
basePath string,
valueExpression *ast.Expression,
sourceFile *ast.SourceFile,
) (string, []*ast.Diagnostic) {
extendedConfig = tspath.NormalizeSlashes(extendedConfig)
var errors []*ast.Diagnostic
var errorFile *ast.SourceFile
if sourceFile != nil {
errorFile = sourceFile
}
if tspath.IsRootedDiskPath(extendedConfig) || strings.HasPrefix(extendedConfig, "./") || strings.HasPrefix(extendedConfig, "../") {
extendedConfigPath := tspath.GetNormalizedAbsolutePath(extendedConfig, basePath)
if !host.FS().FileExists(extendedConfigPath) && !strings.HasSuffix(extendedConfigPath, tspath.ExtensionJson) {
extendedConfigPath = extendedConfigPath + tspath.ExtensionJson
if !host.FS().FileExists(extendedConfigPath) {
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(errorFile, valueExpression, diagnostics.File_0_not_found, extendedConfig))
return "", errors
}
}
return extendedConfigPath, errors
}
// If the path isn't a rooted or relative path, resolve like a module
resolverHost := &resolverHost{host}
if resolved := module.ResolveConfig(extendedConfig, tspath.CombinePaths(basePath, "tsconfig.json"), resolverHost); resolved.IsResolved() {
return resolved.ResolvedFileName, errors
}
if extendedConfig == "" {
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(errorFile, valueExpression, diagnostics.Compiler_option_0_cannot_be_given_an_empty_string, "extends"))
} else {
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(errorFile, valueExpression, diagnostics.File_0_not_found, extendedConfig))
}
return "", errors
}
type tsConfigOptions struct {
prop map[string][]string
references []core.ProjectReference
notDefined string
}
func commandLineOptionsToMap(options []*CommandLineOption) map[string]*CommandLineOption {
result := make(map[string]*CommandLineOption)
for i := range options {
result[(options[i]).Name] = options[i]
}
return result
}
var commandLineCompilerOptionsMap map[string]*CommandLineOption = commandLineOptionsToMap(OptionsDeclarations)
func convertMapToOptions[O optionParser](options *collections.OrderedMap[string, any], result O) O {
// this assumes any `key`, `value` pair in `options` will have `value` already be the correct type. this function should no error handling
for key, value := range options.Entries() {
result.ParseOption(key, value)
}
return result
}
func convertOptionsFromJson[O optionParser](optionsNameMap map[string]*CommandLineOption, jsonOptions any, basePath string, result O) (O, []*ast.Diagnostic) {
if jsonOptions == nil {
return result, nil
}
jsonMap, ok := jsonOptions.(*collections.OrderedMap[string, any])
if !ok {
// !!! probably should be an error
return result, nil
}
var errors []*ast.Diagnostic
for key, value := range jsonMap.Entries() {
opt, ok := optionsNameMap[key]
if !ok {
// !!! TODO?: support suggestion
errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.Unknown_compiler_option_0, key))
continue
}
commandLineOptionEnumMapVal := opt.EnumMap()
if commandLineOptionEnumMapVal != nil {
val, ok := commandLineOptionEnumMapVal.Get(strings.ToLower(value.(string)))
if ok {
errors = result.ParseOption(key, val)
}
} else {
convertJson, err := convertJsonOption(opt, value, basePath, nil, nil, nil)
errors = append(errors, err...)
compilerOptionsErr := result.ParseOption(key, convertJson)
errors = append(errors, compilerOptionsErr...)
}
}
return result, errors
}
func convertArrayLiteralExpressionToJson(
sourceFile *ast.SourceFile,
elements []*ast.Expression,
elementOption *CommandLineOption,
returnValue bool,
) (any, []*ast.Diagnostic) {
if !returnValue {
for _, element := range elements {
convertPropertyValueToJson(sourceFile, element, elementOption, returnValue, nil)
}
return nil, nil
}
// Filter out invalid values
if len(elements) == 0 {
// Always return an empty array, even if elements is nil.
// The parser will produce nil slices instead of allocating empty ones.
return []any{}, nil
}
var errors []*ast.Diagnostic
var value []any
for _, element := range elements {
convertedValue, err := convertPropertyValueToJson(sourceFile, element, elementOption, returnValue, nil)
errors = append(errors, err...)
if convertedValue != nil {
value = append(value, convertedValue)
}
}
return value, errors
}
func directoryOfCombinedPath(fileName string, basePath string) string {
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
// until consistent casing errors are reported
return tspath.GetDirectoryPath(tspath.GetNormalizedAbsolutePath(fileName, basePath))
}
// ParseConfigFileTextToJson parses the text of the tsconfig.json file
// fileName is the path to the config file
// jsonText is the text of the config file
func ParseConfigFileTextToJson(fileName string, path tspath.Path, jsonText string) (any, []*ast.Diagnostic) {
jsonSourceFile := parser.ParseJSONText(fileName, path, jsonText)
config, errors := convertConfigFileToObject(jsonSourceFile /*jsonConversionNotifier*/, nil)
if len(jsonSourceFile.Diagnostics()) > 0 {
errors = []*ast.Diagnostic{jsonSourceFile.Diagnostics()[0]}
}
return config, errors
}
type ParseConfigHost interface {
FS() vfs.FS
GetCurrentDirectory() string
}
type resolverHost struct {
ParseConfigHost
}
func (r *resolverHost) Trace(msg string) {}
func ParseJsonSourceFileConfigFileContent(sourceFile *TsConfigSourceFile, host ParseConfigHost, basePath string, existingOptions *core.CompilerOptions, configFileName string, resolutionStack []tspath.Path, extraFileExtensions []fileExtensionInfo, extendedConfigCache map[tspath.Path]*ExtendedConfigCacheEntry) *ParsedCommandLine {
// tracing?.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName });
result := parseJsonConfigFileContentWorker(nil /*json*/, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache)
// tracing?.pop();
return result
}
func convertObjectLiteralExpressionToJson(
sourceFile *ast.SourceFile,
returnValue bool,
node *ast.ObjectLiteralExpression,
objectOption *CommandLineOption,
jsonConversionNotifier *jsonConversionNotifier,
) (*collections.OrderedMap[string, any], []*ast.Diagnostic) {
var result *collections.OrderedMap[string, any]
if returnValue {
result = &collections.OrderedMap[string, any]{}
}
var errors []*ast.Diagnostic
for _, element := range node.Properties.Nodes {
if element.Kind != ast.KindPropertyAssignment {
errors = append(errors, ast.NewDiagnostic(sourceFile, element.Loc, diagnostics.Property_assignment_expected))
continue
}
// !!!
// if ast.IsQuestionToken(element) {
// errors = append(errors, ast.NewDiagnostic(sourceFile, element.Loc, diagnostics.Property_assignment_expected))
// }
if element.Name() != nil && !isDoubleQuotedString(element.Name()) {
errors = append(errors, ast.NewDiagnostic(sourceFile, element.Loc, diagnostics.String_literal_with_double_quotes_expected))
}
textOfKey := ""
if !ast.IsComputedNonLiteralName(element.Name()) {
textOfKey, _ = ast.TryGetTextOfPropertyName(element.Name())
}
keyText := textOfKey
var option *CommandLineOption = nil
if keyText != "" && objectOption != nil && objectOption.ElementOptions != nil {
option = objectOption.ElementOptions[keyText]
}
value, err := convertPropertyValueToJson(sourceFile, element.AsPropertyAssignment().Initializer, option, returnValue, jsonConversionNotifier)
errors = append(errors, err...)
if keyText != "" {
if returnValue {
result.Set(keyText, value)
}
// Notify key value set, if user asked for it
if jsonConversionNotifier != nil {
_, err := jsonConversionNotifier.onPropertySet(keyText, value, element.AsPropertyAssignment(), objectOption, option)
errors = append(errors, err...)
}
}
}
return result, errors
}
// convertToJson converts the json syntax tree into the json value and report errors
// This returns the json value (apart from checking errors) only if returnValue provided is true.
// Otherwise it just checks the errors and returns undefined
func convertToJson(
sourceFile *ast.SourceFile,
rootExpression *ast.Expression,
returnValue bool,
jsonConversionNotifier *jsonConversionNotifier,
) (any, []*ast.Diagnostic) {
if rootExpression == nil {
if returnValue {
return struct{}{}, nil
} else {
return nil, nil
}
}
var rootOptions *CommandLineOption
if jsonConversionNotifier != nil {
rootOptions = jsonConversionNotifier.rootOptions
}
return convertPropertyValueToJson(sourceFile, rootExpression, rootOptions, returnValue, jsonConversionNotifier)
}
func isDoubleQuotedString(node *ast.Node) bool {
return ast.IsStringLiteral(node)
}
func convertPropertyValueToJson(sourceFile *ast.SourceFile, valueExpression *ast.Expression, option *CommandLineOption, returnValue bool, jsonConversionNotifier *jsonConversionNotifier) (any, []*ast.Diagnostic) {
switch valueExpression.Kind {
case ast.KindTrueKeyword:
return true, nil
case ast.KindFalseKeyword:
return false, nil
case ast.KindNullKeyword: // todo: how to manage null
return nil, nil
case ast.KindStringLiteral:
if !isDoubleQuotedString(valueExpression) {
return valueExpression.AsStringLiteral().Text, []*ast.Diagnostic{ast.NewDiagnostic(sourceFile, valueExpression.Loc, diagnostics.String_literal_with_double_quotes_expected)}
}
return valueExpression.AsStringLiteral().Text, nil
case ast.KindNumericLiteral:
return float64(jsnum.FromString(valueExpression.AsNumericLiteral().Text)), nil
case ast.KindPrefixUnaryExpression:
if valueExpression.AsPrefixUnaryExpression().Operator != ast.KindMinusToken || valueExpression.AsPrefixUnaryExpression().Operand.Kind != ast.KindNumericLiteral {
break // not valid JSON syntax
}
return float64(-jsnum.FromString(valueExpression.AsPrefixUnaryExpression().Operand.AsNumericLiteral().Text)), nil
case ast.KindObjectLiteralExpression:
objectLiteralExpression := valueExpression.AsObjectLiteralExpression()
// Currently having element option declaration in the tsconfig with type "object"
// determines if it needs onSetValidOptionKeyValueInParent callback or not
// At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
// that satisfies it and need it to modify options set in them (for normalizing file paths)
// vs what we set in the json
// If need arises, we can modify this interface and callbacks as needed
return convertObjectLiteralExpressionToJson(sourceFile, returnValue, objectLiteralExpression, option, jsonConversionNotifier)
case ast.KindArrayLiteralExpression:
result, errors := convertArrayLiteralExpressionToJson(
sourceFile,
valueExpression.AsArrayLiteralExpression().Elements.Nodes,
option,
returnValue,
)
return result, errors
}
// Not in expected format
var errors []*ast.Diagnostic
if option != nil {
errors = []*ast.Diagnostic{ast.NewDiagnostic(sourceFile, valueExpression.Loc, diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.Name, getCompilerOptionValueTypeString(option))}
} else {
errors = []*ast.Diagnostic{ast.NewDiagnostic(sourceFile, valueExpression.Loc, diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)}
}
return nil, errors
}
// ParseJsonConfigFileContent parses the contents of a config file (tsconfig.json).
// jsonNode: The contents of the config file to parse
// host: Instance of ParseConfigHost used to enumerate files in folder.
// basePath: A root directory to resolve relative path entries in the config file to. e.g. outDir
func ParseJsonConfigFileContent(json any, host ParseConfigHost, basePath string, existingOptions *core.CompilerOptions, configFileName string, resolutionStack []tspath.Path, extraFileExtensions []fileExtensionInfo, extendedConfigCache map[tspath.Path]*ExtendedConfigCacheEntry) *ParsedCommandLine {
result := parseJsonConfigFileContentWorker(parseJsonToStringKey(json), nil /*sourceFile*/, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache)
return result
}
// convertToObject converts the json syntax tree into the json value
func convertToObject(sourceFile *ast.SourceFile) (any, []*ast.Diagnostic) {
var rootExpression *ast.Expression
if len(sourceFile.Statements.Nodes) != 0 {
rootExpression = sourceFile.Statements.Nodes[0].AsExpressionStatement().Expression
}
return convertToJson(sourceFile, rootExpression, true /*returnValue*/, nil /*jsonConversionNotifier*/)
}
func getDefaultCompilerOptions(configFileName string) *core.CompilerOptions {
options := &core.CompilerOptions{}
if configFileName != "" && tspath.GetBaseFileName(configFileName) == "jsconfig.json" {
depth := 2
options = &core.CompilerOptions{
AllowJs: core.TSTrue,
MaxNodeModuleJsDepth: &depth,
AllowSyntheticDefaultImports: core.TSTrue,
SkipLibCheck: core.TSTrue,
NoEmit: core.TSTrue,
}
}
return options
}
func convertCompilerOptionsFromJsonWorker(jsonOptions any, basePath string, configFileName string) (*core.CompilerOptions, []*ast.Diagnostic) {
options := getDefaultCompilerOptions(configFileName)
_, errors := convertOptionsFromJson(commandLineCompilerOptionsMap, jsonOptions, basePath, &compilerOptionsParser{options})
if configFileName != "" {
options.ConfigFilePath = tspath.NormalizeSlashes(configFileName)
}
return options, errors
}
func parseOwnConfigOfJson(
json *collections.OrderedMap[string, any],
host ParseConfigHost,
basePath string,
configFileName string,
) (*parsedTsconfig, []*ast.Diagnostic) {
var errors []*ast.Diagnostic
if json.Has("excludes") {
errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.Unknown_option_excludes_Did_you_mean_exclude))
}
options, err := convertCompilerOptionsFromJsonWorker(json.GetOrZero("compilerOptions"), basePath, configFileName)
errors = append(errors, err...)
// typeAcquisition := convertTypeAcquisitionFromJsonWorker(json.typeAcquisition, basePath, errors, configFileName)
// watchOptions := convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors)
// json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors)
var extendedConfigPath []string
if extends := json.GetOrZero("extends"); extends != nil && extends != "" {
extendedConfigPath, err = getExtendsConfigPathOrArray(extends, host, basePath, configFileName, nil, nil, nil)
errors = append(errors, err...)
}
parsedConfig := &parsedTsconfig{
raw: json,
options: options,
extendedConfigPath: extendedConfigPath,
}
return parsedConfig, errors
}
func readJsonConfigFile(fileName string, path tspath.Path, readFile func(fileName string) (string, bool)) (*TsConfigSourceFile, []*ast.Diagnostic) {
text, diagnostic := TryReadFile(fileName, readFile, []*ast.Diagnostic{})
if text != "" {
return &TsConfigSourceFile{
SourceFile: parser.ParseJSONText(fileName, path, text),
}, diagnostic
} else {
file := &TsConfigSourceFile{
SourceFile: (&ast.NodeFactory{}).NewSourceFile("", fileName, path, nil).AsSourceFile(),
}
file.SourceFile.SetDiagnostics(diagnostic)
return file, diagnostic
}
}
func getExtendedConfig(
sourceFile *TsConfigSourceFile,
extendedConfigPath string,
host ParseConfigHost,
resolutionStack []string,
extendedConfigCache map[tspath.Path]*ExtendedConfigCacheEntry,
result *extendsResult,
) (*parsedTsconfig, []*ast.Diagnostic) {
path := tspath.ToPath(extendedConfigPath, host.GetCurrentDirectory(), host.FS().UseCaseSensitiveFileNames())
var extendedResult *TsConfigSourceFile
var extendedConfig *parsedTsconfig
var errors []*ast.Diagnostic
value := extendedConfigCache[path]
if extendedConfigCache != nil && value != nil {
extendedResult = value.extendedResult
extendedConfig = value.extendedConfig
} else {
var err []*ast.Diagnostic
extendedResult, err = readJsonConfigFile(extendedConfigPath, path, host.FS().ReadFile)
errors = append(errors, err...)
if len(extendedResult.SourceFile.Diagnostics()) == 0 {
extendedConfig, err = parseConfig(nil, extendedResult, host, tspath.GetDirectoryPath(extendedConfigPath), tspath.GetBaseFileName(extendedConfigPath), resolutionStack, extendedConfigCache)
errors = append(errors, err...)
}
if extendedConfigCache != nil {
extendedConfigCache[path] = &ExtendedConfigCacheEntry{
extendedResult: extendedResult,
extendedConfig: extendedConfig,
}
}
}
if sourceFile != nil {
result.extendedSourceFiles.Add(extendedResult.SourceFile.FileName())
if len(extendedResult.extendedSourceFiles) != 0 {
for _, extenedSourceFile := range extendedResult.extendedSourceFiles {
result.extendedSourceFiles.Add(extenedSourceFile)
}
}
}
if len(extendedResult.SourceFile.Diagnostics()) != 0 {
errors = append(errors, extendedResult.SourceFile.Diagnostics()...)
return nil, errors
}
return extendedConfig, errors
}
// parseConfig just extracts options/include/exclude/files out of a config file.
// It does not resolve the included files.
func parseConfig(
json *collections.OrderedMap[string, any],
sourceFile *TsConfigSourceFile,
host ParseConfigHost,
basePath string,
configFileName string,
resolutionStack []string,
extendedConfigCache map[tspath.Path]*ExtendedConfigCacheEntry,
) (*parsedTsconfig, []*ast.Diagnostic) {
basePath = tspath.NormalizeSlashes(basePath)
resolvedPath := tspath.GetNormalizedAbsolutePath(configFileName, basePath)
var errors []*ast.Diagnostic
if slices.Contains(resolutionStack, resolvedPath) {
var result *parsedTsconfig
errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.Circularity_detected_while_resolving_configuration_Colon_0))
if json.Size() == 0 {
result = &parsedTsconfig{raw: json}
} else {
rawResult, err := convertToObject(sourceFile.SourceFile)
errors = append(errors, err...)
result = &parsedTsconfig{raw: rawResult}
}
return result, errors
}
var ownConfig *parsedTsconfig
var err []*ast.Diagnostic
if json != nil {
ownConfig, err = parseOwnConfigOfJson(json, host, basePath, configFileName)
} else {
ownConfig, err = parseOwnConfigOfJsonSourceFile(tsconfigToSourceFile(sourceFile), host, basePath, configFileName)
}
errors = append(errors, err...)
if ownConfig.options != nil && ownConfig.options.Paths != nil {
// If we end up needing to resolve relative paths from 'paths' relative to
// the config file location, we'll need to know where that config file was.
// Since 'paths' can be inherited from an extended config in another directory,
// we wouldn't know which directory to use unless we store it here.
ownConfig.options.PathsBasePath = basePath
}
applyExtendedConfig := func(result *extendsResult, extendedConfigPath string) {
extendedConfig, extendedErrors := getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, extendedConfigCache, result)
errors = append(errors, extendedErrors...)
if extendedConfig != nil && extendedConfig.options != nil {
extendsRaw := extendedConfig.raw
relativeDifference := ""
setPropertyValue := func(propertyName string) {
if rawMap, ok := ownConfig.raw.(*collections.OrderedMap[string, any]); ok && rawMap.Has(propertyName) {
return
}
if propertyName == "include" || propertyName == "exclude" || propertyName == "files" {
if rawMap, ok := extendsRaw.(*collections.OrderedMap[string, any]); ok && rawMap.Has(propertyName) {
if slice, _ := rawMap.GetOrZero(propertyName).([]any); slice != nil {
value := core.Map(slice, func(path any) any {
if startsWithConfigDirTemplate(path) || tspath.IsRootedDiskPath(path.(string)) {
return path.(string)
} else {
if relativeDifference == "" {
t := tspath.ComparePathsOptions{
UseCaseSensitiveFileNames: host.FS().UseCaseSensitiveFileNames(),
CurrentDirectory: host.GetCurrentDirectory(),
}
relativeDifference = tspath.ConvertToRelativePath(basePath, t)
}
return tspath.CombinePaths(relativeDifference, path.(string))
}
})
if propertyName == "include" {
result.include = value
} else if propertyName == "exclude" {
result.exclude = value
} else if propertyName == "files" {
result.files = value
}
}
}
}
}
setPropertyValue("include")
setPropertyValue("exclude")
setPropertyValue("files")
if extendedRawMap, ok := extendsRaw.(*collections.OrderedMap[string, any]); ok && extendedRawMap.Has("compileOnSave") {
if compileOnSave, ok := extendedRawMap.GetOrZero("compileOnSave").(bool); ok {
result.compileOnSave = compileOnSave
}
}
mergeCompilerOptions(result.options, extendedConfig.options)
}
}
if ownConfig.extendedConfigPath != nil {
// copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
resolutionStack = append(resolutionStack, resolvedPath)
result := &extendsResult{
options: &core.CompilerOptions{},
}
if reflect.TypeOf(ownConfig.extendedConfigPath).Kind() == reflect.String {
applyExtendedConfig(result, ownConfig.extendedConfigPath.(string))
} else if configPath, ok := ownConfig.extendedConfigPath.([]string); ok {
for _, extendedConfigPath := range configPath {
applyExtendedConfig(result, extendedConfigPath)
}
}
if result.include != nil {
ownConfig.raw.(*collections.OrderedMap[string, any]).Set("include", result.include)
}
if result.exclude != nil {
ownConfig.raw.(*collections.OrderedMap[string, any]).Set("exclude", result.exclude)
}
if result.files != nil {
ownConfig.raw.(*collections.OrderedMap[string, any]).Set("files", result.files)
}
if result.compileOnSave && !ownConfig.raw.(*collections.OrderedMap[string, any]).Has("compileOnSave") {
ownConfig.raw.(*collections.OrderedMap[string, any]).Set("compileOnSave", result.compileOnSave)
}
if sourceFile != nil {
for extendedSourceFile := range result.extendedSourceFiles.Keys() {
sourceFile.extendedSourceFiles = append(sourceFile.extendedSourceFiles, extendedSourceFile)
}
}
ownConfig.options = mergeCompilerOptions(result.options, ownConfig.options)
// ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ?
// assignWatchOptions(result, ownConfig.watchOptions) :
// ownConfig.watchOptions || result.watchOptions;
}
return ownConfig, errors
}
const defaultIncludeSpec = "**/*"
type propOfRaw struct {
sliceValue []any
wrongValue string
}
// parseJsonConfigFileContentWorker parses the contents of a config file from json or json source file (tsconfig.json).
// json: The contents of the config file to parse
// sourceFile: sourceFile corresponding to the Json