Skip to content

Commit d981162

Browse files
authored
refactor tsconfigsourcefile to use ast.SourceFile, and use *ParsedCommandLine where possible (microsoft#257)
1 parent 875a2d2 commit d981162

File tree

3 files changed

+40
-36
lines changed

3 files changed

+40
-36
lines changed

internal/tsoptions/commandlineparser.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ func convertJsonOptionOfEnumType(
325325
opt *CommandLineOption,
326326
value string,
327327
valueExpression *ast.Expression,
328-
sourceFile *TsConfigSourceFile,
328+
sourceFile *ast.SourceFile,
329329
) (any, []*ast.Diagnostic) {
330330
if value == "" {
331331
return nil, nil
@@ -339,9 +339,5 @@ func convertJsonOptionOfEnumType(
339339
if ok {
340340
return validateJsonOptionValue(opt, val, valueExpression, sourceFile)
341341
}
342-
// todo: clean up use of `TsConfigSourceFile`
343-
if sourceFile == nil {
344-
return nil, []*ast.Diagnostic{createDiagnosticForInvalidEnumType(opt, nil, nil)}
345-
}
346-
return nil, []*ast.Diagnostic{createDiagnosticForInvalidEnumType(opt, sourceFile.SourceFile, valueExpression)}
342+
return nil, []*ast.Diagnostic{createDiagnosticForInvalidEnumType(opt, sourceFile, valueExpression)}
347343
}

internal/tsoptions/tsconfigparsing.go

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ type parsedTsconfig struct {
117117
}
118118

119119
func parseOwnConfigOfJsonSourceFile(
120-
sourceFile *TsConfigSourceFile,
120+
sourceFile *ast.SourceFile,
121121
host ParseConfigHost,
122122
basePath string,
123123
configFileName string,
@@ -165,7 +165,7 @@ func parseOwnConfigOfJsonSourceFile(
165165
propertySetErrors = append(propertySetErrors, err...)
166166
} else if option == nil {
167167
if keyText == "excludes" {
168-
propertySetErrors = append(propertySetErrors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile.SourceFile, propertyAssignment.Name(), diagnostics.Unknown_option_excludes_Did_you_mean_exclude))
168+
propertySetErrors = append(propertySetErrors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment.Name(), diagnostics.Unknown_option_excludes_Did_you_mean_exclude))
169169
}
170170
if core.Find(optionsDeclarations, func(option *CommandLineOption) bool { return option.Name == keyText }) != nil {
171171
rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.Name())
@@ -176,7 +176,7 @@ func parseOwnConfigOfJsonSourceFile(
176176
}
177177

178178
json, err := convertConfigFileToObject(
179-
sourceFile.SourceFile,
179+
sourceFile,
180180
&jsonConversionNotifier{
181181
tsconfigRootOptionsMap,
182182
onPropertySet,
@@ -200,6 +200,14 @@ type TsConfigSourceFile struct {
200200
configFileSpecs *configFileSpecs
201201
SourceFile *ast.SourceFile
202202
}
203+
204+
func tsconfigToSourceFile(tsconfigSourceFile *TsConfigSourceFile) *ast.SourceFile {
205+
if tsconfigSourceFile == nil {
206+
return nil
207+
}
208+
return tsconfigSourceFile.SourceFile
209+
}
210+
203211
type jsonConversionNotifier struct {
204212
rootOptions *CommandLineOption
205213
onPropertySet func(keyText string, value any, propertyAssignment *ast.PropertyAssignment, parentOption *CommandLineOption, option *CommandLineOption) (any, []*ast.Diagnostic)
@@ -272,7 +280,7 @@ func validateJsonOptionValue(
272280
opt *CommandLineOption,
273281
val any,
274282
valueExpression *ast.Expression,
275-
sourceFile *TsConfigSourceFile,
283+
sourceFile *ast.SourceFile,
276284
) (any, []*ast.Diagnostic) {
277285
if val == nil || val == "" {
278286
return nil, nil
@@ -284,7 +292,7 @@ func validateJsonOptionValue(
284292
if result == nil {
285293
return val, nil
286294
}
287-
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile.SourceFile, valueExpression, err))
295+
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, err))
288296
} else {
289297
return val, nil
290298
}
@@ -297,7 +305,7 @@ func convertJsonOptionOfListType(
297305
basePath string,
298306
propertyAssignment *ast.PropertyAssignment,
299307
valueExpression *ast.Node,
300-
sourceFile *TsConfigSourceFile,
308+
sourceFile *ast.SourceFile,
301309
) ([]any, []*ast.Diagnostic) {
302310
var expression *ast.Node
303311
var errors []*ast.Diagnostic
@@ -350,7 +358,7 @@ func convertJsonOption(
350358
basePath string,
351359
propertyAssignment *ast.PropertyAssignment,
352360
valueExpression *ast.Expression,
353-
sourceFile *TsConfigSourceFile,
361+
sourceFile *ast.SourceFile,
354362
) (any, []*ast.Diagnostic) {
355363
var errors []*ast.Diagnostic
356364
if opt.isCommandLineOnly {
@@ -361,7 +369,7 @@ func convertJsonOption(
361369
if sourceFile == nil && nodeValue == nil {
362370
errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.Option_0_can_only_be_specified_on_command_line, opt.Name))
363371
} else {
364-
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile.SourceFile, nodeValue, diagnostics.Option_0_can_only_be_specified_on_command_line, opt.Name))
372+
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnostics.Option_0_can_only_be_specified_on_command_line, opt.Name))
365373
}
366374
return nil, errors
367375
}
@@ -390,7 +398,7 @@ func convertJsonOption(
390398
return normalizeNonListOptionValue(opt, basePath, validatedValue), errors
391399
}
392400
} else {
393-
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile.SourceFile, valueExpression, diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.Name, getCompilerOptionValueTypeString(opt)))
401+
errors = append(errors, createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.Name, getCompilerOptionValueTypeString(opt)))
394402
return nil, errors
395403
}
396404
}
@@ -402,7 +410,7 @@ func getExtendsConfigPathOrArray(
402410
configFileName string,
403411
propertyAssignment *ast.PropertyAssignment,
404412
valueExpression *ast.Expression,
405-
sourceFile *TsConfigSourceFile,
413+
sourceFile *ast.SourceFile,
406414
) ([]string, []*ast.Diagnostic) {
407415
var extendedConfigPathArray []string
408416
newBase := basePath
@@ -446,13 +454,13 @@ func getExtendsConfigPath(
446454
host ParseConfigHost,
447455
basePath string,
448456
valueExpression *ast.Expression,
449-
sourceFile *TsConfigSourceFile,
457+
sourceFile *ast.SourceFile,
450458
) (string, []*ast.Diagnostic) {
451459
extendedConfig = tspath.NormalizeSlashes(extendedConfig)
452460
var errors []*ast.Diagnostic
453461
var errorFile *ast.SourceFile
454462
if sourceFile != nil {
455-
errorFile = sourceFile.SourceFile
463+
errorFile = sourceFile
456464
}
457465
if tspath.IsRootedDiskPath(extendedConfig) || strings.HasPrefix(extendedConfig, "./") || strings.HasPrefix(extendedConfig, "../") {
458466
extendedConfigPath := tspath.GetNormalizedAbsolutePath(extendedConfig, basePath)
@@ -579,7 +587,7 @@ type resolverHost struct {
579587

580588
func (r *resolverHost) Trace(msg string) {}
581589

582-
func ParseJsonSourceFileConfigFileContent(sourceFile *TsConfigSourceFile, host ParseConfigHost, basePath string, existingOptions *core.CompilerOptions, configFileName string, resolutionStack []tspath.Path, extraFileExtensions []fileExtensionInfo, extendedConfigCache map[string]*extendedConfigCacheEntry) ParsedCommandLine {
590+
func ParseJsonSourceFileConfigFileContent(sourceFile *TsConfigSourceFile, host ParseConfigHost, basePath string, existingOptions *core.CompilerOptions, configFileName string, resolutionStack []tspath.Path, extraFileExtensions []fileExtensionInfo, extendedConfigCache map[string]*extendedConfigCacheEntry) *ParsedCommandLine {
583591
// tracing?.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName });
584592
result := parseJsonConfigFileContentWorker(nil /*json*/, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache)
585593
// tracing?.pop();
@@ -719,7 +727,7 @@ func convertPropertyValueToJson(sourceFile *ast.SourceFile, valueExpression *ast
719727
// jsonNode: The contents of the config file to parse
720728
// host: Instance of ParseConfigHost used to enumerate files in folder.
721729
// basePath: A root directory to resolve relative path entries in the config file to. e.g. outDir
722-
func ParseJsonConfigFileContent(json any, host ParseConfigHost, basePath string, existingOptions *core.CompilerOptions, configFileName string, resolutionStack []tspath.Path, extraFileExtensions []fileExtensionInfo, extendedConfigCache map[string]*extendedConfigCacheEntry) ParsedCommandLine {
730+
func ParseJsonConfigFileContent(json any, host ParseConfigHost, basePath string, existingOptions *core.CompilerOptions, configFileName string, resolutionStack []tspath.Path, extraFileExtensions []fileExtensionInfo, extendedConfigCache map[string]*extendedConfigCacheEntry) *ParsedCommandLine {
723731
result := parseJsonConfigFileContentWorker(parseJsonToStringKey(json), nil /*sourceFile*/, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache)
724732
return result
725733
}
@@ -883,7 +891,7 @@ func parseConfig(
883891
if json != nil {
884892
ownConfig, err = parseOwnConfigOfJson(json, host, basePath, configFileName)
885893
} else {
886-
ownConfig, err = parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName)
894+
ownConfig, err = parseOwnConfigOfJsonSourceFile(tsconfigToSourceFile(sourceFile), host, basePath, configFileName)
887895
}
888896
errors = append(errors, err...)
889897
if ownConfig.options != nil && ownConfig.options.Paths != nil {
@@ -1004,7 +1012,7 @@ func parseJsonConfigFileContentWorker(
10041012
resolutionStack []tspath.Path,
10051013
extraFileExtensions []fileExtensionInfo,
10061014
extendedConfigCache map[string]*extendedConfigCacheEntry,
1007-
) ParsedCommandLine {
1015+
) *ParsedCommandLine {
10081016
// Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
10091017
var errors []*ast.Diagnostic
10101018
resolutionStackString := []string{}
@@ -1060,7 +1068,7 @@ func parseJsonConfigFileContentWorker(
10601068
fileName = "tsconfig.json"
10611069
}
10621070
diagnosticMessage := diagnostics.The_files_list_in_config_file_0_is_empty
1063-
nodeValue := forEachTsConfigPropArray(sourceFile, "files", func(property *ast.PropertyAssignment) *ast.Node { return property.Initializer })
1071+
nodeValue := forEachTsConfigPropArray(sourceFile.SourceFile, "files", func(property *ast.PropertyAssignment) *ast.Node { return property.Initializer })
10641072
errors = append(errors, ast.NewDiagnostic(sourceFile.SourceFile, core.NewTextRange(scanner.SkipTrivia(sourceFile.SourceFile.Text, nodeValue.Pos()), nodeValue.End()), diagnosticMessage, fileName))
10651073
} else {
10661074
errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.The_files_list_in_config_file_0_is_empty, configFileName))
@@ -1099,7 +1107,7 @@ func parseJsonConfigFileContentWorker(
10991107
// file system.
11001108
if includeSpecs.sliceValue != nil {
11011109
var err []*ast.Diagnostic
1102-
validatedIncludeSpecsBeforeSubstitution, err = validateSpecs(includeSpecs.sliceValue, true /*disallowTrailingRecursion*/, sourceFile, "include")
1110+
validatedIncludeSpecsBeforeSubstitution, err = validateSpecs(includeSpecs.sliceValue, true /*disallowTrailingRecursion*/, tsconfigToSourceFile(sourceFile), "include")
11031111
errors = append(errors, err...)
11041112
validatedIncludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate(
11051113
validatedIncludeSpecsBeforeSubstitution,
@@ -1111,7 +1119,7 @@ func parseJsonConfigFileContentWorker(
11111119
}
11121120
if excludeSpecs.sliceValue != nil {
11131121
var err []*ast.Diagnostic
1114-
validatedExcludeSpecsBeforeSubstitution, err = validateSpecs(excludeSpecs.sliceValue, false /*disallowTrailingRecursion*/, sourceFile, "exclude")
1122+
validatedExcludeSpecsBeforeSubstitution, err = validateSpecs(excludeSpecs.sliceValue, false /*disallowTrailingRecursion*/, tsconfigToSourceFile(sourceFile), "exclude")
11151123
errors = append(errors, err...)
11161124
validatedExcludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate(
11171125
validatedExcludeSpecsBeforeSubstitution,
@@ -1193,7 +1201,7 @@ func parseJsonConfigFileContentWorker(
11931201
return projectReferences
11941202
}
11951203

1196-
return ParsedCommandLine{
1204+
return &ParsedCommandLine{
11971205
ParsedConfig: &core.ParsedOptions{
11981206
CompilerOptions: parsedConfig.options,
11991207
FileNames: getFileNames(basePathForFileNames),
@@ -1214,10 +1222,10 @@ func shouldReportNoInputFiles(fileNames []string, canJsonReportNoInutFiles bool,
12141222
return len(fileNames) == 0 && canJsonReportNoInutFiles && len(resolutionStack) == 0
12151223
}
12161224

1217-
func validateSpecs(specs any, disallowTrailingRecursion bool, jsonSourceFile *TsConfigSourceFile, specKey string) ([]string, []*ast.Diagnostic) {
1225+
func validateSpecs(specs any, disallowTrailingRecursion bool, jsonSourceFile *ast.SourceFile, specKey string) ([]string, []*ast.Diagnostic) {
12181226
createDiagnostic := func(message *diagnostics.Message, spec string) *ast.Diagnostic {
12191227
element := getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec)
1220-
return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(jsonSourceFile.SourceFile, element.AsNode(), message, spec)
1228+
return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(jsonSourceFile, element.AsNode(), message, spec)
12211229
}
12221230
var errors []*ast.Diagnostic
12231231
var finalSpecs []string
@@ -1282,7 +1290,7 @@ func invalidDotDotAfterRecursiveWildcard(s string) bool {
12821290
// \/?$ # matches an optional trailing directory separator at the end of the string.
12831291
const invalidTrailingRecursionPattern = `(?:^|\/)\*\*\/?$`
12841292

1285-
func getTsConfigPropArrayElementValue(tsConfigSourceFile *TsConfigSourceFile, propKey string, elementValue string) *ast.StringLiteral {
1293+
func getTsConfigPropArrayElementValue(tsConfigSourceFile *ast.SourceFile, propKey string, elementValue string) *ast.StringLiteral {
12861294
return forEachTsConfigPropArray(tsConfigSourceFile, propKey, func(property *ast.PropertyAssignment) *ast.StringLiteral {
12871295
if ast.IsArrayLiteralExpression(property.Initializer) {
12881296
value := core.Find(property.Initializer.AsArrayLiteralExpression().Elements.Nodes, func(element *ast.Node) bool {
@@ -1296,7 +1304,7 @@ func getTsConfigPropArrayElementValue(tsConfigSourceFile *TsConfigSourceFile, pr
12961304
})
12971305
}
12981306

1299-
func forEachTsConfigPropArray[T any](tsConfigSourceFile *TsConfigSourceFile, propKey string, callback func(property *ast.PropertyAssignment) *T) *T {
1307+
func forEachTsConfigPropArray[T any](tsConfigSourceFile *ast.SourceFile, propKey string, callback func(property *ast.PropertyAssignment) *T) *T {
13001308
if tsConfigSourceFile != nil {
13011309
return forEachPropertyAssignment(getTsConfigObjectLiteralExpression(tsConfigSourceFile), propKey, callback)
13021310
}
@@ -1319,9 +1327,9 @@ func forEachPropertyAssignment[T any](objectLiteral *ast.ObjectLiteralExpression
13191327
return *new(T)
13201328
}
13211329

1322-
func getTsConfigObjectLiteralExpression(tsConfigSourceFile *TsConfigSourceFile) *ast.ObjectLiteralExpression {
1323-
if tsConfigSourceFile != nil && tsConfigSourceFile.SourceFile.Statements != nil && len(tsConfigSourceFile.SourceFile.Statements.Nodes) > 0 {
1324-
expression := tsConfigSourceFile.SourceFile.Statements.Nodes[0].AsExpressionStatement().Expression
1330+
func getTsConfigObjectLiteralExpression(tsConfigSourceFile *ast.SourceFile) *ast.ObjectLiteralExpression {
1331+
if tsConfigSourceFile != nil && tsConfigSourceFile.Statements != nil && len(tsConfigSourceFile.Statements.Nodes) > 0 {
1332+
expression := tsConfigSourceFile.Statements.Nodes[0].AsExpressionStatement().Expression
13251333
return expression.AsObjectLiteralExpression()
13261334
}
13271335
return nil

internal/tsoptions/tsconfigparsing_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ func TestParseJsonConfigFileContent(t *testing.T) {
499499
for _, rec := range parseJsonConfigFileTests {
500500
t.Run(rec.title+" with json api", func(t *testing.T) {
501501
t.Parallel()
502-
baselineParseConfigWith(t, rec.title+" with json api.js", rec.noSubmoduleBaseline, rec.input, func(config testConfig, host ParseConfigHost, basePath string) ParsedCommandLine {
502+
baselineParseConfigWith(t, rec.title+" with json api.js", rec.noSubmoduleBaseline, rec.input, func(config testConfig, host ParseConfigHost, basePath string) *ParsedCommandLine {
503503
parsed, _ := ParseConfigFileTextToJson(config.configFileName, config.basePath, config.jsonText)
504504
return ParseJsonConfigFileContent(
505505
parsed,
@@ -522,7 +522,7 @@ func TestParseJsonSourceFileConfigFileContent(t *testing.T) {
522522
for _, rec := range parseJsonConfigFileTests {
523523
t.Run(rec.title+" with jsonSourceFile api", func(t *testing.T) {
524524
t.Parallel()
525-
baselineParseConfigWith(t, rec.title+" with jsonSourceFile api.js", rec.noSubmoduleBaseline, rec.input, func(config testConfig, host ParseConfigHost, basePath string) ParsedCommandLine {
525+
baselineParseConfigWith(t, rec.title+" with jsonSourceFile api.js", rec.noSubmoduleBaseline, rec.input, func(config testConfig, host ParseConfigHost, basePath string) *ParsedCommandLine {
526526
parsed := parser.ParseJSONText(config.configFileName, config.jsonText)
527527
tsConfigSourceFile := &TsConfigSourceFile{
528528
SourceFile: parsed,
@@ -542,7 +542,7 @@ func TestParseJsonSourceFileConfigFileContent(t *testing.T) {
542542
}
543543
}
544544

545-
func baselineParseConfigWith(t *testing.T, baselineFileName string, noSubmoduleBaseline bool, input []testConfig, getParsed func(config testConfig, host ParseConfigHost, basePath string) ParsedCommandLine) {
545+
func baselineParseConfigWith(t *testing.T, baselineFileName string, noSubmoduleBaseline bool, input []testConfig, getParsed func(config testConfig, host ParseConfigHost, basePath string) *ParsedCommandLine) {
546546
var baselineContent strings.Builder
547547
for i, config := range input {
548548
basePath := config.basePath

0 commit comments

Comments
 (0)