diff --git a/.golangci.yml b/.golangci.yml index afb62f07e9..fbdecbdc7c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -39,6 +39,7 @@ linters: - perfsprint - predeclared - reassign + - staticcheck - testableexamples - tparallel - unconvert @@ -53,7 +54,6 @@ linters: # - gocritic # - gosec # - revive - # - staticcheck # - testifylint # - unparam # - unused @@ -70,6 +70,22 @@ linters: - pkg: 'encoding/json$' desc: 'Use "github.com/go-json-experiment/json" instead.' + staticcheck: + checks: + - all + - -QF1001 + - -QF1003 + - -SA1019 + - -SA6005 + - -SA9003 + - -ST1000 + - -ST1003 + - -ST1006 # TODO: enable + - -ST1016 + - -ST1020 + - -ST1021 + - -ST1022 + exclusions: rules: - path: internal/fourslash/tests/gen/ diff --git a/internal/astnav/tokens_test.go b/internal/astnav/tokens_test.go index b5eb7ba39f..461f30a825 100644 --- a/internal/astnav/tokens_test.go +++ b/internal/astnav/tokens_test.go @@ -285,23 +285,23 @@ 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())) + fmt.Fprintf(output, "〚Positions: [%d, %d]〛\n", rng.Pos(), rng.End()) if diff.tsToken != nil { - output.WriteString(fmt.Sprintf("【TS: %s [%d, %d)】\n", diff.tsToken.Kind, tsTokenPos, tsTokenEnd)) + fmt.Fprintf(output, "【TS: %s [%d, %d)】\n", diff.tsToken.Kind, tsTokenPos, tsTokenEnd) } else { output.WriteString("【TS: nil】\n") } if diff.goToken != nil { - output.WriteString(fmt.Sprintf("《Go: %s [%d, %d)》\n", diff.goToken.Kind, goTokenPos, goTokenEnd)) + fmt.Fprintf(output, "《Go: %s [%d, %d)》\n", diff.goToken.Kind, goTokenPos, goTokenEnd) } else { output.WriteString("《Go: nil》\n") } 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 8fde6ff763..d438efce66 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) + 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) + decl := ast.GetNameOfDeclaration(declaration) if decl == nil { decl = declaration } @@ -2101,7 +2101,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 + 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 9bf74ed8a4..f000dc3648 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -1651,13 +1651,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*/) } @@ -10412,10 +10405,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 @@ -14754,10 +14747,10 @@ func (c *Checker) getSuggestedImportSource(moduleReference string, tsExtension s if c.moduleKind.IsNonNodeESM() || mode == core.ModuleKindESNext { preferTs := tspath.IsDeclarationFileName(moduleReference) && c.compilerOptions.GetAllowImportingTsExtensions() var ext string - switch { - case tsExtension == tspath.ExtensionMts || tsExtension == tspath.ExtensionDmts: + switch tsExtension { + case tspath.ExtensionMts, tspath.ExtensionDmts: ext = core.IfElse(preferTs, ".mts", ".mjs") - case tsExtension == tspath.ExtensionCts || tsExtension == tspath.ExtensionDcts: + case tspath.ExtensionCts, tspath.ExtensionDcts: ext = core.IfElse(preferTs, ".cts", ".cjs") default: ext = core.IfElse(preferTs, ".ts", ".js") @@ -16231,7 +16224,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 { @@ -17802,12 +17795,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}) @@ -19280,7 +19273,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) @@ -20292,7 +20285,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] @@ -28405,10 +28398,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 @@ -29831,10 +29824,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 6ff6acbf4c..286d1a9c0d 100644 --- a/internal/checker/flow.go +++ b/internal/checker/flow.go @@ -1979,7 +1979,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 + 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 ee64d4072b..d2570ddda7 100644 --- a/internal/checker/grammarchecks.go +++ b/internal/checker/grammarchecks.go @@ -1525,7 +1525,7 @@ func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) } - var current *ast.Node = node + current := node for current != nil { if ast.IsFunctionLikeOrClassStaticBlockDeclaration(current) { return c.grammarErrorOnNode(node, diagnostics.Jump_target_cannot_cross_function_boundary) @@ -1829,14 +1829,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 d395f03a98..e9c4471099 100644 --- a/internal/checker/inference.go +++ b/internal/checker/inference.go @@ -580,10 +580,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/jsx.go b/internal/checker/jsx.go index 7f0342d76b..722f53f0e9 100644 --- a/internal/checker/jsx.go +++ b/internal/checker/jsx.go @@ -806,7 +806,7 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme return len(ast.GetSemanticJsxChildren(children)) != 0 } if parentHasSemanticJsxChildren(openingLikeElement) { - var childTypes []*Type = c.checkJsxChildren(openingLikeElement.Parent, checkMode) + childTypes := c.checkJsxChildren(openingLikeElement.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/checker/nodebuilderimpl.go b/internal/checker/nodebuilderimpl.go index 9f07545c05..7d273e0a23 100644 --- a/internal/checker/nodebuilderimpl.go +++ b/internal/checker/nodebuilderimpl.go @@ -181,7 +181,7 @@ func (b *nodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.Typ // !!! Without the above, nested type args are silently elided // then move qualifiers ids := getAccessStack(ref) - var typeName *ast.Node = root.AsTypeReferenceNode().TypeName + typeName := root.AsTypeReferenceNode().TypeName for _, id := range ids { typeName = b.f.NewQualifiedName(typeName, id) } @@ -190,7 +190,7 @@ func (b *nodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.Typ } func getAccessStack(ref *ast.Node) []*ast.Node { - var state *ast.Node = ref.AsTypeReferenceNode().TypeName + state := ref.AsTypeReferenceNode().TypeName ids := []*ast.Node{} for !ast.IsIdentifier(state) { entity := state.AsQualifiedName() @@ -1320,7 +1320,7 @@ func (b *nodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifi } text := rawText - for true { + for { _, present := b.ctx.typeParameterNamesByText[text] if !present && !b.typeParameterShadowsOtherTypeParameterInScope(text, typeParameter) { break @@ -1752,47 +1752,47 @@ func (b *nodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signa } var node *ast.Node - switch { - case kind == ast.KindCallSignature: + switch kind { + case ast.KindCallSignature: node = b.f.NewCallSignatureDeclaration(typeParamList, paramList, returnTypeNode) - case kind == ast.KindConstructSignature: + case ast.KindConstructSignature: node = b.f.NewConstructSignatureDeclaration(typeParamList, paramList, returnTypeNode) - case kind == ast.KindMethodSignature: + case ast.KindMethodSignature: var questionToken *ast.Node if options != nil { questionToken = options.questionToken } node = b.f.NewMethodSignatureDeclaration(modifierList, name, questionToken, typeParamList, paramList, returnTypeNode) - case kind == ast.KindMethodDeclaration: + case ast.KindMethodDeclaration: node = b.f.NewMethodDeclaration(modifierList, nil /*asteriskToken*/, name, nil /*questionToken*/, typeParamList, paramList, returnTypeNode, nil /*fullSignature*/, nil /*body*/) - case kind == ast.KindConstructor: + case ast.KindConstructor: node = b.f.NewConstructorDeclaration(modifierList, nil /*typeParamList*/, paramList, nil /*returnTypeNode*/, nil /*fullSignature*/, nil /*body*/) - case kind == ast.KindGetAccessor: + case ast.KindGetAccessor: node = b.f.NewGetAccessorDeclaration(modifierList, name, nil /*typeParamList*/, paramList, returnTypeNode, nil /*fullSignature*/, nil /*body*/) - case kind == ast.KindSetAccessor: + case ast.KindSetAccessor: node = b.f.NewSetAccessorDeclaration(modifierList, name, nil /*typeParamList*/, paramList, nil /*returnTypeNode*/, nil /*fullSignature*/, nil /*body*/) - case kind == ast.KindIndexSignature: + case ast.KindIndexSignature: node = b.f.NewIndexSignatureDeclaration(modifierList, paramList, returnTypeNode) // !!! JSDoc Support - // case kind == ast.KindJSDocFunctionType: + // case ast.KindJSDocFunctionType: // node = b.f.NewJSDocFunctionType(parameters, returnTypeNode) - case kind == ast.KindFunctionType: + case ast.KindFunctionType: if returnTypeNode == nil { returnTypeNode = b.f.NewTypeReferenceNode(b.f.NewIdentifier(""), nil) } node = b.f.NewFunctionTypeNode(typeParamList, paramList, returnTypeNode) - case kind == ast.KindConstructorType: + case ast.KindConstructorType: if returnTypeNode == nil { returnTypeNode = b.f.NewTypeReferenceNode(b.f.NewIdentifier(""), nil) } node = b.f.NewConstructorTypeNode(modifierList, typeParamList, paramList, returnTypeNode) - case kind == ast.KindFunctionDeclaration: + case ast.KindFunctionDeclaration: // TODO: assert name is Identifier node = b.f.NewFunctionDeclaration(modifierList, nil /*asteriskToken*/, name, typeParamList, paramList, returnTypeNode, nil /*fullSignature*/, nil /*body*/) - case kind == ast.KindFunctionExpression: + case ast.KindFunctionExpression: // TODO: assert name is Identifier node = b.f.NewFunctionExpression(modifierList, nil /*asteriskToken*/, name, typeParamList, paramList, returnTypeNode, nil /*fullSignature*/, b.f.NewBlock(b.f.NewNodeList([]*ast.Node{}), false)) - case kind == ast.KindArrowFunction: + case ast.KindArrowFunction: node = b.f.NewArrowFunction(modifierList, typeParamList, paramList, returnTypeNode, nil /*fullSignature*/, nil /*equalsGreaterThanToken*/, b.f.NewBlock(b.f.NewNodeList([]*ast.Node{}), false)) default: panic("Unhandled kind in signatureToSignatureDeclarationHelper") @@ -1834,7 +1834,7 @@ func (c *Checker) getExpandedParameters(sig *Signature, skipUnionExpanding bool) counter = 1 } var name string - for true { + for { name = fmt.Sprintf("%s_%d", names[i], counter) _, ok := uniqueNames[name] if ok { @@ -2551,7 +2551,7 @@ func (b *nodeBuilderImpl) conditionalTypeToTypeNode(_t *Type) *ast.TypeNode { func (b *nodeBuilderImpl) getParentSymbolOfTypeParameter(typeParameter *TypeParameter) *ast.Symbol { tp := ast.GetDeclarationOfKind(typeParameter.symbol, ast.KindTypeParameter) - var host *ast.Node + var host *ast.Node //nolint:staticcheck // !!! JSDoc support // if ast.IsJSDocTemplateTag(tp.Parent) { // host = getEffectiveContainerForJSDocTemplateTag(tp.Parent) @@ -2565,7 +2565,7 @@ func (b *nodeBuilderImpl) getParentSymbolOfTypeParameter(typeParameter *TypePara } func (b *nodeBuilderImpl) typeReferenceToTypeNode(t *Type) *ast.TypeNode { - var typeArguments []*Type = b.ch.getTypeArguments(t) + typeArguments := b.ch.getTypeArguments(t) if t.Target() == b.ch.globalArrayType || t.Target() == b.ch.globalReadonlyArrayType { if b.ctx.flags&nodebuilder.FlagsWriteArrayAsGenericType != 0 { typeArgumentNode := b.typeToTypeNode(typeArguments[0]) diff --git a/internal/checker/relater.go b/internal/checker/relater.go index dbc104ff2f..afb59c5160 100644 --- a/internal/checker/relater.go +++ b/internal/checker/relater.go @@ -4454,10 +4454,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/checker/symbolaccessibility.go b/internal/checker/symbolaccessibility.go index d9741f18a5..cedcc118ca 100644 --- a/internal/checker/symbolaccessibility.go +++ b/internal/checker/symbolaccessibility.go @@ -569,10 +569,8 @@ func (ch *Checker) isAccessible( resolvedAliasSymbol *ast.Symbol, ignoreQualification bool, ) bool { - likeSymbols := false - if ctx.symbol == resolvedAliasSymbol { - likeSymbols = true - } + likeSymbols := ctx.symbol == resolvedAliasSymbol + if ctx.symbol == symbolFromSymbolTable { likeSymbols = true } diff --git a/internal/checker/utilities.go b/internal/checker/utilities.go index e131201893..07de43151f 100644 --- a/internal/checker/utilities.go +++ b/internal/checker/utilities.go @@ -1840,7 +1840,7 @@ func (c *Checker) typesPackageExists(packageName string) bool { func (c *Checker) packageBundlesTypes(packageName string) bool { packagesMap := c.getPackagesMap() - hasTypes, _ := packagesMap[packageName] + hasTypes := packagesMap[packageName] return hasTypes } diff --git a/internal/collections/syncmap.go b/internal/collections/syncmap.go index 9a020bc23e..602652e132 100644 --- a/internal/collections/syncmap.go +++ b/internal/collections/syncmap.go @@ -66,10 +66,7 @@ func (s *SyncMap[K, V]) ToMap() map[K]V { func (s *SyncMap[K, V]) Keys() iter.Seq[K] { return func(yield func(K) bool) { s.m.Range(func(key, value any) bool { - if !yield(key.(K)) { - return false - } - return true + return yield(key.(K)) }) } } diff --git a/internal/collections/syncset.go b/internal/collections/syncset.go index 74b52fb843..fb4803f939 100644 --- a/internal/collections/syncset.go +++ b/internal/collections/syncset.go @@ -58,10 +58,7 @@ func (s *SyncSet[T]) ToSlice() []T { func (s *SyncSet[T]) Keys() iter.Seq[T] { return func(yield func(T) bool) { s.m.Range(func(key T, value struct{}) bool { - if !yield(key) { - return false - } - return true + return yield(key) }) } } diff --git a/internal/compiler/projectreferencefilemapper.go b/internal/compiler/projectreferencefilemapper.go index 17649ec3e0..3adca11c61 100644 --- a/internal/compiler/projectreferencefilemapper.go +++ b/internal/compiler/projectreferencefilemapper.go @@ -51,7 +51,7 @@ func (mapper *projectReferenceFileMapper) getResolvedProjectReferences() []*tsop if ok { result = make([]*tsoptions.ParsedCommandLine, 0, len(refs)) for _, refPath := range refs { - refConfig, _ := mapper.configToProjectReference[refPath] + refConfig := mapper.configToProjectReference[refPath] result = append(result, refConfig) } } @@ -128,7 +128,7 @@ func (mapper *projectReferenceFileMapper) forEachResolvedReferenceWorker( if !seenRef.AddIfAbsent(path) { continue } - config, _ := mapper.configToProjectReference[path] + config := mapper.configToProjectReference[path] fn(path, config, parent, index) mapper.forEachResolvedReferenceWorker(mapper.referencesInConfigFile[path], fn, config, seenRef) } diff --git a/internal/compiler/projectreferenceparser.go b/internal/compiler/projectreferenceparser.go index f6dd57b4af..1a255bbf54 100644 --- a/internal/compiler/projectreferenceparser.go +++ b/internal/compiler/projectreferenceparser.go @@ -84,8 +84,7 @@ func (p *projectReferenceParser) initMapperWorker(tasks []*projectReferenceParse if !seen.AddIfAbsent(task) { continue } - var referencesInConfig []tspath.Path - referencesInConfig = p.initMapperWorker(task.subTasks, seen) + referencesInConfig := p.initMapperWorker(task.subTasks, seen) p.loader.projectReferenceFileMapper.configToProjectReference[path] = task.resolved p.loader.projectReferenceFileMapper.referencesInConfigFile[path] = referencesInConfig if task.resolved == nil || p.loader.projectReferenceFileMapper.opts.Config.ConfigFile == task.resolved.ConfigFile { diff --git a/internal/core/textchange.go b/internal/core/textchange.go index 9945af4f70..904ebe9948 100644 --- a/internal/core/textchange.go +++ b/internal/core/textchange.go @@ -16,13 +16,13 @@ func ApplyBulkEdits(text string, edits []TextChange) string { b.Grow(len(text)) lastEnd := 0 for _, e := range edits { - start := e.TextRange.Pos() + start := e.Pos() if start != lastEnd { - b.WriteString(text[lastEnd:e.TextRange.Pos()]) + b.WriteString(text[lastEnd:e.Pos()]) } b.WriteString(e.NewText) - lastEnd = e.TextRange.End() + lastEnd = e.End() } b.WriteString(text[lastEnd:]) diff --git a/internal/debug/shared.go b/internal/debug/shared.go index aa2ff66a27..3275089bc2 100644 --- a/internal/debug/shared.go +++ b/internal/debug/shared.go @@ -32,11 +32,12 @@ func AssertNever(member any, message ...string) { msg = message[0] } var detail string - if member, ok := member.(interface{ KindString() string }); ok { + switch member := member.(type) { + case interface{ KindString() string }: detail = member.KindString() - } else if member, ok := member.(fmt.Stringer); ok { + case fmt.Stringer: detail = member.String() - } else { + default: detail = fmt.Sprintf("%v", member) } Fail(fmt.Sprintf("%s %s", msg, detail)) diff --git a/internal/execute/build/orchestrator.go b/internal/execute/build/orchestrator.go index d521031780..aa4f43c370 100644 --- a/internal/execute/build/orchestrator.go +++ b/internal/execute/build/orchestrator.go @@ -167,7 +167,6 @@ func (o *Orchestrator) setupBuildTask( } } } - circularityStack = circularityStack[:len(circularityStack)-1] completed.Add(path) task.reportDone = make(chan struct{}) prev := core.LastOrNil(o.order) diff --git a/internal/execute/incremental/snapshot.go b/internal/execute/incremental/snapshot.go index d1ce2053cd..866267065e 100644 --- a/internal/execute/incremental/snapshot.go +++ b/internal/execute/incremental/snapshot.go @@ -297,10 +297,10 @@ func diagnosticToStringBuilder(diagnostic *ast.Diagnostic, file *ast.SourceFile, ))) } if diagnostic.File() != nil { - builder.WriteString(fmt.Sprintf("(%d,%d): ", diagnostic.Pos(), diagnostic.Len())) + fmt.Fprintf(builder, "(%d,%d): ", diagnostic.Pos(), diagnostic.Len()) } builder.WriteString(diagnostic.Category().Name()) - builder.WriteString(fmt.Sprintf("%d: ", diagnostic.Code())) + fmt.Fprintf(builder, "%d: ", diagnostic.Code()) builder.WriteString(diagnostic.Message()) for _, chain := range diagnostic.MessageChain() { diagnosticToStringBuilder(chain, file, builder) diff --git a/internal/execute/tsctests/runner.go b/internal/execute/tsctests/runner.go index 7cb8c261bd..8f55062b69 100644 --- a/internal/execute/tsctests/runner.go +++ b/internal/execute/tsctests/runner.go @@ -88,7 +88,7 @@ func (test *tscInput) run(t *testing.T, scenario string) { var nonIncrementalSys *testSys commandLineArgs := core.IfElse(do.commandLineArgs == nil, test.commandLineArgs, do.commandLineArgs) wg.Queue(func() { - baselineBuilder.WriteString(fmt.Sprintf("\n\nEdit [%d]:: %s\n", index, do.caption)) + fmt.Fprintf(baselineBuilder, "\n\nEdit [%d]:: %s\n", index, do.caption) if do.edit != nil { do.edit(sys) } @@ -116,13 +116,13 @@ func (test *tscInput) run(t *testing.T, scenario string) { diff := getDiffForIncremental(sys, nonIncrementalSys) if diff != "" { - baselineBuilder.WriteString(fmt.Sprintf("\n\nDiff:: %s\n", core.IfElse(do.expectedDiff == "", "!!! Unexpected diff, please review and either fix or write explanation as expectedDiff !!!", do.expectedDiff))) + fmt.Fprintf(baselineBuilder, "\n\nDiff:: %s\n", core.IfElse(do.expectedDiff == "", "!!! Unexpected diff, please review and either fix or write explanation as expectedDiff !!!", do.expectedDiff)) baselineBuilder.WriteString(diff) if do.expectedDiff == "" { unexpectedDiff += fmt.Sprintf("Edit [%d]:: %s\n!!! Unexpected diff, please review and either fix or write explanation as expectedDiff !!!\n%s\n", index, do.caption, diff) } } else if do.expectedDiff != "" { - baselineBuilder.WriteString(fmt.Sprintf("\n\nDiff:: %s !!! Diff not found but explanation present, please review and remove the explanation !!!\n", do.expectedDiff)) + fmt.Fprintf(baselineBuilder, "\n\nDiff:: %s !!! Diff not found but explanation present, please review and remove the explanation !!!\n", do.expectedDiff) unexpectedDiff += fmt.Sprintf("Edit [%d]:: %s\n!!! Diff not found but explanation present, please review and remove the explanation !!!\n", index, do.caption) } } diff --git a/internal/execute/tsctests/tscbuild_test.go b/internal/execute/tsctests/tscbuild_test.go index 5c7a91b293..f44e777737 100644 --- a/internal/execute/tsctests/tscbuild_test.go +++ b/internal/execute/tsctests/tscbuild_test.go @@ -2266,7 +2266,7 @@ func TestBuildProjectReferenceWithRootDirInParent(t *testing.T) { subScenario: "reports error for same tsbuildinfo file because no rootDir in the base", files: getBuildProjectReferenceWithRootDirInParentFileMap( func(files FileMap) { - text, _ := files["/home/src/workspaces/solution/tsconfig.base.json"] + text := files["/home/src/workspaces/solution/tsconfig.base.json"] files["/home/src/workspaces/solution/tsconfig.base.json"] = strings.Replace(text.(string), `"rootDir": "./src/",`, "", 1) }, ), @@ -2514,10 +2514,10 @@ func TestBuildResolveJsonModule(t *testing.T) { tsconfigFiles: `"include": [ "src/**/*" ],`, additionalCompilerOptions: `"rootDir": "src",`, modifyFiles: func(files FileMap) { - text, _ := files["/home/src/workspaces/solution/project/src/hello.json"] + text := files["/home/src/workspaces/solution/project/src/hello.json"] delete(files, "/home/src/workspaces/solution/project/src/hello.json") files["/home/src/workspaces/solution/project/hello.json"] = text - text, _ = files["/home/src/workspaces/solution/project/src/index.ts"] + text = files["/home/src/workspaces/solution/project/src/index.ts"] files["/home/src/workspaces/solution/project/src/index.ts"] = strings.Replace(text.(string), "./hello.json", "../hello.json", 1) }, }, @@ -2525,10 +2525,10 @@ func TestBuildResolveJsonModule(t *testing.T) { subScenario: "include only with json without rootDir but outside configDirectory", tsconfigFiles: `"include": [ "src/**/*" ],`, modifyFiles: func(files FileMap) { - text, _ := files["/home/src/workspaces/solution/project/src/hello.json"] + text := files["/home/src/workspaces/solution/project/src/hello.json"] delete(files, "/home/src/workspaces/solution/project/src/hello.json") files["/home/src/workspaces/solution/hello.json"] = text - text, _ = files["/home/src/workspaces/solution/project/src/index.ts"] + text = files["/home/src/workspaces/solution/project/src/index.ts"] files["/home/src/workspaces/solution/project/src/index.ts"] = strings.Replace(text.(string), "./hello.json", "../../hello.json", 1) }, }, @@ -2540,10 +2540,10 @@ func TestBuildResolveJsonModule(t *testing.T) { subScenario: "include of json along with other include and file name matches ts file", tsconfigFiles: `"include": [ "src/**/*", "src/**/*.json" ],`, modifyFiles: func(files FileMap) { - text, _ := files["/home/src/workspaces/solution/project/src/hello.json"] + text := files["/home/src/workspaces/solution/project/src/hello.json"] delete(files, "/home/src/workspaces/solution/project/src/hello.json") files["/home/src/workspaces/solution/project/src/index.json"] = text - text, _ = files["/home/src/workspaces/solution/project/src/index.ts"] + text = files["/home/src/workspaces/solution/project/src/index.ts"] files["/home/src/workspaces/solution/project/src/index.ts"] = strings.Replace(text.(string), "./hello.json", "./index.json", 1) }, }, @@ -2937,7 +2937,7 @@ func TestBuildSample(t *testing.T) { { subScenario: "skips builds downstream projects if upstream projects have errors with stopBuildOnErrors", files: getBuildSampleFileMap(func(files FileMap) { - text, _ := files["/user/username/projects/sample1/core/index.ts"] + text := files["/user/username/projects/sample1/core/index.ts"] files["/user/username/projects/sample1/core/index.ts"] = text.(string) + `multiply();` }), cwd: "/user/username/projects/sample1", @@ -2969,7 +2969,7 @@ func TestBuildSample(t *testing.T) { "skipDefaultLibCheck": true, }, }`) - text, _ := files["/user/username/projects/sample1/core/index.ts"] + text := files["/user/username/projects/sample1/core/index.ts"] files["/user/username/projects/sample1/core/index.ts"] = text.(string) + `multiply();` }), cwd: "/user/username/projects/sample1", @@ -3152,7 +3152,7 @@ class someClass2 { }`, { subScenario: "builds correctly when project is not composite or doesnt have any references", files: getBuildSampleFileMap(func(files FileMap) { - text, _ := files["/user/username/projects/sample1/core/tsconfig.json"] + text := files["/user/username/projects/sample1/core/tsconfig.json"] files["/user/username/projects/sample1/core/tsconfig.json"] = strings.Replace(text.(string), `"composite": true,`, "", 1) }), cwd: "/user/username/projects/sample1", @@ -3332,7 +3332,7 @@ class someClass2 { }`, "target": "es5" } }`) - text, _ := files["/user/username/projects/sample1/tests/tsconfig.json"] + text := files["/user/username/projects/sample1/tests/tsconfig.json"] files["/user/username/projects/sample1/tests/tsconfig.json"] = strings.Replace(text.(string), `"references": [`, `"extends": "./tsconfig.base.json", "references": [`, 1) }), cwd: "/user/username/projects/sample1", @@ -3358,7 +3358,7 @@ class someClass2 { }`, { subScenario: "builds downstream projects even if upstream projects have errors", files: getBuildSampleFileMap(func(files FileMap) { - text, _ := files["/user/username/projects/sample1/logic/index.ts"] + text := files["/user/username/projects/sample1/logic/index.ts"] files["/user/username/projects/sample1/logic/index.ts"] = strings.Replace(text.(string), "c.multiply(10, 15)", `c.muitply()`, 1) }), cwd: "/user/username/projects/sample1", @@ -3412,7 +3412,7 @@ class someClass2 { }`, { subScenario: "when logic specifies tsBuildInfoFile", files: getBuildSampleFileMap(func(files FileMap) { - text, _ := files["/user/username/projects/sample1/logic/tsconfig.json"] + text := files["/user/username/projects/sample1/logic/tsconfig.json"] files["/user/username/projects/sample1/logic/tsconfig.json"] = strings.Replace( text.(string), `"composite": true,`, diff --git a/internal/format/api_test.go b/internal/format/api_test.go index 048d816f58..9a8a215a01 100644 --- a/internal/format/api_test.go +++ b/internal/format/api_test.go @@ -20,13 +20,13 @@ func applyBulkEdits(text string, edits []core.TextChange) string { b.Grow(len(text)) lastEnd := 0 for _, e := range edits { - start := e.TextRange.Pos() + start := e.Pos() if start != lastEnd { - b.WriteString(text[lastEnd:e.TextRange.Pos()]) + b.WriteString(text[lastEnd:e.Pos()]) } b.WriteString(e.NewText) - lastEnd = e.TextRange.End() + lastEnd = e.End() } b.WriteString(text[lastEnd:]) diff --git a/internal/format/scanner.go b/internal/format/scanner.go index 5ce691c507..71325fde5a 100644 --- a/internal/format/scanner.go +++ b/internal/format/scanner.go @@ -126,7 +126,7 @@ func (s *formattingScanner) shouldRescanJsxText(node *ast.Node) bool { if ast.IsJsxText(node) { return true } - if !ast.IsJsxElement(node) || s.hasLastTokenInfo == false { + if !ast.IsJsxElement(node) || !s.hasLastTokenInfo { return false } diff --git a/internal/format/span.go b/internal/format/span.go index 4657949f7e..555c1b5a07 100644 --- a/internal/format/span.go +++ b/internal/format/span.go @@ -123,7 +123,7 @@ func prepareRangeContainsErrorFunction(errors []*ast.Diagnostic, originalRange c return func(r core.TextRange) bool { // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. // 'index' tracks the index of the most recent error that was checked. - for true { + for { if index >= len(sorted) { // all errors in the range were already checked -> no error in specified range return false @@ -143,7 +143,6 @@ func prepareRangeContainsErrorFunction(errors []*ast.Diagnostic, originalRange c index++ } - return false // unreachable } } @@ -267,7 +266,7 @@ func (w *formatSpanWorker) execute(s *formattingScanner) []core.TextChange { w.insertIndentation(item.Loc.Pos(), indentation, false) }) - if opt.TrimTrailingWhitespace != false { + if opt.TrimTrailingWhitespace { w.trimTrailingWhitespacesForRemainingRange(remainingTrivia) } } @@ -635,7 +634,7 @@ func (w *formatSpanWorker) processPair(currentItem TextRangeWithKind, currentSta w.currentRules = w.currentRules[:0] w.currentRules = getRules(w.formattingContext, w.currentRules) - trimTrailingWhitespaces := w.formattingContext.Options.TrimTrailingWhitespace != false + trimTrailingWhitespaces := w.formattingContext.Options.TrimTrailingWhitespace lineAction := LineActionNone if len(w.currentRules) > 0 { @@ -1050,7 +1049,7 @@ func (w *formatSpanWorker) consumeTokenAndAdvanceScanner(currentTokenInfo tokenI if indentToken { tokenIndentation := -1 if isTokenInRange && !w.rangeContainsError(currentTokenInfo.token.Loc) { - tokenIndentation = dynamicIndenation.getIndentationForToken(tokenStartLine, currentTokenInfo.token.Kind, container, !!isListEndToken) + tokenIndentation = dynamicIndenation.getIndentationForToken(tokenStartLine, currentTokenInfo.token.Kind, container, isListEndToken) } indentNextTokenOrTrivia := true if len(currentTokenInfo.leadingTrivia) > 0 { @@ -1153,12 +1152,10 @@ func (i *dynamicIndenter) shouldAddDelta(line int, kind ast.Kind, container *ast case ast.KindJsxOpeningElement, ast.KindJsxClosingElement, ast.KindJsxSelfClosingElement: return false } - break case ast.KindOpenBracketToken, ast.KindCloseBracketToken: if container.Kind != ast.KindMappedType { return false } - break } // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return i.nodeStartLine != line && diff --git a/internal/fourslash/baselineutil.go b/internal/fourslash/baselineutil.go index 83e683b1d4..4dc423acc9 100644 --- a/internal/fourslash/baselineutil.go +++ b/internal/fourslash/baselineutil.go @@ -446,7 +446,7 @@ func (t *textWithContext) add(detail *baselineDetail) { if t.isLibFile { t.newContent.WriteString("--- (line: --) skipped ---\n") } else { - t.newContent.WriteString(fmt.Sprintf("--- (line: %v) skipped ---\n", locationLineIndex-t.nLinesContext+1)) + fmt.Fprintf(t.newContent, "--- (line: %v) skipped ---\n", locationLineIndex-t.nLinesContext+1) } t.newContent.WriteString(t.sliceOfContent( t.getIndex(t.lineStarts.LineStarts[locationLineIndex-t.nLinesContext+1]), @@ -586,7 +586,7 @@ func (t *textWithContext) sliceOfContent(start *int, end *int) string { return t.content[*start:*end] } -func (t *textWithContext) getIndex(i interface{}) *int { +func (t *textWithContext) getIndex(i any) *int { switch i := i.(type) { case *int: return i diff --git a/internal/ls/autoimportfixes.go b/internal/ls/autoimportfixes.go index 907f74d238..f9aebd9c2a 100644 --- a/internal/ls/autoimportfixes.go +++ b/internal/ls/autoimportfixes.go @@ -77,7 +77,7 @@ func (ct *changeTracker) doAddExistingFix( if defaultImport != nil { debug.Assert(clause.Name() == nil, "Cannot add a default import to an import clause that already has one") - ct.insertNodeAt(sourceFile, core.TextPos(astnav.GetStartOfNode(clause, sourceFile, false)), ct.NodeFactory.NewIdentifier(defaultImport.name), changeNodeOptions{suffix: ", "}) + ct.insertNodeAt(sourceFile, core.TextPos(astnav.GetStartOfNode(clause, sourceFile, false)), ct.NewIdentifier(defaultImport.name), changeNodeOptions{suffix: ", "}) } if len(namedImports) > 0 { @@ -88,10 +88,10 @@ func (ct *changeTracker) doAddExistingFix( if namedImport.propertyName != "" { identifier = ct.NodeFactory.NewIdentifier(namedImport.propertyName).AsIdentifier().AsNode() } - return ct.NodeFactory.NewImportSpecifier( + return ct.NewImportSpecifier( (!importClause.IsTypeOnly || promoteFromTypeOnly) && shouldUseTypeOnly(namedImport.addAsTypeOnly, preferences), identifier, - ct.NodeFactory.NewIdentifier(namedImport.name), + ct.NewIdentifier(namedImport.name), ) }) // !!! sort with specifierComparer @@ -137,7 +137,7 @@ func (ct *changeTracker) doAddExistingFix( } } else { if len(newSpecifiers) > 0 { - namedImports := ct.NodeFactory.NewNamedImports(ct.NodeFactory.NewNodeList(newSpecifiers)) + namedImports := ct.NewNamedImports(ct.NewNodeList(newSpecifiers)) if importClause.NamedBindings != nil { ct.replaceNode(sourceFile, importClause.NamedBindings, namedImports, nil) } else { @@ -174,9 +174,9 @@ func (ct *changeTracker) addElementToBindingPattern(sourceFile *ast.SourceFile, if len(bindingPattern.Elements()) > 0 { ct.insertNodeInListAfter(sourceFile, bindingPattern.Elements()[len(bindingPattern.Elements())-1], element, nil) } else { - ct.replaceNode(sourceFile, bindingPattern, ct.NodeFactory.NewBindingPattern( + ct.replaceNode(sourceFile, bindingPattern, ct.NewBindingPattern( ast.KindObjectBindingPattern, - ct.NodeFactory.NewNodeList([]*ast.Node{element}), + ct.NewNodeList([]*ast.Node{element}), ), nil) } } @@ -184,12 +184,12 @@ func (ct *changeTracker) addElementToBindingPattern(sourceFile *ast.SourceFile, func (ct *changeTracker) newBindingElementFromNameAndPropertyName(name string, propertyName *string) *ast.Node { var newPropertyNameIdentifier *ast.Node if propertyName != nil { - newPropertyNameIdentifier = ct.NodeFactory.NewIdentifier(*propertyName) + newPropertyNameIdentifier = ct.NewIdentifier(*propertyName) } - return ct.NodeFactory.NewBindingElement( + return ct.NewBindingElement( nil, /*dotDotDotToken*/ newPropertyNameIdentifier, - ct.NodeFactory.NewIdentifier(name), + ct.NewIdentifier(name), nil, /* initializer */ ) } @@ -241,13 +241,13 @@ func (ct *changeTracker) insertImports(sourceFile *ast.SourceFile, imports []*as func (ct *changeTracker) makeImport(defaultImport *ast.IdentifierNode, namedImports []*ast.Node, moduleSpecifier *ast.Expression, isTypeOnly bool) *ast.Statement { var newNamedImports *ast.Node if len(namedImports) > 0 { - newNamedImports = ct.NodeFactory.NewNamedImports(ct.NodeFactory.NewNodeList(namedImports)) + newNamedImports = ct.NewNamedImports(ct.NewNodeList(namedImports)) } var importClause *ast.Node if defaultImport != nil || newNamedImports != nil { - importClause = ct.NodeFactory.NewImportClause(isTypeOnly, defaultImport, newNamedImports) + importClause = ct.NewImportClause(isTypeOnly, defaultImport, newNamedImports) } - return ct.NodeFactory.NewImportDeclaration( /*modifiers*/ nil, importClause, moduleSpecifier, nil /*attributes*/) + return ct.NewImportDeclaration( /*modifiers*/ nil, importClause, moduleSpecifier, nil /*attributes*/) } func (ct *changeTracker) getNewImports( @@ -259,7 +259,7 @@ func (ct *changeTracker) getNewImports( compilerOptions *core.CompilerOptions, preferences *UserPreferences, ) []*ast.Statement { - moduleSpecifierStringLiteral := ct.NodeFactory.NewStringLiteral(moduleSpecifier) + moduleSpecifierStringLiteral := ct.NewStringLiteral(moduleSpecifier) var statements []*ast.Statement // []AnyImportSyntax if defaultImport != nil || len(namedImports) > 0 { // `verbatimModuleSyntax` should prefer top-level `import type` - @@ -271,18 +271,18 @@ func (ct *changeTracker) getNewImports( var defaultImportNode *ast.Node if defaultImport != nil { - defaultImportNode = ct.NodeFactory.NewIdentifier(defaultImport.name) + defaultImportNode = ct.NewIdentifier(defaultImport.name) } statements = append(statements, ct.makeImport(defaultImportNode, core.Map(namedImports, func(namedImport *Import) *ast.Node { var namedImportPropertyName *ast.Node if namedImport.propertyName != "" { - namedImportPropertyName = ct.NodeFactory.NewIdentifier(namedImport.propertyName) + namedImportPropertyName = ct.NewIdentifier(namedImport.propertyName) } - return ct.NodeFactory.NewImportSpecifier( + return ct.NewImportSpecifier( !topLevelTypeOnly && shouldUseTypeOnly(namedImport.addAsTypeOnly, preferences), namedImportPropertyName, - ct.NodeFactory.NewIdentifier(namedImport.name), + ct.NewIdentifier(namedImport.name), ) }), moduleSpecifierStringLiteral, topLevelTypeOnly)) } @@ -290,19 +290,19 @@ func (ct *changeTracker) getNewImports( if namespaceLikeImport != nil { var declaration *ast.Statement if namespaceLikeImport.kind == ImportKindCommonJS { - declaration = ct.NodeFactory.NewImportEqualsDeclaration( + declaration = ct.NewImportEqualsDeclaration( /*modifiers*/ nil, shouldUseTypeOnly(namespaceLikeImport.addAsTypeOnly, preferences), - ct.NodeFactory.NewIdentifier(namespaceLikeImport.name), - ct.NodeFactory.NewExternalModuleReference(moduleSpecifierStringLiteral), + ct.NewIdentifier(namespaceLikeImport.name), + ct.NewExternalModuleReference(moduleSpecifierStringLiteral), ) } else { - declaration = ct.NodeFactory.NewImportDeclaration( + declaration = ct.NewImportDeclaration( /*modifiers*/ nil, - ct.NodeFactory.NewImportClause( + ct.NewImportClause( shouldUseTypeOnly(namespaceLikeImport.addAsTypeOnly, preferences), /*name*/ nil, - ct.NodeFactory.NewNamespaceImport(ct.NodeFactory.NewIdentifier(namespaceLikeImport.name)), + ct.NewNamespaceImport(ct.NewIdentifier(namespaceLikeImport.name)), ), moduleSpecifierStringLiteral, /*attributes*/ nil, diff --git a/internal/ls/autoimports.go b/internal/ls/autoimports.go index 3b38e0d637..dfb838e453 100644 --- a/internal/ls/autoimports.go +++ b/internal/ls/autoimports.go @@ -380,9 +380,7 @@ func (l *LanguageService) getImportCompletionAction( // formatContext *formattingContext, preferences *UserPreferences, ) (string, codeAction) { - var exportInfos []*SymbolExportInfo - // `exportMapKey` should be in the `itemData` of each auto-import completion entry and sent in resolving completion entry requests - exportInfos = l.getExportInfos(ctx, ch, sourceFile, preferences, exportMapKey) + exportInfos := l.getExportInfos(ctx, ch, sourceFile, preferences, exportMapKey) if len(exportInfos) == 0 { panic("Some exportInfo should match the specified exportMapKey") } diff --git a/internal/ls/changetrackerimpl.go b/internal/ls/changetrackerimpl.go index e8f3d13e69..e28a2c0093 100644 --- a/internal/ls/changetrackerimpl.go +++ b/internal/ls/changetrackerimpl.go @@ -25,7 +25,7 @@ func (ct *changeTracker) getTextChangesFromChanges() map[string][]*lsproto.TextE slices.SortStableFunc(changesInFile, func(a, b *trackerEdit) int { return CompareRanges(ptrTo(a.Range), ptrTo(b.Range)) }) // verify that change intervals do not overlap, except possibly at end points. for i := range len(changesInFile) - 1 { - if ComparePositions(changesInFile[i].Range.End, changesInFile[i+1].Range.Start) > 0 { + if ComparePositions(changesInFile[i].Range.End, changesInFile[i+1].Start) > 0 { // assert change[i].End <= change[i + 1].Start panic(fmt.Sprintf("changes overlap: %v and %v", changesInFile[i].Range, changesInFile[i+1].Range)) } @@ -61,7 +61,7 @@ func (ct *changeTracker) computeNewText(change *trackerEdit, targetSourceFile *a return change.NewText } - pos := int(ct.ls.converters.LineAndCharacterToPosition(sourceFile, change.Range.Start)) + pos := int(ct.ls.converters.LineAndCharacterToPosition(sourceFile, change.Start)) formatNode := func(n *ast.Node) string { return ct.getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, change.options) } @@ -302,7 +302,7 @@ func (ct *changeTracker) getAdjustedEndPosition(sourceFile *ast.SourceFile, node // ============= utilities ============= func hasCommentsBeforeLineBreak(text string, start int) bool { - for _, ch := range []rune(text[start:]) { + for _, ch := range text[start:] { if !stringutil.IsWhiteSpaceSingleLine(ch) { return ch == '/' } diff --git a/internal/ls/completions.go b/internal/ls/completions.go index 6966553a1e..2ec3c00dc8 100644 --- a/internal/ls/completions.go +++ b/internal/ls/completions.go @@ -1128,6 +1128,7 @@ func (l *LanguageService) getCompletionData( symbols = append(symbols, filteredMembers...) // Set sort texts. + //nolint:staticcheck transformObjectLiteralMembers := ptrIsTrue(preferences.IncludeCompletionsWithObjectLiteralMethodSnippets) && objectLikeContainer.Kind == ast.KindObjectLiteralExpression for _, member := range filteredMembers { @@ -3346,7 +3347,7 @@ func charactersFuzzyMatchInString(identifierString string, lowercaseCharacters s lowerCaseRunes := []rune(lowercaseCharacters) testChar := lowerCaseRunes[characterIndex] - for _, strChar := range []rune(identifierString) { + for _, strChar := range identifierString { if strChar == testChar || strChar == unicode.ToUpper(testChar) { willMatchFirstChar := prevChar == 0 || // Beginning of word 'a' <= prevChar && prevChar <= 'z' && 'A' <= strChar && strChar <= 'Z' || // camelCase transition diff --git a/internal/ls/hover.go b/internal/ls/hover.go index a608fdf024..556cbd2580 100644 --- a/internal/ls/hover.go +++ b/internal/ls/hover.go @@ -316,7 +316,7 @@ func writeSignatures(b *strings.Builder, c *checker.Checker, signatures []*check b.WriteString("\n") } if i == 3 && len(signatures) >= 5 { - b.WriteString(fmt.Sprintf("// +%v more overloads", len(signatures)-3)) + fmt.Fprintf(b, "// +%v more overloads", len(signatures)-3) break } b.WriteString(prefix) diff --git a/internal/ls/signaturehelp.go b/internal/ls/signaturehelp.go index 09284f9594..d3e7b7973a 100644 --- a/internal/ls/signaturehelp.go +++ b/internal/ls/signaturehelp.go @@ -1049,9 +1049,8 @@ func getContextualSignatureLocationInfo(node *ast.Node, sourceFile *ast.SourceFi case ast.KindBinaryExpression: highestBinary := getHighestBinary(parent.AsBinaryExpression()) contextualType := c.GetContextualType(highestBinary.AsNode(), checker.ContextFlagsNone) - argumentIndex := 0 if node.Kind != ast.KindOpenParenToken { - argumentIndex = countBinaryExpressionParameters(parent.AsBinaryExpression()) - 1 + argumentIndex := countBinaryExpressionParameters(parent.AsBinaryExpression()) - 1 argumentCount := countBinaryExpressionParameters(highestBinary) if contextualType != nil { return &contextualSignatureLocationInfo{ diff --git a/internal/ls/utilities.go b/internal/ls/utilities.go index d0078ba56d..57cf740cd4 100644 --- a/internal/ls/utilities.go +++ b/internal/ls/utilities.go @@ -684,7 +684,7 @@ func isLabelOfLabeledStatement(node *ast.Node) bool { } func findReferenceInPosition(refs []*ast.FileReference, pos int) *ast.FileReference { - return core.Find(refs, func(ref *ast.FileReference) bool { return ref.TextRange.ContainsInclusive(pos) }) + return core.Find(refs, func(ref *ast.FileReference) bool { return ref.ContainsInclusive(pos) }) } func isTagName(node *ast.Node) bool { @@ -908,7 +908,7 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // specially by `getSymbolAtLocation`. isModifier := func(node *ast.Node) bool { if ast.IsModifier(node) && (forRename || node.Kind != ast.KindDefaultKeyword) { - return ast.CanHaveModifiers(parent) && slices.Contains(parent.Modifiers().NodeList.Nodes, node) + return ast.CanHaveModifiers(parent) && slices.Contains(parent.Modifiers().Nodes, node) } switch node.Kind { case ast.KindClassKeyword: @@ -1146,7 +1146,7 @@ func getAdjustedLocationForDeclaration(node *ast.Node, forRename bool, sourceFil // for class and function declarations, use the `default` modifier // when the declaration is unnamed. if node.Modifiers() != nil { - return core.Find(node.Modifiers().NodeList.Nodes, func(*ast.Node) bool { return node.Kind == ast.KindDefaultKeyword }) + return core.Find(node.Modifiers().Nodes, func(*ast.Node) bool { return node.Kind == ast.KindDefaultKeyword }) } case ast.KindClassExpression: // for class expressions, use the `class` keyword when the class is unnamed diff --git a/internal/modulespecifiers/specifiers.go b/internal/modulespecifiers/specifiers.go index 1f8e26b040..1f8806e7f2 100644 --- a/internal/modulespecifiers/specifiers.go +++ b/internal/modulespecifiers/specifiers.go @@ -706,7 +706,7 @@ func tryGetModuleNameAsNodeModule( if !packageNameOnly { packageRootIndex := parts.PackageRootIndex var moduleFileName string - for true { + for { // If the module could be imported by a directory name, use that directory's name pkgJsonResults := tryDirectoryWithPackageJson( *parts, @@ -815,14 +815,14 @@ func tryDirectoryWithPackageJson( conditions := module.GetConditions(options, importMode) var fromExports string - if packageJsonContent != nil && packageJsonContent.Fields.Exports.Type != packagejson.JSONValueTypeNotPresent { + if packageJsonContent != nil && packageJsonContent.Exports.Type != packagejson.JSONValueTypeNotPresent { fromExports = tryGetModuleNameFromExports( options, host, pathObj.FileName, packageRootPath, packageName, - packageJsonContent.Fields.Exports, + packageJsonContent.Exports, conditions, ) } @@ -832,7 +832,7 @@ func tryDirectoryWithPackageJson( verbatimFromExports: true, } } - if packageJsonContent != nil && packageJsonContent.Fields.Exports.Type != packagejson.JSONValueTypeNotPresent { + if packageJsonContent != nil && packageJsonContent.Exports.Type != packagejson.JSONValueTypeNotPresent { return pkgJsonDirAttemptResult{ moduleFileToTry: pathObj.FileName, blockedByExports: true, @@ -969,7 +969,7 @@ func tryGetModuleNameFromPackageJsonImports( return "" } - imports := info.GetContents().Fields.Imports + imports := info.GetContents().Imports switch imports.Type { case packagejson.JSONValueTypeNotPresent, packagejson.JSONValueTypeArray, packagejson.JSONValueTypeString: return "" // not present or invalid for imports diff --git a/internal/packagejson/cache.go b/internal/packagejson/cache.go index 7b72a4e3e9..04a474c709 100644 --- a/internal/packagejson/cache.go +++ b/internal/packagejson/cache.go @@ -21,12 +21,12 @@ 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 { p.versionTraces = append(p.versionTraces, diagnostics.X_package_json_does_not_have_a_0_field.Format("typesVersions")) return } - if p.Fields.TypesVersions.Type != JSONValueTypeObject { - p.versionTraces = append(p.versionTraces, diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2.Format("typesVersions", "object", p.Fields.TypesVersions.Type.String())) + if p.TypesVersions.Type != JSONValueTypeObject { + p.versionTraces = append(p.versionTraces, 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 f3f7fd6912..e6988a697c 100644 --- a/internal/parser/jsdoc.go +++ b/internal/parser/jsdoc.go @@ -1167,7 +1167,7 @@ func (p *Parser) parseOptionalJsdoc(t ast.Kind) bool { } func (p *Parser) parseJSDocEntityName() *ast.EntityName { - var entity *ast.EntityName = 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/parser/parser.go b/internal/parser/parser.go index 8ced9412b8..e0e8db1f0a 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -6449,7 +6449,7 @@ func (p *Parser) processPragmasIntoFields(context *ast.SourceFile) { 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/project/configfileregistrybuilder.go b/internal/project/configfileregistrybuilder.go index 725bc343a8..9ee74909ef 100644 --- a/internal/project/configfileregistrybuilder.go +++ b/internal/project/configfileregistrybuilder.go @@ -168,15 +168,11 @@ func (c *configFileRegistryBuilder) updateRootFilesWatch(fileName string, entry wildcardGlobs := entry.commandLine.WildcardDirectories() rootFileGlobs := make([]string, 0, len(wildcardGlobs)+1+len(entry.commandLine.ExtendedSourceFiles())) rootFileGlobs = append(rootFileGlobs, fileName) - for _, extendedConfig := range entry.commandLine.ExtendedSourceFiles() { - rootFileGlobs = append(rootFileGlobs, extendedConfig) - } + rootFileGlobs = append(rootFileGlobs, entry.commandLine.ExtendedSourceFiles()...) for dir, recursive := range wildcardGlobs { rootFileGlobs = append(rootFileGlobs, fmt.Sprintf("%s/%s", tspath.NormalizePath(dir), core.IfElse(recursive, recursiveFileGlobPattern, fileGlobPattern))) } - for _, fileName := range entry.commandLine.LiteralFileNames() { - rootFileGlobs = append(rootFileGlobs, fileName) - } + rootFileGlobs = append(rootFileGlobs, entry.commandLine.LiteralFileNames()...) slices.Sort(rootFileGlobs) entry.rootFilesWatch = entry.rootFilesWatch.Clone(rootFileGlobs) diff --git a/internal/project/project.go b/internal/project/project.go index 6354e0ab30..39706d88df 100644 --- a/internal/project/project.go +++ b/internal/project/project.go @@ -350,12 +350,12 @@ func (p *Project) toPath(fileName string) tspath.Path { } func (p *Project) print(writeFileNames bool, writeFileExplanation bool, builder *strings.Builder) string { - builder.WriteString(fmt.Sprintf("\nProject '%s'\n", p.Name())) + fmt.Fprintf(builder, "\nProject '%s'\n", p.Name()) if p.Program == nil { builder.WriteString("\tFiles (0) NoProgram\n") } else { sourceFiles := p.Program.GetSourceFiles() - builder.WriteString(fmt.Sprintf("\tFiles (%d)\n", len(sourceFiles))) + fmt.Fprintf(builder, "\tFiles (%d)\n", len(sourceFiles)) if writeFileNames { for _, sourceFile := range sourceFiles { builder.WriteString("\t\t" + sourceFile.FileName() + "\n") diff --git a/internal/project/refcounting_test.go b/internal/project/refcounting_test.go index eef05a7898..9c7a341910 100644 --- a/internal/project/refcounting_test.go +++ b/internal/project/refcounting_test.go @@ -99,7 +99,7 @@ func TestRefCountingCaches(t *testing.T) { assert.NilError(t, err) assert.Equal(t, utilsEntry.refCount, 1) assert.Equal(t, mainEntry.refCount, 0) - mainEntry, ok := session.parseCache.entries.Load(newParseCacheKey(main.ParseOptions(), main.ScriptKind)) + _, ok := session.parseCache.entries.Load(newParseCacheKey(main.ParseOptions(), main.ScriptKind)) assert.Equal(t, ok, false) }) }) diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index 90ef2f1aef..084e1526e6 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -1368,10 +1368,8 @@ func (s *Scanner) ScanJSDocToken() ast.Kind { if IsIdentifierStart(ch) { char := ch - for { - if s.pos >= len(s.text) { - break - } + for s.pos < len(s.text) { + char, size = s.charAndSize() if !IsIdentifierPart(char) && char != '-' { break diff --git a/internal/testutil/harnessutil/sourcemap_recorder.go b/internal/testutil/harnessutil/sourcemap_recorder.go index d5d6521673..17c31bc1f4 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/projecttestutil/projecttestutil.go b/internal/testutil/projecttestutil/projecttestutil.go index 169709d42c..eea0137f98 100644 --- a/internal/testutil/projecttestutil/projecttestutil.go +++ b/internal/testutil/projecttestutil/projecttestutil.go @@ -176,7 +176,7 @@ func (h *SessionUtils) appendTypesRegistryConfig(builder *strings.Builder, index if index > 0 { builder.WriteString(",") } - builder.WriteString(fmt.Sprintf("\n \"%s\": {%s\n }", entry, TypesRegistryConfigText())) + fmt.Fprintf(builder, "\n \"%s\": {%s\n }", entry, TypesRegistryConfigText()) } func Setup(files map[string]any) (*project.Session, *SessionUtils) { diff --git a/internal/testutil/tsbaseline/error_baseline.go b/internal/testutil/tsbaseline/error_baseline.go index 1490c267e5..03786b72b7 100644 --- a/internal/testutil/tsbaseline/error_baseline.go +++ b/internal/testutil/tsbaseline/error_baseline.go @@ -96,7 +96,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/testutil/tsbaseline/sourcemap_baseline.go b/internal/testutil/tsbaseline/sourcemap_baseline.go index 903c189dee..948f3f254a 100644 --- a/internal/testutil/tsbaseline/sourcemap_baseline.go +++ b/internal/testutil/tsbaseline/sourcemap_baseline.go @@ -87,11 +87,10 @@ 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 { + 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/transformers/declarations/transform.go b/internal/transformers/declarations/transform.go index 02bb0d9d41..2ff2580e26 100644 --- a/internal/transformers/declarations/transform.go +++ b/internal/transformers/declarations/transform.go @@ -223,10 +223,7 @@ func (tx *DeclarationTransformer) transformAndReplaceLatePaintedStatements(state // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. - for true { - if len(tx.state.lateMarkedStatements) == 0 { - break - } + for len(tx.state.lateMarkedStatements) != 0 { next := tx.state.lateMarkedStatements[0] tx.state.lateMarkedStatements = tx.state.lateMarkedStatements[1:] @@ -1231,7 +1228,7 @@ func (tx *DeclarationTransformer) transformModuleDeclaration(input *ast.ModuleDe // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) original := tx.EmitContext().MostOriginal(inner) id := ast.GetNodeId(original) - body, _ := tx.lateStatementReplacementMap[id] + body := tx.lateStatementReplacementMap[id] delete(tx.lateStatementReplacementMap, id) return tx.Factory().UpdateModuleDeclaration( input, diff --git a/internal/transformers/declarations/util.go b/internal/transformers/declarations/util.go index e6d71f5697..515fa58ff1 100644 --- a/internal/transformers/declarations/util.go +++ b/internal/transformers/declarations/util.go @@ -134,10 +134,7 @@ func isEnclosingDeclaration(node *ast.Node) bool { } func isAlwaysType(node *ast.Node) bool { - if node.Kind == ast.KindInterfaceDeclaration { - return true - } - return false + return node.Kind == ast.KindInterfaceDeclaration } func maskModifierFlags(host DeclarationEmitHost, node *ast.Node, modifierMask ast.ModifierFlags, modifierAdditions ast.ModifierFlags) ast.ModifierFlags { diff --git a/internal/transformers/estransforms/namedevaluation.go b/internal/transformers/estransforms/namedevaluation.go index e35851b39c..6ce13ce02e 100644 --- a/internal/transformers/estransforms/namedevaluation.go +++ b/internal/transformers/estransforms/namedevaluation.go @@ -74,14 +74,12 @@ func isAnonymousFunctionDefinition(emitContext *printer.EmitContext, node *ast.E if classHasDeclaredOrExplicitlyAssignedName(emitContext, node) { return false } - break case ast.KindFunctionExpression: if node.AsFunctionExpression().Name() != nil { return false } - break case ast.KindArrowFunction: - break + // Do nothing. default: return false } @@ -111,7 +109,6 @@ func isNamedEvaluationSource(node *ast.Node) bool { case ast.KindEqualsToken, ast.KindAmpersandAmpersandEqualsToken, ast.KindBarBarEqualsToken, ast.KindQuestionQuestionEqualsToken: return ast.IsIdentifier(node.AsBinaryExpression().Left) } - break case ast.KindExportAssignment: return true } diff --git a/internal/transformers/jsxtransforms/jsx.go b/internal/transformers/jsxtransforms/jsx.go index 1b8be9984f..008dca457f 100644 --- a/internal/transformers/jsxtransforms/jsx.go +++ b/internal/transformers/jsxtransforms/jsx.go @@ -840,22 +840,22 @@ var htmlEntityMatcher = regexp2.MustCompile(`&((#((\d+)|x([\da-fA-F]+)))|(\w+)); func htmlEntityReplacer(m regexp2.Match) string { decimal := m.GroupByNumber(4) - if decimal != nil && decimal.Capture.String() != "" { - parsed, err := strconv.ParseInt(decimal.Capture.String(), 10, 32) + if decimal != nil && decimal.String() != "" { + parsed, err := strconv.ParseInt(decimal.String(), 10, 32) if err == nil { return string(rune(parsed)) } } hex := m.GroupByNumber(5) - if hex != nil && hex.Capture.String() != "" { - parsed, err := strconv.ParseInt(hex.Capture.String(), 16, 32) + if hex != nil && hex.String() != "" { + parsed, err := strconv.ParseInt(hex.String(), 16, 32) if err == nil { return string(rune(parsed)) } } word := m.GroupByNumber(6) - if word != nil && word.Capture.String() != "" { - res, ok := entities[word.Capture.String()] + if word != nil && word.String() != "" { + res, ok := entities[word.String()] if ok { return string(res) } diff --git a/internal/tsoptions/tsconfigparsing.go b/internal/tsoptions/tsconfigparsing.go index 9ccef5af8d..ad58c29573 100644 --- a/internal/tsoptions/tsconfigparsing.go +++ b/internal/tsoptions/tsconfigparsing.go @@ -560,7 +560,7 @@ type CommandLineOptionNameMap map[string]*CommandLineOption func (m CommandLineOptionNameMap) Get(name string) *CommandLineOption { opt, ok := m[name] if !ok { - opt, _ = m[strings.ToLower(name)] + opt = m[strings.ToLower(name)] } return opt } @@ -1073,7 +1073,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{ + result := &extendsResult{ options: &core.CompilerOptions{}, } if reflect.TypeOf(ownConfig.extendedConfigPath).Kind() == reflect.String { @@ -1606,7 +1606,6 @@ func getFileNamesFromConfigSpecs( host vfs.FS, extraFileExtensions []FileExtensionInfo, ) ([]string, int) { - 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 4f57b5068f..f1a4e8ce02 100644 --- a/internal/tsoptions/tsconfigparsing_test.go +++ b/internal/tsoptions/tsconfigparsing_test.go @@ -154,9 +154,8 @@ func TestParseConfigFileTextToJson(t *testing.T) { } type parseJsonConfigTestCase struct { - title string - noSubmoduleBaseline bool - input []testConfig + title string + input []testConfig } var parseJsonConfigFileTests = []parseJsonConfigTestCase{ @@ -234,8 +233,7 @@ var parseJsonConfigFileTests = []parseJsonConfigTestCase{ }}, }, { - 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 = []parseJsonConfigTestCase{ }}, }, { - 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 = []parseJsonConfigTestCase{ }}, }, { - 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 = []parseJsonConfigTestCase{ }}, }, { - title: "handles empty types array", - noSubmoduleBaseline: true, + title: "handles empty types array", input: []testConfig{{ jsonText: `{ "compilerOptions": { @@ -510,8 +505,7 @@ var parseJsonConfigFileTests = []parseJsonConfigTestCase{ }}, }, { - title: "issue 1267 scenario - extended files not picked up", - noSubmoduleBaseline: true, + title: "issue 1267 scenario - extended files not picked up", input: []testConfig{{ jsonText: `{ "extends": "./tsconfig-base/backend.json", @@ -580,8 +574,7 @@ export {}`, }}, }, { - title: "null overrides in extended tsconfig - array fields", - noSubmoduleBaseline: true, + title: "null overrides in extended tsconfig - array fields", input: []testConfig{{ jsonText: `{ "extends": "./tsconfig-base.json", @@ -606,8 +599,7 @@ export {}`, }}, }, { - title: "null overrides in extended tsconfig - string fields", - noSubmoduleBaseline: true, + title: "null overrides in extended tsconfig - string fields", input: []testConfig{{ jsonText: `{ "extends": "./tsconfig-base.json", @@ -632,8 +624,7 @@ export {}`, }}, }, { - title: "null overrides in extended tsconfig - mixed field types", - noSubmoduleBaseline: true, + title: "null overrides in extended tsconfig - mixed field types", input: []testConfig{{ jsonText: `{ "extends": "./tsconfig-base.json", @@ -663,8 +654,7 @@ export {}`, }}, }, { - title: "null overrides with multiple extends levels", - noSubmoduleBaseline: true, + title: "null overrides with multiple extends levels", input: []testConfig{{ jsonText: `{ "extends": "./tsconfig-middle.json", @@ -696,8 +686,7 @@ export {}`, }}, }, { - title: "null overrides in middle level of extends chain", - noSubmoduleBaseline: true, + title: "null overrides in middle level of extends chain", input: []testConfig{{ jsonText: `{ "extends": "./tsconfig-middle.json", @@ -771,7 +760,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, getParsedWithJsonApi) + baselineParseConfigWith(t, rec.title+" with json api.js", rec.input, getParsedWithJsonApi) }) } } @@ -798,7 +787,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, getParsedWithJsonSourceFileApi) + baselineParseConfigWith(t, rec.title+" with jsonSourceFile api.js", rec.input, getParsedWithJsonSourceFileApi) }) } } @@ -825,8 +814,8 @@ func getParsedWithJsonSourceFileApi(config testConfig, host tsoptions.ParseConfi ) } -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, 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 @@ -974,12 +963,12 @@ func TestParseTypeAcquisition(t *testing.T) { } t.Run(withJsonApiName, func(t *testing.T) { t.Parallel() - baselineParseConfigWith(t, withJsonApiName+".js", true, input, getParsedWithJsonApi) + baselineParseConfigWith(t, withJsonApiName+".js", input, getParsedWithJsonApi) }) withJsonSourceFileApiName := test.title + " with jsonSourceFile api" t.Run(withJsonSourceFileApiName, func(t *testing.T) { t.Parallel() - baselineParseConfigWith(t, withJsonSourceFileApiName+".js", true, input, getParsedWithJsonSourceFileApi) + baselineParseConfigWith(t, withJsonSourceFileApiName+".js", input, getParsedWithJsonSourceFileApi) }) } }