From 1783becbe8ffcd03b79b15c60de4cb5037efdac1 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 25 Mar 2025 22:24:23 -0700 Subject: [PATCH 1/6] Enable staticcheck --- .golangci.yml | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index 373793aa33..37874ee08a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -38,6 +38,7 @@ linters: - perfsprint - predeclared - reassign + - staticcheck - testableexamples - tparallel - unconvert @@ -52,7 +53,6 @@ linters: # - gocritic # - gosec # - revive - # - staticcheck # - testifylint # - unparam # - unused @@ -62,6 +62,20 @@ linters: customlint: type: module + staticcheck: + checks: + - all + - -QF1001 + - -QF1003 + - -SA6005 + - -SA9003 + - -ST1000 + - -ST1003 + - -ST1016 + - -ST1020 + - -ST1021 + - -ST1022 + exclusions: presets: - comments From 07cfcfb8132b116dcc3daba1cff96c100c71b222 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 25 Mar 2025 22:29:14 -0700 Subject: [PATCH 2/6] Fix staticcheck issues --- internal/astnav/tokens_test.go | 10 ++--- internal/binder/binder.go | 6 +-- internal/checker/checker.go | 45 ++++++++----------- internal/checker/flow.go | 2 +- internal/checker/grammarchecks.go | 12 ++--- internal/checker/inference.go | 6 +-- internal/checker/relater.go | 6 +-- internal/compiler/packagejson/cache.go | 6 +-- internal/parser/jsdoc.go | 2 +- internal/scanner/scanner.go | 6 +-- .../testutil/tsbaseline/error_baseline.go | 2 +- internal/tsoptions/tsconfigparsing.go | 5 +-- internal/tsoptions/tsconfigparsing_test.go | 4 +- 13 files changed, 51 insertions(+), 61 deletions(-) diff --git a/internal/astnav/tokens_test.go b/internal/astnav/tokens_test.go index 76e1474ddb..0149478b9f 100644 --- a/internal/astnav/tokens_test.go +++ b/internal/astnav/tokens_test.go @@ -252,15 +252,15 @@ func writeRangeDiff(output *strings.Builder, file *ast.SourceFile, diff tokenDif output.WriteString("\n\n") } - output.WriteString(fmt.Sprintf("〚Positions: [%d, %d]〛\n", rng.Pos(), rng.End())) - output.WriteString(fmt.Sprintf("【TS: %s [%d, %d)】\n", diff.tsToken.Kind, diff.tsToken.Pos, diff.tsToken.End)) - output.WriteString(fmt.Sprintf("《Go: %s [%d, %d)》\n", diff.goToken.Kind, diff.goToken.Pos, diff.goToken.End)) + fmt.Fprintf(output, "〚Positions: [%d, %d]〛\n", rng.Pos(), rng.End()) + fmt.Fprintf(output, "【TS: %s [%d, %d)】\n", diff.tsToken.Kind, diff.tsToken.Pos, diff.tsToken.End) + fmt.Fprintf(output, "《Go: %s [%d, %d)》\n", diff.goToken.Kind, diff.goToken.Pos, diff.goToken.End) for line := contextStart; line <= contextEnd; line++ { if truncate, skipTo := shouldTruncate(line); truncate { - output.WriteString(fmt.Sprintf("%s │........ %d lines omitted ........\n", strings.Repeat(" ", digits), skipTo-line+1)) + fmt.Fprintf(output, "%s │........ %d lines omitted ........\n", strings.Repeat(" ", digits), skipTo-line+1) line = skipTo } - output.WriteString(fmt.Sprintf("%*d │", digits, line+1)) + fmt.Fprintf(output, "%*d │", digits, line+1) end := len(file.Text) + 1 if line < len(lines)-1 { end = int(lines[line+1]) diff --git a/internal/binder/binder.go b/internal/binder/binder.go index f4b9274763..197c59fc27 100644 --- a/internal/binder/binder.go +++ b/internal/binder/binder.go @@ -245,7 +245,7 @@ func (b *Binder) declareSymbolEx(symbolTable ast.SymbolTable, parent *ast.Symbol } } } - var declarationName *ast.Node = ast.GetNameOfDeclaration(node) + var declarationName = ast.GetNameOfDeclaration(node) if declarationName == nil { declarationName = node } @@ -260,7 +260,7 @@ func (b *Binder) declareSymbolEx(symbolTable ast.SymbolTable, parent *ast.Symbol diag.AddRelatedInfo(b.createDiagnosticForNode(node, diagnostics.Did_you_mean_0, "export type { "+node.AsTypeAliasDeclaration().Name().AsIdentifier().Text+" }")) } for index, declaration := range symbol.Declarations { - var decl *ast.Node = ast.GetNameOfDeclaration(declaration) + var decl = ast.GetNameOfDeclaration(declaration) if decl == nil { decl = declaration } @@ -2023,7 +2023,7 @@ func (b *Binder) bindCaseBlock(node *ast.Node) { switchStatement := node.Parent clauses := node.AsCaseBlock().Clauses.Nodes isNarrowingSwitch := switchStatement.Expression().Kind == ast.KindTrueKeyword || isNarrowingExpression(switchStatement.Expression()) - var fallthroughFlow *ast.FlowNode = b.unreachableFlow + var fallthroughFlow = b.unreachableFlow for i := 0; i < len(clauses); i++ { clauseStart := i for len(clauses[i].AsCaseOrDefaultClause().Statements.Nodes) == 0 && i+1 < len(clauses) { diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 98be14ab3e..92de35dff7 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -1589,13 +1589,6 @@ func (c *Checker) getSuggestedLibForNonExistentName(name string) string { return "" } -func (c *Checker) getPrimitiveAliasSymbols() { - var symbols []*ast.Symbol - for _, name := range []string{"string", "number", "boolean", "object", "bigint", "symbol"} { - symbols = append(symbols, c.newSymbol(ast.SymbolFlagsTypeAlias, name)) - } -} - func (c *Checker) getSuggestedSymbolForNonexistentSymbol(location *ast.Node, outerName string, meaning ast.SymbolFlags) *ast.Symbol { return c.resolveNameForSymbolSuggestion(location, outerName, meaning, nil /*nameNotFoundMessage*/, false /*isUse*/, false /*excludeGlobals*/) } @@ -10207,10 +10200,10 @@ func (c *Checker) checkPrefixUnaryExpression(node *ast.Node) *Type { case ast.KindExclamationToken: c.checkTruthinessOfType(operandType, expr.Operand) facts := c.getTypeFacts(operandType, TypeFactsTruthy|TypeFactsFalsy) - switch { - case facts == TypeFactsTruthy: + switch facts { + case TypeFactsTruthy: return c.falseType - case facts == TypeFactsFalsy: + case TypeFactsFalsy: return c.trueType default: return c.booleanType @@ -12440,10 +12433,10 @@ func (c *Checker) checkObjectLiteral(node *ast.Node, checkMode CheckMode) *Type } if ast.IsPropertyAssignment(memberDecl) || ast.IsShorthandPropertyAssignment(memberDecl) || ast.IsObjectLiteralMethod(memberDecl) { var t *Type - switch { - case memberDecl.Kind == ast.KindPropertyAssignment: + switch memberDecl.Kind { + case ast.KindPropertyAssignment: t = c.checkPropertyAssignment(memberDecl, checkMode) - case memberDecl.Kind == ast.KindShorthandPropertyAssignment: + case ast.KindShorthandPropertyAssignment: var expr *ast.Node if !inDestructuringPattern { expr = memberDecl.AsShorthandPropertyAssignment().ObjectAssignmentInitializer @@ -15576,7 +15569,7 @@ func (c *Checker) getBaseConstructorTypeOfClass(t *Type) *Type { err := c.error(baseTypeNode.Expression(), diagnostics.Type_0_is_not_a_constructor_function_type, c.TypeToString(baseConstructorType)) if baseConstructorType.flags&TypeFlagsTypeParameter != 0 { constraint := c.getConstraintFromTypeParameter(baseConstructorType) - var ctorReturn *Type = c.unknownType + ctorReturn := c.unknownType if constraint != nil { ctorSigs := c.getSignaturesOfType(constraint, SignatureKindConstruct) if len(ctorSigs) != 0 { @@ -17055,12 +17048,12 @@ func (c *Checker) getOptionalType(t *Type, isProperty bool) *Type { // Add undefined or null or both to a type if they are missing. func (c *Checker) getNullableType(t *Type, flags TypeFlags) *Type { missing := (flags & ^t.flags) & (TypeFlagsUndefined | TypeFlagsNull) - switch { - case missing == 0: + switch missing { + case 0: return t - case missing == TypeFlagsUndefined: + case TypeFlagsUndefined: return c.getUnionType([]*Type{t, c.undefinedType}) - case missing == TypeFlagsNull: + case TypeFlagsNull: return c.getUnionType([]*Type{t, c.nullType}) } return c.getUnionType([]*Type{t, c.undefinedType, c.nullType}) @@ -18483,7 +18476,7 @@ func (c *Checker) getReturnTypeFromBody(fn *ast.Node, checkMode CheckMode) *Type var returnType *Type var yieldType *Type var nextType *Type - var fallbackReturnType *Type = c.voidType + fallbackReturnType := c.voidType switch { case !ast.IsBlock(body): returnType = c.checkExpressionCachedEx(body, checkMode & ^CheckModeSkipGenericFunctions) @@ -19494,7 +19487,7 @@ func (c *Checker) getUnionSignatures(signatureLists [][]*Signature) []*Signature // nature and having overloads in multiple constituents would necessitate making a power set of signatures from the type, whose // ordering would be non-obvious) masterList := signatureLists[indexWithLengthOverOne] - var results []*Signature = slices.Clone(masterList) + results := slices.Clone(masterList) for _, signatures := range signatureLists { if !core.Same(signatures, masterList) { signature := signatures[0] @@ -27417,10 +27410,10 @@ func (c *Checker) getContextualTypeForArgument(callTarget *ast.Node, arg *ast.No func (c *Checker) getContextualTypeForArgumentAtIndex(callTarget *ast.Node, argIndex int) *Type { if ast.IsImportCall(callTarget) { - switch { - case argIndex == 0: + switch argIndex { + case 0: return c.stringType - case argIndex == 1: + case 1: return c.getGlobalImportCallOptionsType() default: return c.anyType @@ -28805,10 +28798,10 @@ func (c *Checker) getGlobalNonNullableTypeInstantiation(t *Type) *Type { } func (c *Checker) convertAutoToAny(t *Type) *Type { - switch { - case t == c.autoType: + switch t { + case c.autoType: return c.anyType - case t == c.autoArrayType: + case c.autoArrayType: return c.anyArrayType } return t diff --git a/internal/checker/flow.go b/internal/checker/flow.go index 0093e5a80e..b824ae1550 100644 --- a/internal/checker/flow.go +++ b/internal/checker/flow.go @@ -1976,7 +1976,7 @@ func (c *Checker) getSwitchClauseTypeOfWitnesses(node *ast.Node) []string { // Return the combined not-equal type facts for all cases except those between the start and end indices. func (c *Checker) getNotEqualFactsFromTypeofSwitch(start int, end int, witnesses []string) TypeFacts { - var facts TypeFacts = TypeFactsNone + var facts = TypeFactsNone for i, witness := range witnesses { if (i < start || i >= end) && witness != "" { f, ok := typeofNEFacts[witness] diff --git a/internal/checker/grammarchecks.go b/internal/checker/grammarchecks.go index d8d0a732d0..46989933ea 100644 --- a/internal/checker/grammarchecks.go +++ b/internal/checker/grammarchecks.go @@ -1498,7 +1498,7 @@ func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) } - var current *ast.Node = node + var current = node for current != nil { if ast.IsFunctionLikeOrClassStaticBlockDeclaration(current) { return c.grammarErrorOnNode(node, diagnostics.Jump_target_cannot_cross_function_boundary) @@ -1801,14 +1801,14 @@ func (c *Checker) checkGrammarForDisallowedBlockScopedVariableStatement(node *as blockScopeKind := c.getCombinedNodeFlagsCached(node.DeclarationList) & ast.NodeFlagsBlockScoped if blockScopeKind != 0 { var keyword string - switch { - case blockScopeKind == ast.NodeFlagsLet: + switch blockScopeKind { + case ast.NodeFlagsLet: keyword = "let" - case blockScopeKind == ast.NodeFlagsConst: + case ast.NodeFlagsConst: keyword = "const" - case blockScopeKind == ast.NodeFlagsUsing: + case ast.NodeFlagsUsing: keyword = "using" - case blockScopeKind == ast.NodeFlagsAwaitUsing: + case ast.NodeFlagsAwaitUsing: keyword = "await using" default: panic("Unknown BlockScope flag") diff --git a/internal/checker/inference.go b/internal/checker/inference.go index 7fb543263a..860376c50d 100644 --- a/internal/checker/inference.go +++ b/internal/checker/inference.go @@ -579,10 +579,10 @@ func (c *Checker) inferToTemplateLiteralType(n *InferenceState, source *Type, ta case left.flags&TypeFlagsBoolean != 0: return left case right.flags&TypeFlagsBoolean != 0: - switch { - case str == "true": + switch str { + case "true": return c.trueType - case str == "false": + case "false": return c.falseType default: return c.booleanType diff --git a/internal/checker/relater.go b/internal/checker/relater.go index c3281879da..0f7a860ee9 100644 --- a/internal/checker/relater.go +++ b/internal/checker/relater.go @@ -4458,10 +4458,10 @@ func (r *Relater) constructorVisibilitiesAreCompatible(sourceSignature *Signatur // See signatureAssignableTo, compareSignaturesIdentical func (r *Relater) signatureRelatedTo(source *Signature, target *Signature, erase bool, reportErrors bool, intersectionState IntersectionState) Ternary { checkMode := SignatureCheckModeNone - switch { - case r.relation == r.c.subtypeRelation: + switch r.relation { + case r.c.subtypeRelation: checkMode = SignatureCheckModeStrictTopSignature - case r.relation == r.c.strictSubtypeRelation: + case r.c.strictSubtypeRelation: checkMode = SignatureCheckModeStrictTopSignature | SignatureCheckModeStrictArity } if erase { diff --git a/internal/compiler/packagejson/cache.go b/internal/compiler/packagejson/cache.go index 6c93fc99c7..9dc58a99a9 100644 --- a/internal/compiler/packagejson/cache.go +++ b/internal/compiler/packagejson/cache.go @@ -20,15 +20,15 @@ type PackageJson struct { func (p *PackageJson) GetVersionPaths(trace func(string)) VersionPaths { p.once.Do(func() { - if p.Fields.TypesVersions.Type == JSONValueTypeNotPresent { + if p.TypesVersions.Type == JSONValueTypeNotPresent { if trace != nil { trace(diagnostics.X_package_json_does_not_have_a_0_field.Format("typesVersions")) } return } - if p.Fields.TypesVersions.Type != JSONValueTypeObject { + if p.TypesVersions.Type != JSONValueTypeObject { if trace != nil { - trace(diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2.Format("typesVersions", "object", p.Fields.TypesVersions.Type.String())) + trace(diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2.Format("typesVersions", "object", p.TypesVersions.Type.String())) } return } diff --git a/internal/parser/jsdoc.go b/internal/parser/jsdoc.go index 662b313714..6d7564d4fb 100644 --- a/internal/parser/jsdoc.go +++ b/internal/parser/jsdoc.go @@ -1212,7 +1212,7 @@ func (p *Parser) parseOptionalJsdoc(t ast.Kind) bool { } func (p *Parser) parseJSDocEntityName() *ast.EntityName { - var entity *ast.EntityName = p.parseJSDocIdentifierName(nil) + var entity = p.parseJSDocIdentifierName(nil) if p.parseOptional(ast.KindOpenBracketToken) { p.parseExpected(ast.KindCloseBracketToken) // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index 5409b85d78..fa557debc3 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -1361,10 +1361,8 @@ func (s *Scanner) ScanJSDocToken() ast.Kind { if isIdentifierStart(ch, s.languageVersion) { char := ch - for { - if s.pos >= len(s.text) { - break - } + for s.pos < len(s.text) { + char, size = s.charAndSize() if !isIdentifierPart(char, s.languageVersion) && char != '-' { break diff --git a/internal/testutil/tsbaseline/error_baseline.go b/internal/testutil/tsbaseline/error_baseline.go index 186d02c15a..ef0d0a1a72 100644 --- a/internal/testutil/tsbaseline/error_baseline.go +++ b/internal/testutil/tsbaseline/error_baseline.go @@ -95,7 +95,7 @@ func iterateErrorBaseline(t *testing.T, inputFiles []*harnessutil.TestFile, inpu var errLines []string for _, line := range strings.Split(removeTestPathPrefixes(message, false), "\n") { line = strings.TrimSuffix(line, "\r") - if len(line) < 0 { + if len(line) == 0 { continue } out := fmt.Sprintf("!!! %s TS%d: %s", diag.Category().Name(), diag.Code(), line) diff --git a/internal/tsoptions/tsconfigparsing.go b/internal/tsoptions/tsconfigparsing.go index 8fa2758034..de636f811c 100644 --- a/internal/tsoptions/tsconfigparsing.go +++ b/internal/tsoptions/tsconfigparsing.go @@ -953,7 +953,7 @@ func parseConfig( if ownConfig.extendedConfigPath != nil { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = append(resolutionStack, resolvedPath) - var result *extendsResult = &extendsResult{ + var result = &extendsResult{ options: &core.CompilerOptions{}, } if reflect.TypeOf(ownConfig.extendedConfigPath).Kind() == reflect.String { @@ -1152,7 +1152,7 @@ func parseJsonConfigFileContentWorker( } getProjectReferences := func(basePath string) []core.ProjectReference { - var projectReferences []core.ProjectReference = []core.ProjectReference{} + var projectReferences = []core.ProjectReference{} newReferencesOfRaw := getPropFromRaw("references", func(element any) bool { return reflect.TypeOf(element) == orderedMapType }, "object") if newReferencesOfRaw.sliceValue != nil { for _, reference := range newReferencesOfRaw.sliceValue { @@ -1431,7 +1431,6 @@ func getFileNamesFromConfigSpecs( host vfs.FS, extraFileExtensions []fileExtensionInfo, ) []string { - extraFileExtensions = []fileExtensionInfo{} basePath = tspath.NormalizePath(basePath) keyMappper := func(value string) string { return tspath.GetCanonicalFileName(value, host.UseCaseSensitiveFileNames()) } // Literal file names (provided via the "files" array in tsconfig.json) are stored in a diff --git a/internal/tsoptions/tsconfigparsing_test.go b/internal/tsoptions/tsconfigparsing_test.go index 9eeeef505b..f84e028df8 100644 --- a/internal/tsoptions/tsconfigparsing_test.go +++ b/internal/tsoptions/tsconfigparsing_test.go @@ -599,8 +599,8 @@ func TestParseJsonSourceFileConfigFileContent(t *testing.T) { } } -func baselineParseConfigWith(t *testing.T, baselineFileName string, noSubmoduleBaseline bool, input []testConfig, getParsed func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine) { - noSubmoduleBaseline = true +func baselineParseConfigWith(t *testing.T, baselineFileName string, noSubmoduleBaseline bool, input []testConfig, getParsed func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine) {//nolint:staticcheck + noSubmoduleBaseline = true //nolint:staticcheck var baselineContent strings.Builder for i, config := range input { basePath := config.basePath From b29938dc06f58db9fcd960240eb4f97583168d64 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 26 Mar 2025 11:27:42 -0700 Subject: [PATCH 3/6] Just drop the param --- internal/tsoptions/tsconfigparsing_test.go | 25 +++++++++------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/internal/tsoptions/tsconfigparsing_test.go b/internal/tsoptions/tsconfigparsing_test.go index f84e028df8..dc1bc691d2 100644 --- a/internal/tsoptions/tsconfigparsing_test.go +++ b/internal/tsoptions/tsconfigparsing_test.go @@ -156,9 +156,8 @@ func TestParseConfigFileTextToJson(t *testing.T) { } var parseJsonConfigFileTests = []struct { - title string - noSubmoduleBaseline bool - input []testConfig + title string + input []testConfig }{ { title: "ignore dotted files and folders", @@ -234,8 +233,7 @@ var parseJsonConfigFileTests = []struct { }}, }, { - title: "parses tsconfig with compilerOptions, files, include, and exclude", - noSubmoduleBaseline: true, + title: "parses tsconfig with compilerOptions, files, include, and exclude", input: []testConfig{{ jsonText: `{ "compilerOptions": { @@ -438,8 +436,7 @@ var parseJsonConfigFileTests = []struct { }}, }, { - title: "parses tsconfig with extends, files, include and other options", - noSubmoduleBaseline: true, + title: "parses tsconfig with extends, files, include and other options", input: []testConfig{{ jsonText: `{ "extends": "./tsconfigWithExtends.json", @@ -456,8 +453,7 @@ var parseJsonConfigFileTests = []struct { }}, }, { - title: "parses tsconfig with extends and configDir", - noSubmoduleBaseline: true, + title: "parses tsconfig with extends and configDir", input: []testConfig{{ jsonText: `{ "extends": "./tsconfig.base.json" @@ -496,8 +492,7 @@ var parseJsonConfigFileTests = []struct { }}, }, { - title: "handles empty types array", - noSubmoduleBaseline: true, + title: "handles empty types array", input: []testConfig{{ jsonText: `{ "compilerOptions": { @@ -552,7 +547,7 @@ func TestParseJsonConfigFileContent(t *testing.T) { for _, rec := range parseJsonConfigFileTests { t.Run(rec.title+" with json api", func(t *testing.T) { t.Parallel() - baselineParseConfigWith(t, rec.title+" with json api.js", rec.noSubmoduleBaseline, rec.input, func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine { + baselineParseConfigWith(t, rec.title+" with json api.js", rec.input, func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine { configFileName := tspath.GetNormalizedAbsolutePath(config.configFileName, basePath) path := tspath.ToPath(config.configFileName, basePath, host.FS().UseCaseSensitiveFileNames()) parsed, _ := tsoptions.ParseConfigFileTextToJson(configFileName, path, config.jsonText) @@ -577,7 +572,7 @@ func TestParseJsonSourceFileConfigFileContent(t *testing.T) { for _, rec := range parseJsonConfigFileTests { t.Run(rec.title+" with jsonSourceFile api", func(t *testing.T) { t.Parallel() - baselineParseConfigWith(t, rec.title+" with jsonSourceFile api.js", rec.noSubmoduleBaseline, rec.input, func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine { + baselineParseConfigWith(t, rec.title+" with jsonSourceFile api.js", rec.input, func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine { configFileName := tspath.GetNormalizedAbsolutePath(config.configFileName, basePath) path := tspath.ToPath(config.configFileName, basePath, host.FS().UseCaseSensitiveFileNames()) parsed := parser.ParseJSONText(configFileName, path, config.jsonText) @@ -599,8 +594,8 @@ func TestParseJsonSourceFileConfigFileContent(t *testing.T) { } } -func baselineParseConfigWith(t *testing.T, baselineFileName string, noSubmoduleBaseline bool, input []testConfig, getParsed func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine) {//nolint:staticcheck - noSubmoduleBaseline = true //nolint:staticcheck +func baselineParseConfigWith(t *testing.T, baselineFileName string, input []testConfig, getParsed func(config testConfig, host tsoptions.ParseConfigHost, basePath string) *tsoptions.ParsedCommandLine) { + noSubmoduleBaseline := true var baselineContent strings.Builder for i, config := range input { basePath := config.basePath From e499d77367f130e54564850890e0735668590c2d Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 26 Mar 2025 11:27:53 -0700 Subject: [PATCH 4/6] fmt --- internal/binder/binder.go | 6 +++--- internal/checker/flow.go | 2 +- internal/checker/grammarchecks.go | 2 +- internal/parser/jsdoc.go | 2 +- internal/tsoptions/tsconfigparsing.go | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/binder/binder.go b/internal/binder/binder.go index 197c59fc27..7abf0c3f7c 100644 --- a/internal/binder/binder.go +++ b/internal/binder/binder.go @@ -245,7 +245,7 @@ func (b *Binder) declareSymbolEx(symbolTable ast.SymbolTable, parent *ast.Symbol } } } - var declarationName = ast.GetNameOfDeclaration(node) + declarationName := ast.GetNameOfDeclaration(node) if declarationName == nil { declarationName = node } @@ -260,7 +260,7 @@ func (b *Binder) declareSymbolEx(symbolTable ast.SymbolTable, parent *ast.Symbol diag.AddRelatedInfo(b.createDiagnosticForNode(node, diagnostics.Did_you_mean_0, "export type { "+node.AsTypeAliasDeclaration().Name().AsIdentifier().Text+" }")) } for index, declaration := range symbol.Declarations { - var decl = ast.GetNameOfDeclaration(declaration) + decl := ast.GetNameOfDeclaration(declaration) if decl == nil { decl = declaration } @@ -2023,7 +2023,7 @@ func (b *Binder) bindCaseBlock(node *ast.Node) { switchStatement := node.Parent clauses := node.AsCaseBlock().Clauses.Nodes isNarrowingSwitch := switchStatement.Expression().Kind == ast.KindTrueKeyword || isNarrowingExpression(switchStatement.Expression()) - var fallthroughFlow = b.unreachableFlow + fallthroughFlow := b.unreachableFlow for i := 0; i < len(clauses); i++ { clauseStart := i for len(clauses[i].AsCaseOrDefaultClause().Statements.Nodes) == 0 && i+1 < len(clauses) { diff --git a/internal/checker/flow.go b/internal/checker/flow.go index b824ae1550..6402e2bb3e 100644 --- a/internal/checker/flow.go +++ b/internal/checker/flow.go @@ -1976,7 +1976,7 @@ func (c *Checker) getSwitchClauseTypeOfWitnesses(node *ast.Node) []string { // Return the combined not-equal type facts for all cases except those between the start and end indices. func (c *Checker) getNotEqualFactsFromTypeofSwitch(start int, end int, witnesses []string) TypeFacts { - var facts = TypeFactsNone + facts := TypeFactsNone for i, witness := range witnesses { if (i < start || i >= end) && witness != "" { f, ok := typeofNEFacts[witness] diff --git a/internal/checker/grammarchecks.go b/internal/checker/grammarchecks.go index 46989933ea..11ca64efef 100644 --- a/internal/checker/grammarchecks.go +++ b/internal/checker/grammarchecks.go @@ -1498,7 +1498,7 @@ func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) } - var current = node + current := node for current != nil { if ast.IsFunctionLikeOrClassStaticBlockDeclaration(current) { return c.grammarErrorOnNode(node, diagnostics.Jump_target_cannot_cross_function_boundary) diff --git a/internal/parser/jsdoc.go b/internal/parser/jsdoc.go index 6d7564d4fb..185f1a5e21 100644 --- a/internal/parser/jsdoc.go +++ b/internal/parser/jsdoc.go @@ -1212,7 +1212,7 @@ func (p *Parser) parseOptionalJsdoc(t ast.Kind) bool { } func (p *Parser) parseJSDocEntityName() *ast.EntityName { - var entity = p.parseJSDocIdentifierName(nil) + entity := p.parseJSDocIdentifierName(nil) if p.parseOptional(ast.KindOpenBracketToken) { p.parseExpected(ast.KindCloseBracketToken) // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. diff --git a/internal/tsoptions/tsconfigparsing.go b/internal/tsoptions/tsconfigparsing.go index de636f811c..1828c39d87 100644 --- a/internal/tsoptions/tsconfigparsing.go +++ b/internal/tsoptions/tsconfigparsing.go @@ -953,7 +953,7 @@ func parseConfig( if ownConfig.extendedConfigPath != nil { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = append(resolutionStack, resolvedPath) - var result = &extendsResult{ + result := &extendsResult{ options: &core.CompilerOptions{}, } if reflect.TypeOf(ownConfig.extendedConfigPath).Kind() == reflect.String { @@ -1152,7 +1152,7 @@ func parseJsonConfigFileContentWorker( } getProjectReferences := func(basePath string) []core.ProjectReference { - var projectReferences = []core.ProjectReference{} + projectReferences := []core.ProjectReference{} newReferencesOfRaw := getPropFromRaw("references", func(element any) bool { return reflect.TypeOf(element) == orderedMapType }, "object") if newReferencesOfRaw.sliceValue != nil { for _, reference := range newReferencesOfRaw.sliceValue { From c7f34e970467320d01fd2927aea962d89b57058f Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 9 Apr 2025 14:32:19 -0700 Subject: [PATCH 5/6] Fix --- internal/checker/jsx.go | 2 +- internal/parser/parser.go | 2 +- internal/testutil/harnessutil/sourcemap_recorder.go | 4 ++-- internal/testutil/tsbaseline/sourcemap_baseline.go | 6 +----- internal/vfs/cachedvfs/cachedvfs.go | 2 +- 5 files changed, 6 insertions(+), 10 deletions(-) diff --git a/internal/checker/jsx.go b/internal/checker/jsx.go index 61361fb9d0..2b3f6b0cc5 100644 --- a/internal/checker/jsx.go +++ b/internal/checker/jsx.go @@ -602,7 +602,7 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme } // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if parent != nil && parent.AsJsxElement().OpeningElement == openingLikeElement && len(getSemanticJsxChildren(parent.AsJsxElement().Children.Nodes)) != 0 { - var childTypes []*Type = c.checkJsxChildren(parent, checkMode) + var childTypes = c.checkJsxChildren(parent, checkMode) if !hasSpreadAnyType && jsxChildrenPropertyName != ast.InternalSymbolNameMissing && jsxChildrenPropertyName != "" { // Error if there is a attribute named "children" explicitly specified and children element. // This is because children element will overwrite the value from attributes. diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 426fffac2b..4ffcaf4e70 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -6601,7 +6601,7 @@ func processPragmasIntoFields(context *ast.SourceFile /* !!! reportDiagnostic fu case "ts-check", "ts-nocheck": // _last_ of either nocheck or check in a file is the "winner" for _, directive := range context.Pragmas { - if context.CheckJsDirective == nil || directive.TextRange.Pos() > context.CheckJsDirective.Range.Pos() { + if context.CheckJsDirective == nil || directive.Pos() > context.CheckJsDirective.Range.Pos() { context.CheckJsDirective = &ast.CheckJsDirective{ Enabled: directive.Name == "ts-check", Range: directive.CommentRange, diff --git a/internal/testutil/harnessutil/sourcemap_recorder.go b/internal/testutil/harnessutil/sourcemap_recorder.go index 1e990c2e4e..2038ab7f5d 100644 --- a/internal/testutil/harnessutil/sourcemap_recorder.go +++ b/internal/testutil/harnessutil/sourcemap_recorder.go @@ -17,7 +17,7 @@ type writerAggregator struct { } func (w *writerAggregator) WriteStringF(format string, args ...any) { - w.WriteString(fmt.Sprintf(format, args...)) + fmt.Fprintf(w, format, args...) } func (w *writerAggregator) WriteLine(s string) { @@ -58,7 +58,7 @@ func (d *sourceMapDecoder) decodeNextEncodedSourceMapSpan() *decodedMapping { sourceMapSpan: d.mappings.State(), } if mapping.error == nil { - mapping.error = errors.New("No encoded entry found") + mapping.error = errors.New("no encoded entry found") } return mapping } diff --git a/internal/testutil/tsbaseline/sourcemap_baseline.go b/internal/testutil/tsbaseline/sourcemap_baseline.go index 081825feef..927785ee40 100644 --- a/internal/testutil/tsbaseline/sourcemap_baseline.go +++ b/internal/testutil/tsbaseline/sourcemap_baseline.go @@ -87,11 +87,7 @@ func createSourceMapPreviewLink(sourceMap *harnessutil.TestFile, result *harness return "" } - var sourceTDs []*harnessutil.TestFile - ////if len(sourcemapJSON.Sources) == len(inputsAndOutputs.Inputs) { - //// sourceTDs = inputsAndOutputs.Inputs - ////} else { - sourceTDs = core.Map(sourcemapJSON.Sources, func(s string) *harnessutil.TestFile { + var sourceTDs = core.Map(sourcemapJSON.Sources, func(s string) *harnessutil.TestFile { return core.Find(result.Inputs(), func(td *harnessutil.TestFile) bool { return strings.HasSuffix(td.UnitName, s) }) diff --git a/internal/vfs/cachedvfs/cachedvfs.go b/internal/vfs/cachedvfs/cachedvfs.go index 132c67bfaf..36e1904e89 100644 --- a/internal/vfs/cachedvfs/cachedvfs.go +++ b/internal/vfs/cachedvfs/cachedvfs.go @@ -75,7 +75,7 @@ func (fsys *FS) Remove(path string) error { func (fsys *FS) Stat(path string) vfs.FileInfo { if ret, ok := fsys.statCache.Load(path); ok { - return ret.(vfs.FileInfo) + return ret } ret := fsys.fs.Stat(path) fsys.statCache.Store(path, ret) From 7ca8f4c6c662fe3783f1e97287b6c5eed341e69d Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 18 Apr 2025 13:10:24 -0700 Subject: [PATCH 6/6] Restore comment --- internal/testutil/tsbaseline/sourcemap_baseline.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/testutil/tsbaseline/sourcemap_baseline.go b/internal/testutil/tsbaseline/sourcemap_baseline.go index 737616de49..e247558862 100644 --- a/internal/testutil/tsbaseline/sourcemap_baseline.go +++ b/internal/testutil/tsbaseline/sourcemap_baseline.go @@ -87,6 +87,9 @@ func createSourceMapPreviewLink(sourceMap *harnessutil.TestFile, result *harness return "" } + ////if len(sourcemapJSON.Sources) == len(inputsAndOutputs.Inputs) { + //// sourceTDs = inputsAndOutputs.Inputs + ////} else { sourceTDs := core.Map(sourcemapJSON.Sources, func(s string) *harnessutil.TestFile { return core.Find(result.Inputs(), func(td *harnessutil.TestFile) bool { return strings.HasSuffix(td.UnitName, s)