diff --git a/.golangci.yml b/.golangci.yml index cb70f3e2fe1..398be3bca19 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -41,6 +41,7 @@ linters: - perfsprint - predeclared - reassign + - staticcheck - testableexamples - tparallel - unconvert @@ -55,7 +56,6 @@ linters: # - gocritic # - gosec # - revive - # - staticcheck # - testifylint # - unparam # - unused @@ -87,6 +87,21 @@ linters: msg: a host implementation should likely be used instead pkg: ^runtime$ + staticcheck: + checks: + - all + - -QF1001 # Apply De Morgan’s law + - -QF1003 # Convert if/else-if chain to tagged switch + - -SA1019 # Using a deprecated function, variable, constant or field + - -SA9003 # Empty body in an if or else branch + - -ST1000 # Incorrect or missing package comment + - -ST1003 # Poorly chosen identifier + - -ST1006 # Poorly chosen receiver name + - -ST1016 # Use consistent method receiver names + - -ST1020 # The documentation of an exported function should start with the function’s name + - -ST1021 # The documentation of an exported type should start with type’s name + - -ST1022 # The documentation of an exported variable or constant should start with variable’s name + exclusions: rules: - path: internal/fourslash/tests/gen/ diff --git a/internal/api/encoder/encoder_test.go b/internal/api/encoder/encoder_test.go index f676bf9eebd..cda8fc68162 100644 --- a/internal/api/encoder/encoder_test.go +++ b/internal/api/encoder/encoder_test.go @@ -104,7 +104,7 @@ func formatEncodedSourceFile(encoded []byte) string { strStart := readUint32(encoded, int(offsetStringOffsets+stringIndex*4)) strEnd := readUint32(encoded, int(offsetStringOffsets+stringIndex*4)+4) str := string(encoded[offsetStrings+strStart : offsetStrings+strEnd]) - result.WriteString(fmt.Sprintf(" \"%s\"", str)) + fmt.Fprintf(&result, " \"%s\"", str) } fmt.Fprintf(&result, " [%d, %d), i=%d, next=%d", pos, end, j, encoded[i+encoder.NodeOffsetNext]) result.WriteString("\n") diff --git a/internal/astnav/tokens_test.go b/internal/astnav/tokens_test.go index 896bfc17da1..7198c504c90 100644 --- a/internal/astnav/tokens_test.go +++ b/internal/astnav/tokens_test.go @@ -408,23 +408,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 7fddd97b36d..d4a35330462 100644 --- a/internal/binder/binder.go +++ b/internal/binder/binder.go @@ -249,7 +249,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 } @@ -264,7 +264,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().Text()+" }")) } for index, declaration := range symbol.Declarations { - var decl *ast.Node = ast.GetNameOfDeclaration(declaration) + decl := ast.GetNameOfDeclaration(declaration) if decl == nil { decl = declaration } @@ -2061,7 +2061,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].Statements()) == 0 && i+1 < len(clauses) { diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 47c9b298f18..c03d69b2dfa 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -10510,10 +10510,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 @@ -13382,7 +13382,7 @@ func (c *Checker) isReadonlyAssignmentDeclaration(node *ast.Node) bool { } else { writableType = c.getTypeOfSymbol(writableProp) } - return writableType.flags&TypeFlagsBooleanLiteral != 0 && getBooleanLiteralValue(writableType) == false + return writableType.flags&TypeFlagsBooleanLiteral != 0 && !getBooleanLiteralValue(writableType) } return true } @@ -14959,10 +14959,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") @@ -15694,10 +15694,8 @@ func (c *Checker) getExportsOfModuleWorker(moduleSymbol *ast.Symbol) (exports as return symbols } var originalModule *ast.Symbol - if moduleSymbol != nil { - if c.resolveSymbolEx(moduleSymbol.Exports[ast.InternalSymbolNameExportEquals], false /*dontResolveAlias*/) != nil { - originalModule = moduleSymbol - } + if c.resolveSymbolEx(moduleSymbol.Exports[ast.InternalSymbolNameExportEquals], false /*dontResolveAlias*/) != nil { + originalModule = moduleSymbol } // A module defined by an 'export=' consists of one export that needs to be resolved moduleSymbol = c.resolveExternalModuleSymbol(moduleSymbol, false /*dontResolveAlias*/) @@ -16471,7 +16469,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 { @@ -18097,12 +18095,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}) @@ -19581,7 +19579,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) @@ -20606,7 +20604,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] @@ -28809,10 +28807,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 @@ -30249,10 +30247,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 651010ad69a..9a7df5c0495 100644 --- a/internal/checker/flow.go +++ b/internal/checker/flow.go @@ -1987,7 +1987,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 a40444de1f1..2eab62f7f95 100644 --- a/internal/checker/grammarchecks.go +++ b/internal/checker/grammarchecks.go @@ -1485,7 +1485,7 @@ func (c *Checker) checkGrammarMethod(node *ast.Node /*Union[MethodDeclaration, M func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { targetLabel := node.Label() - 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) @@ -1798,14 +1798,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 0fc55a821ae..1f8b499cff8 100644 --- a/internal/checker/inference.go +++ b/internal/checker/inference.go @@ -575,10 +575,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 d5cad0b4524..52654b1e32e 100644 --- a/internal/checker/jsx.go +++ b/internal/checker/jsx.go @@ -818,7 +818,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 b6621ad5481..e5bca1bf2b3 100644 --- a/internal/checker/nodebuilderimpl.go +++ b/internal/checker/nodebuilderimpl.go @@ -190,7 +190,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) } @@ -199,7 +199,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() @@ -1351,7 +1351,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 @@ -1788,47 +1788,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") @@ -1870,7 +1870,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 { @@ -2707,7 +2707,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) @@ -2721,7 +2721,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 b669f55222a..4c396102458 100644 --- a/internal/checker/relater.go +++ b/internal/checker/relater.go @@ -4478,10 +4478,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/services.go b/internal/checker/services.go index 83904ee0c28..01793b1b3f3 100644 --- a/internal/checker/services.go +++ b/internal/checker/services.go @@ -690,7 +690,7 @@ func (c *Checker) getTypeParameterConstraintForPositionAcrossSignatures(signatur } func (c *Checker) getTypeArgumentConstraint(node *ast.Node) *Type { - var typeArgumentPosition int = -1 + typeArgumentPosition := -1 if ast.HasTypeArguments(node.Parent) { typeArgs := node.Parent.TypeArguments() for i, arg := range typeArgs { diff --git a/internal/checker/symbolaccessibility.go b/internal/checker/symbolaccessibility.go index 8c749b55ea1..a624a652378 100644 --- a/internal/checker/symbolaccessibility.go +++ b/internal/checker/symbolaccessibility.go @@ -596,10 +596,8 @@ func (c *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 d7d592cb448..9709d42e24c 100644 --- a/internal/checker/utilities.go +++ b/internal/checker/utilities.go @@ -1650,7 +1650,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 c191430535c..3b461801c7c 100644 --- a/internal/collections/syncmap.go +++ b/internal/collections/syncmap.go @@ -80,10 +80,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 89475189fef..e602bd49b25 100644 --- a/internal/collections/syncset.go +++ b/internal/collections/syncset.go @@ -68,10 +68,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 58fd18251ed..8b6db61ff59 100644 --- a/internal/compiler/projectreferencefilemapper.go +++ b/internal/compiler/projectreferencefilemapper.go @@ -54,7 +54,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) } } @@ -131,7 +131,7 @@ func (mapper *projectReferenceFileMapper) rangeResolvedReferenceWorker( if !seenRef.AddIfAbsent(path) { continue } - config, _ := mapper.configToProjectReference[path] + config := mapper.configToProjectReference[path] if !f(path, config, parent, index) { return false } diff --git a/internal/core/textchange.go b/internal/core/textchange.go index 9945af4f702..904ebe9948b 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/execute/build/orchestrator.go b/internal/execute/build/orchestrator.go index c3658cec210..bc0f42d767d 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 c76fbbee73d..836820cdbe5 100644 --- a/internal/execute/incremental/snapshot.go +++ b/internal/execute/incremental/snapshot.go @@ -404,10 +404,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(string(diagnostic.MessageKey())) builder.WriteString("\n") for _, arg := range diagnostic.MessageArgs() { diff --git a/internal/execute/tsctests/runner.go b/internal/execute/tsctests/runner.go index 8adfca02233..5f940abe328 100644 --- a/internal/execute/tsctests/runner.go +++ b/internal/execute/tsctests/runner.go @@ -89,7 +89,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) } @@ -117,14 +117,14 @@ 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.WriteString(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)) + fmt.Fprintf(&unexpectedDiff, "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)) - unexpectedDiff.WriteString(fmt.Sprintf("Edit [%d]:: %s\n!!! Diff not found but explanation present, please review and remove the explanation !!!\n", index, do.caption)) + fmt.Fprintf(baselineBuilder, "\n\nDiff:: %s !!! Diff not found but explanation present, please review and remove the explanation !!!\n", do.expectedDiff) + fmt.Fprintf(&unexpectedDiff, "Edit [%d]:: %s\n!!! Diff not found but explanation present, please review and remove the explanation !!!\n", index, do.caption) } } baseline.Run(t, strings.ReplaceAll(test.subScenario, " ", "-")+".js", baselineBuilder.String(), baseline.Options{Subfolder: filepath.Join(test.getBaselineSubFolder(), scenario)}) diff --git a/internal/execute/tsctests/tscbuild_test.go b/internal/execute/tsctests/tscbuild_test.go index d9b0391219f..6d15100c4eb 100644 --- a/internal/execute/tsctests/tscbuild_test.go +++ b/internal/execute/tsctests/tscbuild_test.go @@ -2438,7 +2438,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) }, ), @@ -2685,10 +2685,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) }, }, @@ -2696,10 +2696,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) }, }, @@ -2711,10 +2711,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) }, }, @@ -3108,7 +3108,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", @@ -3140,7 +3140,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", @@ -3323,7 +3323,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", @@ -3503,7 +3503,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", @@ -3529,7 +3529,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", @@ -3583,7 +3583,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 28600b6cf1f..4609c328e6b 100644 --- a/internal/format/api_test.go +++ b/internal/format/api_test.go @@ -21,13 +21,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 ef9ab0d7270..5d9d5e460c3 100644 --- a/internal/format/scanner.go +++ b/internal/format/scanner.go @@ -127,7 +127,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 1f448da00f8..7996c51e78e 100644 --- a/internal/format/span.go +++ b/internal/format/span.go @@ -127,7 +127,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 @@ -147,7 +147,6 @@ func prepareRangeContainsErrorFunction(errors []*ast.Diagnostic, originalRange c index++ } - return false // unreachable } } @@ -1074,7 +1073,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 { @@ -1180,12 +1179,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 a830e2ed9d0..3b55cff83ff 100644 --- a/internal/fourslash/baselineutil.go +++ b/internal/fourslash/baselineutil.go @@ -1012,7 +1012,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]), @@ -1120,7 +1120,7 @@ func annotateContentWithTooltips[T comparable]( builder := strings.Builder{} seenFirst := false for fileName, lines := range filesToLines.Entries() { - builder.WriteString(fmt.Sprintf("=== %s ===\n", fileName)) + fmt.Fprintf(&builder, "=== %s ===\n", fileName) for _, line := range lines { builder.WriteString("// ") builder.WriteString(line) diff --git a/internal/fourslash/fourslash.go b/internal/fourslash/fourslash.go index 32ba291f72d..eb2babdb342 100644 --- a/internal/fourslash/fourslash.go +++ b/internal/fourslash/fourslash.go @@ -2487,12 +2487,12 @@ func formatCallHierarchyItem( } trailingPrefix := prefix - result.WriteString(fmt.Sprintf("%s╭ name: %s\n", prefix, callHierarchyItem.Name)) - result.WriteString(fmt.Sprintf("%s├ kind: %s\n", prefix, symbolKindToLowercase(callHierarchyItem.Kind))) + fmt.Fprintf(result, "%s╭ name: %s\n", prefix, callHierarchyItem.Name) + fmt.Fprintf(result, "%s├ kind: %s\n", prefix, symbolKindToLowercase(callHierarchyItem.Kind)) if callHierarchyItem.Detail != nil && *callHierarchyItem.Detail != "" { - result.WriteString(fmt.Sprintf("%s├ containerName: %s\n", prefix, *callHierarchyItem.Detail)) + fmt.Fprintf(result, "%s├ containerName: %s\n", prefix, *callHierarchyItem.Detail) } - result.WriteString(fmt.Sprintf("%s├ file: %s\n", prefix, callHierarchyItem.Uri.FileName())) + fmt.Fprintf(result, "%s├ file: %s\n", prefix, callHierarchyItem.Uri.FileName()) result.WriteString(prefix) result.WriteString("├ span:\n") formatCallHierarchyItemSpan(f, file, result, callHierarchyItem.Range, prefix+"│ ", prefix+"│ ") @@ -2608,7 +2608,7 @@ func formatCallHierarchyItemSpan( // Calculate line number padding lineNumWidth := len(strconv.Itoa(contextEndLine+1)) + 2 - result.WriteString(fmt.Sprintf("%s╭ %s:%d:%d-%d:%d\n", prefix, file.fileName, startLc.Line+1, startLc.Character+1, endLc.Line+1, endLc.Character+1)) + fmt.Fprintf(result, "%s╭ %s:%d:%d-%d:%d\n", prefix, file.fileName, startLc.Line+1, startLc.Character+1, endLc.Line+1, endLc.Character+1) for lineNum := contextStartLine; lineNum <= contextEndLine; lineNum++ { lineStart := lineStarts[lineNum] @@ -2625,9 +2625,9 @@ func formatCallHierarchyItemSpan( lineNumStr := fmt.Sprintf("%d:", lineNum+1) paddedLineNum := strings.Repeat(" ", lineNumWidth-len(lineNumStr)-1) + lineNumStr if lineContent == "" { - result.WriteString(fmt.Sprintf("%s│ %s\n", prefix, paddedLineNum)) + fmt.Fprintf(result, "%s│ %s\n", prefix, paddedLineNum) } else { - result.WriteString(fmt.Sprintf("%s│ %s %s\n", prefix, paddedLineNum, lineContent)) + fmt.Fprintf(result, "%s│ %s %s\n", prefix, paddedLineNum, lineContent) } // Add selection carets if this line contains part of the span @@ -2647,7 +2647,7 @@ func formatCallHierarchyItemSpan( if isEmpty { // For empty selections, show a single "<" character padding := strings.Repeat(" ", lineNumWidth+selStart) - result.WriteString(fmt.Sprintf("%s│ %s<\n", prefix, padding)) + fmt.Fprintf(result, "%s│ %s<\n", prefix, padding) } else { // Calculate selection length (at least 1) selLength := selEnd - selStart @@ -2662,7 +2662,7 @@ func formatCallHierarchyItemSpan( padding := strings.Repeat(" ", lineNumWidth+selStart) carets := strings.Repeat("^", selLength) - result.WriteString(fmt.Sprintf("%s│ %s%s\n", prefix, padding, carets)) + fmt.Fprintf(result, "%s│ %s%s\n", prefix, padding, carets) } } } diff --git a/internal/ls/autoimport/extract.go b/internal/ls/autoimport/extract.go index 8d2a402fa1c..caecc2ce7fa 100644 --- a/internal/ls/autoimport/extract.go +++ b/internal/ls/autoimport/extract.go @@ -397,10 +397,7 @@ func (e *symbolExtractor) tryResolveSymbol(symbol *ast.Symbol, syntax ExportSynt } func shouldIgnoreSymbol(symbol *ast.Symbol) bool { - if symbol.Flags&ast.SymbolFlagsPrototype != 0 { - return true - } - return false + return symbol.Flags&ast.SymbolFlagsPrototype != 0 } func getSyntax(symbol *ast.Symbol) ExportSyntax { diff --git a/internal/ls/autoimport/fix.go b/internal/ls/autoimport/fix.go index b808cff60ee..8226fe37817 100644 --- a/internal/ls/autoimport/fix.go +++ b/internal/ls/autoimport/fix.go @@ -214,7 +214,7 @@ func addToExistingImport( if defaultImport != nil { debug.Assert(importClause.Name() == nil, "Cannot add a default import to an import clause that already has one") - ct.InsertNodeAt(file, core.TextPos(astnav.GetStartOfNode(importClause.AsNode(), file, false)), ct.NodeFactory.NewIdentifier(defaultImport.name), change.NodeOptions{Suffix: ", "}) + ct.InsertNodeAt(file, core.TextPos(astnav.GetStartOfNode(importClause.AsNode(), file, false)), ct.NewIdentifier(defaultImport.name), change.NodeOptions{Suffix: ", "}) } if len(namedImports) > 0 { @@ -224,10 +224,10 @@ func addToExistingImport( 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), ) }) slices.SortFunc(newSpecifiers, specifierComparer) @@ -248,7 +248,7 @@ func addToExistingImport( if spec.PropertyName != nil { propertyName = spec.PropertyName } - syntheticSpec := ct.NodeFactory.NewImportSpecifier( + syntheticSpec := ct.NewImportSpecifier( true, // isTypeOnly propertyName, spec.Name(), @@ -267,7 +267,7 @@ func addToExistingImport( } } 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(file, importClause.NamedBindings, namedImports, nil) } else { @@ -318,11 +318,11 @@ func addElementToBindingPattern( name string, propertyName string, ) { - element := ct.NodeFactory.NewBindingElement(nil, nil, ct.NodeFactory.NewIdentifier(name), core.IfElse(propertyName == "", nil, ct.NodeFactory.NewIdentifier(propertyName))) + element := ct.NewBindingElement(nil, nil, ct.NewIdentifier(name), core.IfElse(propertyName == "", nil, ct.NewIdentifier(propertyName))) if len(bindingPattern.Elements.Nodes) > 0 { ct.InsertNodeInListAfter(file, bindingPattern.Elements.Nodes[len(bindingPattern.Elements.Nodes)-1], element, bindingPattern.Elements) } else { - ct.ReplaceNode(file, bindingPattern.AsNode(), ct.NodeFactory.NewBindingPattern(ast.KindObjectBindingPattern, ct.AsNodeFactory().NewNodeList([]*ast.Node{element})), nil) + ct.ReplaceNode(file, bindingPattern.AsNode(), ct.NewBindingPattern(ast.KindObjectBindingPattern, ct.AsNodeFactory().NewNodeList([]*ast.Node{element})), nil) } } @@ -337,7 +337,7 @@ func getNewImports( preferences lsutil.UserPreferences, ) []*ast.AnyImportSyntax { tokenFlags := core.IfElse(quotePreference == lsutil.QuotePreferenceSingle, ast.TokenFlagsSingleQuote, ast.TokenFlagsNone) - moduleSpecifierStringLiteral := ct.NodeFactory.NewStringLiteral(moduleSpecifier, tokenFlags) + moduleSpecifierStringLiteral := ct.NewStringLiteral(moduleSpecifier, tokenFlags) var statements []*ast.AnyImportSyntax if defaultImport != nil || len(namedImports) > 0 { // `verbatimModuleSyntax` should prefer top-level `import type` - @@ -350,18 +350,18 @@ func getNewImports( var defaultImportNode *ast.Node if defaultImport != nil { - defaultImportNode = ct.NodeFactory.NewIdentifier(defaultImport.name) + defaultImportNode = ct.NewIdentifier(defaultImport.name) } statements = append(statements, makeImport(ct, defaultImportNode, core.Map(namedImports, func(namedImport *newImportBinding) *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)) } @@ -369,19 +369,19 @@ func getNewImports( if namespaceLikeImport != nil { var declaration *ast.Statement if namespaceLikeImport.kind == lsproto.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( /*phaseModifier*/ core.IfElse(shouldUseTypeOnly(namespaceLikeImport.addAsTypeOnly, preferences), ast.KindTypeKeyword, ast.KindUnknown), /*name*/ nil, - ct.NodeFactory.NewNamespaceImport(ct.NodeFactory.NewIdentifier(namespaceLikeImport.name)), + ct.NewNamespaceImport(ct.NewIdentifier(namespaceLikeImport.name)), ), moduleSpecifierStringLiteral, /*attributes*/ nil, @@ -404,7 +404,7 @@ func getNewRequires( namespaceLikeImport *newImportBinding, compilerOptions *core.CompilerOptions, ) []*ast.Statement { - quotedModuleSpecifier := changeTracker.NodeFactory.NewStringLiteral( + quotedModuleSpecifier := changeTracker.NewStringLiteral( moduleSpecifier, core.IfElse(quotePreference == lsutil.QuotePreferenceSingle, ast.TokenFlagsSingleQuote, ast.TokenFlagsNone), ) @@ -416,30 +416,30 @@ func getNewRequires( for _, namedImport := range namedImports { var propertyName *ast.Node if namedImport.propertyName != "" { - propertyName = changeTracker.NodeFactory.NewIdentifier(namedImport.propertyName) + propertyName = changeTracker.NewIdentifier(namedImport.propertyName) } - bindingElements = append(bindingElements, changeTracker.NodeFactory.NewBindingElement( + bindingElements = append(bindingElements, changeTracker.NewBindingElement( /*dotDotDotToken*/ nil, propertyName, - changeTracker.NodeFactory.NewIdentifier(namedImport.name), + changeTracker.NewIdentifier(namedImport.name), /*initializer*/ nil, )) } if defaultImport != nil { bindingElements = append([]*ast.Node{ - changeTracker.NodeFactory.NewBindingElement( + changeTracker.NewBindingElement( /*dotDotDotToken*/ nil, - changeTracker.NodeFactory.NewIdentifier("default"), - changeTracker.NodeFactory.NewIdentifier(defaultImport.name), + changeTracker.NewIdentifier("default"), + changeTracker.NewIdentifier(defaultImport.name), /*initializer*/ nil, ), }, bindingElements...) } declaration := createConstEqualsRequireDeclaration( changeTracker, - changeTracker.NodeFactory.NewBindingPattern( + changeTracker.NewBindingPattern( ast.KindObjectBindingPattern, - changeTracker.NodeFactory.NewNodeList(bindingElements), + changeTracker.NewNodeList(bindingElements), ), quotedModuleSpecifier, ) @@ -450,7 +450,7 @@ func getNewRequires( if namespaceLikeImport != nil { declaration := createConstEqualsRequireDeclaration( changeTracker, - changeTracker.NodeFactory.NewIdentifier(namespaceLikeImport.name), + changeTracker.NewIdentifier(namespaceLikeImport.name), quotedModuleSpecifier, ) statements = append(statements, declaration) @@ -461,19 +461,19 @@ func getNewRequires( } func createConstEqualsRequireDeclaration(changeTracker *change.Tracker, name *ast.Node, quotedModuleSpecifier *ast.Node) *ast.Statement { - return changeTracker.NodeFactory.NewVariableStatement( + return changeTracker.NewVariableStatement( /*modifiers*/ nil, - changeTracker.NodeFactory.NewVariableDeclarationList( - changeTracker.NodeFactory.NewNodeList([]*ast.Node{ - changeTracker.NodeFactory.NewVariableDeclaration( + changeTracker.NewVariableDeclarationList( + changeTracker.NewNodeList([]*ast.Node{ + changeTracker.NewVariableDeclaration( name, /*exclamationToken*/ nil, /*type*/ nil, - changeTracker.NodeFactory.NewCallExpression( - changeTracker.NodeFactory.NewIdentifier("require"), + changeTracker.NewCallExpression( + changeTracker.NewIdentifier("require"), /*questionDotToken*/ nil, /*typeArguments*/ nil, - changeTracker.NodeFactory.NewNodeList([]*ast.Node{quotedModuleSpecifier}), + changeTracker.NewNodeList([]*ast.Node{quotedModuleSpecifier}), ast.NodeFlagsNone, ), ), @@ -525,13 +525,13 @@ func insertImports(ct *change.Tracker, sourceFile *ast.SourceFile, imports []*as func makeImport(ct *change.Tracker, 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(core.IfElse(isTypeOnly, ast.KindTypeKeyword, ast.KindUnknown), defaultImport, newNamedImports) + importClause = ct.NewImportClause(core.IfElse(isTypeOnly, ast.KindTypeKeyword, ast.KindUnknown), defaultImport, newNamedImports) } - return ct.NodeFactory.NewImportDeclaration( /*modifiers*/ nil, importClause, moduleSpecifier, nil /*attributes*/) + return ct.NewImportDeclaration( /*modifiers*/ nil, importClause, moduleSpecifier, nil /*attributes*/) } func (v *View) GetFixes(ctx context.Context, export *Export, forJSX bool, isValidTypeOnlyUseSite bool, usagePosition *lsproto.Position) []*Fix { @@ -1049,10 +1049,10 @@ func promoteFromTypeOnly( if spec.PropertyName != nil { propertyName = changes.NodeFactory.NewIdentifier(spec.PropertyName.Text()).AsIdentifier().AsNode() } - newSpecifier := changes.NodeFactory.NewImportSpecifier( + newSpecifier := changes.NewImportSpecifier( false, // isTypeOnly = false propertyName, - changes.NodeFactory.NewIdentifier(spec.Name().Text()), + changes.NewIdentifier(spec.Name().Text()), ) specifierComparer, _ := lsutil.GetNamedImportSpecifierComparerWithDetection( spec.Parent.Parent.Parent, // ImportDeclaration @@ -1159,7 +1159,7 @@ func promoteImportClause( // If the alias declaration is an ImportSpecifier and the list is sorted, // move it to index 0 (since it will be the only non-type-only import) - if isSorted.IsFalse() == false && // isSorted !== false + if !isSorted.IsFalse() && // isSorted !== false aliasDeclaration != nil && aliasDeclaration.Kind == ast.KindImportSpecifier { // Find the index of the alias declaration diff --git a/internal/ls/autoimport/index.go b/internal/ls/autoimport/index.go index a83ca9ee560..e4b78efc38b 100644 --- a/internal/ls/autoimport/index.go +++ b/internal/ls/autoimport/index.go @@ -71,9 +71,9 @@ func (idx *Index[T]) SearchWordPrefix(prefix string) []T { // Look up entries that have words starting with this letter var wordStarts []int - nameStarts, _ := idx.index[firstRuneUpper] + nameStarts := idx.index[firstRuneUpper] if firstRuneUpper != firstRuneLower { - wordStarts, _ = idx.index[firstRuneLower] + wordStarts = idx.index[firstRuneLower] } count := len(nameStarts) + len(wordStarts) if count == 0 { diff --git a/internal/ls/change/delete.go b/internal/ls/change/delete.go index b5a3dd4a05d..b609a45ce6a 100644 --- a/internal/ls/change/delete.go +++ b/internal/ls/change/delete.go @@ -165,7 +165,7 @@ func deleteVariableDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]boo gp := parent.Parent switch gp.Kind { case ast.KindForOfStatement, ast.KindForInStatement: - t.ReplaceNode(sourceFile, node, t.NodeFactory.NewObjectLiteralExpression(t.NodeFactory.NewNodeList([]*ast.Node{}), false), nil) + t.ReplaceNode(sourceFile, node, t.NewObjectLiteralExpression(t.NewNodeList([]*ast.Node{}), false), nil) case ast.KindForStatement: deleteNode(t, sourceFile, parent, LeadingTriviaOptionIncludeAll, TrailingTriviaOptionInclude) diff --git a/internal/ls/change/trackerimpl.go b/internal/ls/change/trackerimpl.go index 1d748c3986d..ad137fa26fc 100644 --- a/internal/ls/change/trackerimpl.go +++ b/internal/ls/change/trackerimpl.go @@ -26,7 +26,7 @@ func (t *Tracker) getTextChangesFromChanges() map[string][]*lsproto.TextEdit { slices.SortStableFunc(changesInFile, func(a, b *trackerEdit) int { return lsproto.CompareRanges(a.Range, b.Range) }) // verify that change intervals do not overlap, except possibly at end points. for i := range len(changesInFile) - 1 { - if lsproto.ComparePositions(changesInFile[i].Range.End, changesInFile[i+1].Range.Start) > 0 { + if lsproto.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)) } @@ -62,7 +62,7 @@ func (t *Tracker) computeNewText(change *trackerEdit, targetSourceFile *ast.Sour return change.NewText } - pos := int(t.converters.LineAndCharacterToPosition(sourceFile, change.Range.Start)) + pos := int(t.converters.LineAndCharacterToPosition(sourceFile, change.Start)) formatNode := func(n *ast.Node) string { return t.getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, change.options) } @@ -311,7 +311,7 @@ func (t *Tracker) getAdjustedEndPosition(sourceFile *ast.SourceFile, node *ast.N // ============= 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 b33a367dad8..6fccbf1a828 100644 --- a/internal/ls/completions.go +++ b/internal/ls/completions.go @@ -1048,6 +1048,7 @@ func (l *LanguageService) getCompletionData( symbols = append(symbols, filteredMembers...) // Set sort texts. + //nolint:staticcheck transformObjectLiteralMembers := preferences.IncludeCompletionsWithObjectLiteralMethodSnippets.IsTrue() && objectLikeContainer.Kind == ast.KindObjectLiteralExpression for _, member := range filteredMembers { @@ -1928,7 +1929,7 @@ func (l *LanguageService) getCompletionEntriesFromSymbols( nil, /*detail*/ ) - if isShadowed, _ := uniques[autoImport.Fix.Name]; !isShadowed { + if isShadowed := uniques[autoImport.Fix.Name]; !isShadowed { uniques[autoImport.Fix.Name] = false sortedEntries = append(sortedEntries, entry) } diff --git a/internal/ls/crossproject.go b/internal/ls/crossproject.go index b43b9335197..201f80f4278 100644 --- a/internal/ls/crossproject.go +++ b/internal/ls/crossproject.go @@ -166,41 +166,6 @@ func handleCrossProject[Req lsproto.HasTextDocumentPosition, Resp any]( } } - getResultsIterator := func() iter.Seq[Resp] { - return func(yield func(Resp) bool) { - var seenProjects collections.SyncSet[tspath.Path] - if response, loaded := results.Load(defaultProject.Id()); loaded && response.complete { - if !yield(response.result) { - return - } - } - seenProjects.Add(defaultProject.Id()) - for _, project := range allProjects { - if seenProjects.AddIfAbsent(project.Id()) { - if response, loaded := results.Load(project.Id()); loaded && response.complete { - if !yield(response.result) { - return - } - } - } - } - // Prefer the searches from locations for default definition - results.Range(func(key tspath.Path, response *response[Resp]) bool { - if !response.forOriginalLocation && seenProjects.AddIfAbsent(key) && response.complete { - return yield(response.result) - } - return true - }) - // Then the searches from original locations - results.Range(func(key tspath.Path, response *response[Resp]) bool { - if response.forOriginalLocation && seenProjects.AddIfAbsent(key) && response.complete { - return yield(response.result) - } - return true - }) - } - } - // Outer loop - to complete work if more is added after completing existing queue for { // Process existing known projects first @@ -268,6 +233,41 @@ func handleCrossProject[Req lsproto.HasTextDocumentPosition, Resp any]( } } + getResultsIterator := func() iter.Seq[Resp] { + return func(yield func(Resp) bool) { + var seenProjects collections.SyncSet[tspath.Path] + if response, loaded := results.Load(defaultProject.Id()); loaded && response.complete { + if !yield(response.result) { + return + } + } + seenProjects.Add(defaultProject.Id()) + for _, project := range allProjects { + if seenProjects.AddIfAbsent(project.Id()) { + if response, loaded := results.Load(project.Id()); loaded && response.complete { + if !yield(response.result) { + return + } + } + } + } + // Prefer the searches from locations for default definition + results.Range(func(key tspath.Path, response *response[Resp]) bool { + if !response.forOriginalLocation && seenProjects.AddIfAbsent(key) && response.complete { + return yield(response.result) + } + return true + }) + // Then the searches from original locations + results.Range(func(key tspath.Path, response *response[Resp]) bool { + if response.forOriginalLocation && seenProjects.AddIfAbsent(key) && response.complete { + return yield(response.result) + } + return true + }) + } + } + if results.Size() > 1 { resp = combineResults(getResultsIterator()) } else { diff --git a/internal/ls/folding.go b/internal/ls/folding.go index c07f28967eb..dbba1ae21b2 100644 --- a/internal/ls/folding.go +++ b/internal/ls/folding.go @@ -285,7 +285,6 @@ func addOutliningForLeadingCommentsForPos(ctx context.Context, pos int, sourceFi } lastSingleLineCommentEnd = commentEnd singleLineCommentCount++ - break case ast.KindMultiLineCommentTrivia: comments := combineAndAddMultipleSingleLineComments() if comments != nil { @@ -293,7 +292,6 @@ func addOutliningForLeadingCommentsForPos(ctx context.Context, pos int, sourceFi } foldingRange = append(foldingRange, createFoldingRangeFromBounds(ctx, commentPos, commentEnd, foldingRangeKindComment, sourceFile, l)) singleLineCommentCount = 0 - break default: debug.AssertNever(comment.Kind) } diff --git a/internal/ls/hover.go b/internal/ls/hover.go index 214605fcba6..7f0144e7999 100644 --- a/internal/ls/hover.go +++ b/internal/ls/hover.go @@ -254,7 +254,7 @@ func getQuickInfoAndDeclarationAtLocation(c *checker.Checker, symbol *ast.Symbol for i, sig := range signatures { writeNewLine() 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 64062e4a79c..1829e42a2e0 100644 --- a/internal/ls/signaturehelp.go +++ b/internal/ls/signaturehelp.go @@ -1206,9 +1206,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/string_completions.go b/internal/ls/string_completions.go index 0c5b489db48..f03fe4a1890 100644 --- a/internal/ls/string_completions.go +++ b/internal/ls/string_completions.go @@ -1170,18 +1170,12 @@ func deduplicateModuleCompletions(completions []moduleCompletionNameAndKind) []m if len(completions) <= 1 { return completions } - type key struct { - name string - kind moduleCompletionKind - extension string - } - seen := make(map[key]bool) + seen := make(map[moduleCompletionNameAndKind]bool) var result []moduleCompletionNameAndKind - for _, c := range completions { - k := key{name: c.name, kind: c.kind, extension: c.extension} + for _, k := range completions { if !seen[k] { seen[k] = true - result = append(result, c) + result = append(result, k) } } return result diff --git a/internal/ls/utilities.go b/internal/ls/utilities.go index 38fd4169965..0ed849f230c 100644 --- a/internal/ls/utilities.go +++ b/internal/ls/utilities.go @@ -425,7 +425,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 getContainingNodeIfInHeritageClause(node *ast.Node) *ast.Node { diff --git a/internal/lsp/server.go b/internal/lsp/server.go index 766e865c00d..f285ec44ee0 100644 --- a/internal/lsp/server.go +++ b/internal/lsp/server.go @@ -1449,8 +1449,7 @@ func (s *Server) handleInitializeAPISession(ctx context.Context, params *lsproto s.apiSessions = make(map[string]*api.Session) } - var apiSession *api.Session - apiSession = api.NewSession(s.session, nil) + apiSession := api.NewSession(s.session, nil) // Use provided pipe path or generate a unique one var pipePath string diff --git a/internal/modulespecifiers/specifiers.go b/internal/modulespecifiers/specifiers.go index ea7b1799b0f..773a7594b39 100644 --- a/internal/modulespecifiers/specifiers.go +++ b/internal/modulespecifiers/specifiers.go @@ -765,7 +765,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, @@ -885,14 +885,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, ) } @@ -902,7 +902,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, @@ -1039,7 +1039,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 0295e4e76f7..97c80b55387 100644 --- a/internal/packagejson/cache.go +++ b/internal/packagejson/cache.go @@ -27,17 +27,17 @@ type diagnosticAndArgs struct { func (p *PackageJson) GetVersionPaths(trace func(m *diagnostics.Message, args ...any)) VersionPaths { p.once.Do(func() { - if p.Fields.TypesVersions.Type == JSONValueTypeNotPresent { + if p.TypesVersions.Type == JSONValueTypeNotPresent { p.versionTraces = append(p.versionTraces, diagnosticAndArgs{ diagnostics.X_package_json_does_not_have_a_0_field, []any{"typesVersions"}, }) return } - if p.Fields.TypesVersions.Type != JSONValueTypeObject { + if p.TypesVersions.Type != JSONValueTypeObject { p.versionTraces = append(p.versionTraces, diagnosticAndArgs{ diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, - []any{"typesVersions", "object", p.Fields.TypesVersions.Type.String()}, + []any{"typesVersions", "object", p.TypesVersions.Type.String()}, }) return } diff --git a/internal/parser/jsdoc.go b/internal/parser/jsdoc.go index 9249633ac6b..495b7b2d5e9 100644 --- a/internal/parser/jsdoc.go +++ b/internal/parser/jsdoc.go @@ -1227,7 +1227,7 @@ func (p *Parser) parseOptionalJsdoc(t ast.Kind) bool { } func (p *Parser) parseJSDocEntityName(diagnosticMessage *diagnostics.Message) *ast.EntityName { - var entity *ast.EntityName = p.parseJSDocIdentifierName(diagnosticMessage) + entity := p.parseJSDocIdentifierName(diagnosticMessage) 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 7a4c15ef61a..c230a909e69 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -6607,7 +6607,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/project.go b/internal/project/project.go index e873c3c79fa..a2df39fab35 100644 --- a/internal/project/project.go +++ b/internal/project/project.go @@ -402,12 +402,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") diff --git a/internal/project/refcountcache_test.go b/internal/project/refcountcache_test.go index 439588cd3e8..d16e8f3dbc9 100644 --- a/internal/project/refcountcache_test.go +++ b/internal/project/refcountcache_test.go @@ -107,7 +107,7 @@ func TestRefCountingCaches(t *testing.T) { session.WaitForBackgroundTasks() assert.Equal(t, utilsEntry.refCount, 1) assert.Equal(t, mainEntry.refCount, 0) - mainEntry, ok := session.parseCache.entries.Load(NewParseCacheKey(main.ParseOptions(), main.Hash, main.ScriptKind)) + _, ok := session.parseCache.entries.Load(NewParseCacheKey(main.ParseOptions(), main.Hash, main.ScriptKind)) assert.Equal(t, ok, false) }) diff --git a/internal/project/snapshot.go b/internal/project/snapshot.go index ce67f78c7c5..a1cead5c71f 100644 --- a/internal/project/snapshot.go +++ b/internal/project/snapshot.go @@ -415,8 +415,8 @@ func (s *Snapshot) Clone(ctx context.Context, change SnapshotChange, overlays ma openFiles[path] = overlay.FileName() } prepareAutoImports := tspath.Path("") - if change.ResourceRequest.AutoImports != "" { - prepareAutoImports = change.ResourceRequest.AutoImports.Path(s.UseCaseSensitiveFileNames()) + if change.AutoImports != "" { + prepareAutoImports = change.AutoImports.Path(s.UseCaseSensitiveFileNames()) } oldAutoImports := s.AutoImports if oldAutoImports == nil { diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index aec39a8b4b4..ea95270bf56 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -1481,10 +1481,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/autoimporttestutil/fixtures.go b/internal/testutil/autoimporttestutil/fixtures.go index 73444aa1ef3..a544d5ea57f 100644 --- a/internal/testutil/autoimporttestutil/fixtures.go +++ b/internal/testutil/autoimporttestutil/fixtures.go @@ -204,7 +204,7 @@ func SetupMonorepoLifecycleSession(t *testing.T, config MonorepoSetupConfig) *Mo builder := newFileMapBuilder(nil) monorepoRoot := normalizeAbsolutePath(config.Root) - monorepoName := config.MonorepoPackageTemplate.Name + monorepoName := config.Name if monorepoName == "" { monorepoName = "monorepo" } @@ -494,7 +494,7 @@ func (b *fileMapBuilder) AddPackageJSONWithDependenciesNamed(projectDir string, b.nextProjectID++ name = fmt.Sprintf("local-project-%d", b.nextProjectID) } - builder.WriteString(fmt.Sprintf("{\n \"name\": \"%s\"", name)) + fmt.Fprintf(&builder, "{\n \"name\": \"%s\"", name) if len(dependencyLines) > 0 { builder.WriteString(",\n \"dependencies\": {\n ") builder.WriteString(strings.Join(dependencyLines, ",\n ")) @@ -527,7 +527,7 @@ func (b *fileMapBuilder) addRootPackageJSON(rootDir string, packageName string, if pkgName == "" { pkgName = "monorepo-root" } - builder.WriteString(fmt.Sprintf("{\n \"name\": \"%s\",\n \"private\": true", pkgName)) + fmt.Fprintf(&builder, "{\n \"name\": \"%s\",\n \"private\": true", pkgName) if len(dependencyLines) > 0 { builder.WriteString(",\n \"dependencies\": {\n ") builder.WriteString(strings.Join(dependencyLines, ",\n ")) diff --git a/internal/testutil/harnessutil/sourcemap_recorder.go b/internal/testutil/harnessutil/sourcemap_recorder.go index cc811c4a3c9..af704bb3f05 100644 --- a/internal/testutil/harnessutil/sourcemap_recorder.go +++ b/internal/testutil/harnessutil/sourcemap_recorder.go @@ -18,7 +18,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) { @@ -60,7 +60,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 da9d5b67471..48035afa1c1 100644 --- a/internal/testutil/projecttestutil/projecttestutil.go +++ b/internal/testutil/projecttestutil/projecttestutil.go @@ -139,7 +139,7 @@ func TypesRegistryConfigText() string { if result.Len() != 0 { result.WriteString(",") } - result.WriteString(fmt.Sprintf("\n \"%s\": \"%s\"", key, value)) + fmt.Fprintf(&result, "\n \"%s\": \"%s\"", key, value) } typesRegistryConfigText = result.String() @@ -190,7 +190,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/sourcemap_baseline.go b/internal/testutil/tsbaseline/sourcemap_baseline.go index 4c83c3a9203..ac9f6b0bbb1 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 59271ada5f4..36c0c872c98 100644 --- a/internal/transformers/declarations/transform.go +++ b/internal/transformers/declarations/transform.go @@ -322,10 +322,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:] @@ -1391,7 +1388,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 f19f6912d4d..5cc4ebfbf5b 100644 --- a/internal/transformers/declarations/util.go +++ b/internal/transformers/declarations/util.go @@ -110,10 +110,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 3d24cbe97d7..e723e340f50 100644 --- a/internal/transformers/estransforms/namedevaluation.go +++ b/internal/transformers/estransforms/namedevaluation.go @@ -75,14 +75,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 } @@ -112,7 +110,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/tstransforms/legacydecorators.go b/internal/transformers/tstransforms/legacydecorators.go index 22d0192e806..5d6a1e3e574 100644 --- a/internal/transformers/tstransforms/legacydecorators.go +++ b/internal/transformers/tstransforms/legacydecorators.go @@ -593,7 +593,7 @@ func (tx *LegacyDecoratorsTransformer) generateConstructorDecorationExpression(n var classAlias *ast.Node if tx.classAliases != nil { - classAlias, _ = tx.classAliases[node.AsNode()] + classAlias = tx.classAliases[node.AsNode()] } // When we used to transform to ES5/3 this would be moved inside an IIFE and should reference the name diff --git a/internal/tsoptions/tsconfigparsing.go b/internal/tsoptions/tsconfigparsing.go index 15118ae277f..f6575d2271d 100644 --- a/internal/tsoptions/tsconfigparsing.go +++ b/internal/tsoptions/tsconfigparsing.go @@ -575,7 +575,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 } @@ -1094,7 +1094,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 { @@ -1623,7 +1623,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 @@ -1661,7 +1660,7 @@ func getFileNamesFromConfigSpecs( includes := core.Filter(validatedIncludeSpecs, func(include string) bool { return strings.HasSuffix(include, tspath.ExtensionJson) }) jsonOnlyIncludeMatchers = vfsmatch.NewSpecMatcher(includes, basePath, vfsmatch.UsageFiles, host.UseCaseSensitiveFileNames()) } - var includeIndex int = -1 + includeIndex := -1 if jsonOnlyIncludeMatchers != nil { includeIndex = jsonOnlyIncludeMatchers.MatchIndex(file) } diff --git a/internal/tsoptions/tsconfigparsing_test.go b/internal/tsoptions/tsconfigparsing_test.go index f24bf14eccd..0fa41b4b3e8 100644 --- a/internal/tsoptions/tsconfigparsing_test.go +++ b/internal/tsoptions/tsconfigparsing_test.go @@ -157,9 +157,8 @@ func TestParseConfigFileTextToJson(t *testing.T) { } type parseJsonConfigTestCase struct { - title string - noSubmoduleBaseline bool - input []testConfig + title string + input []testConfig } var parseJsonConfigFileTests = []parseJsonConfigTestCase{ @@ -237,8 +236,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": { @@ -441,8 +439,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", @@ -459,8 +456,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" @@ -499,8 +495,7 @@ var parseJsonConfigFileTests = []parseJsonConfigTestCase{ }}, }, { - title: "handles empty types array", - noSubmoduleBaseline: true, + title: "handles empty types array", input: []testConfig{{ jsonText: `{ "compilerOptions": { @@ -513,8 +508,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", @@ -583,8 +577,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", @@ -609,8 +602,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", @@ -635,8 +627,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", @@ -666,8 +657,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", @@ -699,8 +689,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", @@ -774,7 +763,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) }) } } @@ -801,7 +790,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) }) } } @@ -829,8 +818,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 @@ -979,12 +968,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) }) } }