diff --git a/.golangci.yml b/.golangci.yml index 373793aa33..27eaa6a790 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -38,6 +38,7 @@ linters: - perfsprint - predeclared - reassign + - staticcheck - testableexamples - tparallel - unconvert @@ -52,7 +53,6 @@ linters: # - gocritic # - gosec # - revive - # - staticcheck # - testifylint # - unparam # - unused @@ -62,6 +62,21 @@ linters: customlint: type: module + staticcheck: + checks: + - all + - -QF1001 + - -QF1003 + - -SA6005 + - -SA9003 + - -ST1000 + - -ST1003 + - -ST1006 # TODO: enable + - -ST1016 + - -ST1020 + - -ST1021 + - -ST1022 + exclusions: presets: - comments diff --git a/internal/ast/utilities.go b/internal/ast/utilities.go index 6e6fdad7c2..09dd561c04 100644 --- a/internal/ast/utilities.go +++ b/internal/ast/utilities.go @@ -1767,7 +1767,6 @@ func GetSuperContainer(node *Node, stopOnFunctions bool) *Node { switch node.Kind { case KindComputedPropertyName: node = node.Parent - break case KindFunctionDeclaration, KindFunctionExpression, KindArrowFunction: if !stopOnFunctions { continue @@ -1787,7 +1786,6 @@ func GetSuperContainer(node *Node, stopOnFunctions bool) *Node { // from the parent class declaration. node = node.Parent } - break } } } diff --git a/internal/astnav/tokens_test.go b/internal/astnav/tokens_test.go index 9c237dafee..8660eb60f6 100644 --- a/internal/astnav/tokens_test.go +++ b/internal/astnav/tokens_test.go @@ -287,23 +287,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 3dc5ad31e8..a9ac1216e4 100644 --- a/internal/binder/binder.go +++ b/internal/binder/binder.go @@ -248,7 +248,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 } @@ -263,7 +263,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 } @@ -2137,7 +2137,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 fca04dd588..a083b3c2d5 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -1654,13 +1654,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*/) } @@ -10366,10 +10359,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 @@ -14686,10 +14679,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") @@ -16134,7 +16127,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 { @@ -17692,12 +17685,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}) @@ -19122,7 +19115,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) @@ -20133,7 +20126,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] @@ -28153,10 +28146,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 @@ -29575,10 +29568,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/emitresolver.go b/internal/checker/emitresolver.go index 0939def9d7..adc9126fc5 100644 --- a/internal/checker/emitresolver.go +++ b/internal/checker/emitresolver.go @@ -510,7 +510,7 @@ func (r *emitResolver) requiresAddingImplicitUndefined(declaration *ast.Node, sy } t := r.checker.getTypeOfSymbol(symbol) r.checker.mappedSymbolLinks.Has(symbol) - return !!((symbol.Flags&ast.SymbolFlagsProperty != 0) && (symbol.Flags&ast.SymbolFlagsOptional != 0) && isOptionalDeclaration(declaration) && r.checker.ReverseMappedSymbolLinks.Has(symbol) && r.checker.ReverseMappedSymbolLinks.Get(symbol).mappedType != nil && containsNonMissingUndefinedType(r.checker, t)) + return (symbol.Flags&ast.SymbolFlagsProperty != 0) && (symbol.Flags&ast.SymbolFlagsOptional != 0) && isOptionalDeclaration(declaration) && r.checker.ReverseMappedSymbolLinks.Has(symbol) && r.checker.ReverseMappedSymbolLinks.Get(symbol).mappedType != nil && containsNonMissingUndefinedType(r.checker, t) case ast.KindParameter, ast.KindJSDocParameterTag: return r.requiresAddingImplicitUndefinedWorker(declaration, enclosingDeclaration) default: @@ -900,12 +900,10 @@ func (r *emitResolver) CreateLiteralConstValue(emitContext *printer.EmitContext, if t.flags&TypeFlagsLiteral == 0 { return nil // non-literal type } - literalValue := t.AsLiteralType().value - switch literalValue.(type) { + switch value := t.AsLiteralType().value.(type) { case string: - return emitContext.Factory.NewStringLiteral(literalValue.(string)) + return emitContext.Factory.NewStringLiteral(value) case jsnum.Number: - value := literalValue.(jsnum.Number) if value.Abs() != value { // negative return emitContext.Factory.NewPrefixUnaryExpression( @@ -915,7 +913,6 @@ func (r *emitResolver) CreateLiteralConstValue(emitContext *printer.EmitContext, } return emitContext.Factory.NewNumericLiteral(value.String()) case jsnum.PseudoBigInt: - value := literalValue.(jsnum.PseudoBigInt) if value.Negative { // negative return emitContext.Factory.NewPrefixUnaryExpression( @@ -925,7 +922,7 @@ func (r *emitResolver) CreateLiteralConstValue(emitContext *printer.EmitContext, } return emitContext.Factory.NewNumericLiteral(value.Base10Value) case bool: - if literalValue.(bool) { + if value { return emitContext.Factory.NewKeywordExpression(ast.KindTrueKeyword) } return emitContext.Factory.NewKeywordExpression(ast.KindFalseKeyword) diff --git a/internal/checker/flow.go b/internal/checker/flow.go index b8e1841171..c4bb09cce5 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 cd3cca23f3..1d3ca2cb2d 100644 --- a/internal/checker/grammarchecks.go +++ b/internal/checker/grammarchecks.go @@ -1513,7 +1513,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) @@ -1817,14 +1817,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 80e465aada..e3d04435db 100644 --- a/internal/checker/inference.go +++ b/internal/checker/inference.go @@ -579,10 +579,10 @@ func (c *Checker) inferToTemplateLiteralType(n *InferenceState, source *Type, ta case left.flags&TypeFlagsBoolean != 0: return left case right.flags&TypeFlagsBoolean != 0: - switch { - case str == "true": + switch str { + case "true": return c.trueType - case str == "false": + case "false": return c.falseType default: return c.booleanType diff --git a/internal/checker/jsx.go b/internal/checker/jsx.go index 5629ba9ff7..9765cf8175 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 e15722e5a2..ccd985f67e 100644 --- a/internal/checker/nodebuilderimpl.go +++ b/internal/checker/nodebuilderimpl.go @@ -179,7 +179,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) } @@ -188,7 +188,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() @@ -917,7 +917,7 @@ func (b *nodeBuilderImpl) getSymbolChain(symbol *ast.Symbol, meaning ast.SymbolF // If a parent symbol is an anonymous type, don't write it. (symbol.Flags&(ast.SymbolFlagsTypeLiteral|ast.SymbolFlagsObjectLiteral) == 0) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - if !endOfChain && !yieldModuleSymbol && !!core.Some(symbol.Declarations, hasNonGlobalAugmentationExternalModuleSymbol) { + if !endOfChain && !yieldModuleSymbol && core.Some(symbol.Declarations, hasNonGlobalAugmentationExternalModuleSymbol) { return nil } return []*ast.Symbol{symbol} @@ -1212,7 +1212,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 @@ -1625,7 +1625,7 @@ func (b *nodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signa typeParamList = b.f.NewNodeList(typeParameters) } var modifierList *ast.ModifierList - if modifiers != nil && len(modifiers) > 0 { + if len(modifiers) > 0 { modifierList = b.f.NewModifierList(modifiers) } var name *ast.Node @@ -1637,47 +1637,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 /*body*/) - case kind == ast.KindConstructor: + case ast.KindConstructor: node = b.f.NewConstructorDeclaration(modifierList, nil /*typeParamList*/, paramList, nil /*returnTypeNode*/, nil /*body*/) - case kind == ast.KindGetAccessor: + case ast.KindGetAccessor: node = b.f.NewGetAccessorDeclaration(modifierList, name, nil /*typeParamList*/, paramList, returnTypeNode, nil /*body*/) - case kind == ast.KindSetAccessor: + case ast.KindSetAccessor: node = b.f.NewSetAccessorDeclaration(modifierList, name, nil /*typeParamList*/, paramList, nil /*returnTypeNode*/, 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 /*body*/) - case kind == ast.KindFunctionExpression: + case ast.KindFunctionExpression: // TODO: assert name is Identifier node = b.f.NewFunctionExpression(modifierList, nil /*asteriskToken*/, name, typeParamList, paramList, returnTypeNode, 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 /*equalsGreaterThanToken*/, b.f.NewBlock(b.f.NewNodeList([]*ast.Node{}), false)) default: panic("Unhandled kind in signatureToSignatureDeclarationHelper") @@ -1726,7 +1726,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 { @@ -2449,7 +2449,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) @@ -2463,7 +2463,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 7d6193ae49..f0719e3b6d 100644 --- a/internal/checker/relater.go +++ b/internal/checker/relater.go @@ -4460,10 +4460,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 72114cf347..92368f55a8 100644 --- a/internal/checker/symbolaccessibility.go +++ b/internal/checker/symbolaccessibility.go @@ -573,10 +573,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 08b7ab1300..2c21523e9c 100644 --- a/internal/checker/utilities.go +++ b/internal/checker/utilities.go @@ -1935,7 +1935,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/compiler/projectreferencefilemapper.go b/internal/compiler/projectreferencefilemapper.go index 319c2ab477..8896b2541a 100644 --- a/internal/compiler/projectreferencefilemapper.go +++ b/internal/compiler/projectreferencefilemapper.go @@ -89,7 +89,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) } } @@ -154,7 +154,7 @@ func (mapper *projectReferenceFileMapper) forEachResolvedReferenceWorker( fn func(path tspath.Path, config *tsoptions.ParsedCommandLine), ) { for _, path := range references { - config, _ := mapper.configToProjectReference[path] + config := mapper.configToProjectReference[path] fn(path, config) mapper.forEachResolvedReferenceWorker(mapper.referencesInConfigFile[path], fn) } diff --git a/internal/execute/tsc.go b/internal/execute/tsc.go index 5edfe9c4d8..6e9e529f16 100644 --- a/internal/execute/tsc.go +++ b/internal/execute/tsc.go @@ -28,13 +28,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/api_test.go b/internal/format/api_test.go index 62e87898a8..a14bdf9c72 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 181b823588..3ae6cf76f2 100644 --- a/internal/format/scanner.go +++ b/internal/format/scanner.go @@ -125,7 +125,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 16695cb19c..793b29a189 100644 --- a/internal/format/span.go +++ b/internal/format/span.go @@ -122,7 +122,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 @@ -142,7 +142,6 @@ func prepareRangeContainsErrorFunction(errors []*ast.Diagnostic, originalRange c index++ } - return false // unreachable } } @@ -266,7 +265,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) } } @@ -633,7 +632,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 { @@ -1047,7 +1046,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 { @@ -1150,12 +1149,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/fourslash.go b/internal/fourslash/fourslash.go index 2bb33dee37..80e239d09b 100644 --- a/internal/fourslash/fourslash.go +++ b/internal/fourslash/fourslash.go @@ -415,10 +415,8 @@ func verifyCompletionsItems(t *testing.T, prefix string, actual []*lsproto.Compl return } nameToActualItem := make(map[string]*lsproto.CompletionItem) - if actual != nil { - for _, item := range actual { - nameToActualItem[item.Label] = item - } + for _, item := range actual { + nameToActualItem[item.Label] = item } if expected.Includes != nil { for _, item := range expected.Includes { diff --git a/internal/ls/completions.go b/internal/ls/completions.go index 586b310d9d..c3851a0a67 100644 --- a/internal/ls/completions.go +++ b/internal/ls/completions.go @@ -930,6 +930,7 @@ func getCompletionData(program *compiler.Program, typeChecker *checker.Checker, symbols = append(symbols, filteredMembers...) // Set sort texts. + //nolint:staticcheck transformObjectLiteralMembers := ptrIsTrue(preferences.IncludeCompletionsWithObjectLiteralMethodSnippets) && objectLikeContainer.Kind == ast.KindObjectLiteralExpression for _, member := range filteredMembers { diff --git a/internal/ls/findallreferences.go b/internal/ls/findallreferences.go index ff48544ba1..3d173aeb22 100644 --- a/internal/ls/findallreferences.go +++ b/internal/ls/findallreferences.go @@ -686,13 +686,11 @@ func getReferencesForThisKeyword(thisOrSuperKeyword *ast.Node, sourceFiles []*as } staticFlag &= searchSpaceNode.ModifierFlags() searchSpaceNode = searchSpaceNode.Parent // re-assign to be the owning class - break case ast.KindSourceFile: if ast.IsExternalModule(searchSpaceNode.AsSourceFile()) || isParameterName(thisOrSuperKeyword) { return nil } case ast.KindFunctionDeclaration, ast.KindFunctionExpression: - break // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: @@ -758,7 +756,6 @@ func getReferencesForSuperKeyword(superKeyword *ast.Node) []*SymbolAndEntries { case ast.KindPropertyDeclaration, ast.KindPropertySignature, ast.KindMethodDeclaration, ast.KindMethodSignature, ast.KindConstructor, ast.KindGetAccessor, ast.KindSetAccessor: staticFlag &= searchSpaceNode.ModifierFlags() searchSpaceNode = searchSpaceNode.Parent // re-assign to be the owning class - break default: return nil } @@ -1060,15 +1057,17 @@ func (state *refState) createSearch(location *ast.Node, symbol *ast.Symbol, comi symbolToSearchFor = symbol } } - text = func() string { - var name string = ast.SymbolName(symbolToSearchFor) - firstChar, _ := utf8.DecodeRuneInString(name) - lastChar, _ := utf8.DecodeLastRuneInString(name) - if firstChar == lastChar && (firstChar == '\'' || firstChar == '"' || firstChar == '`') { - return name[1 : len(name)-1] - } - return name - }() + if text == "" { + text = func() string { + name := ast.SymbolName(symbolToSearchFor) + firstChar, _ := utf8.DecodeRuneInString(name) + lastChar, _ := utf8.DecodeLastRuneInString(name) + if firstChar == lastChar && (firstChar == '\'' || firstChar == '"' || firstChar == '`') { + return name[1 : len(name)-1] + } + return name + }() + } escapedText := text if len(allSearchSymbols) == 0 { allSearchSymbols = []*ast.Symbol{symbol} diff --git a/internal/ls/hover.go b/internal/ls/hover.go index c2195d5a2e..4e92bdc752 100644 --- a/internal/ls/hover.go +++ b/internal/ls/hover.go @@ -245,7 +245,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 40f2aecf3d..8be9cdd7f2 100644 --- a/internal/ls/signaturehelp.go +++ b/internal/ls/signaturehelp.go @@ -263,7 +263,7 @@ func createSignatureHelpItems(candidates []*checker.Signature, resolvedSignature // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL help.ActiveParameter = ptrTo(lsproto.ToNullable(uint32(len(activeSignature.Parameters)))) } - if help.ActiveParameter != nil && *&help.ActiveParameter.Value > uint32(len(activeSignature.Parameters)-1) { + if help.ActiveParameter != nil && help.ActiveParameter.Value > uint32(len(activeSignature.Parameters)-1) { help.ActiveParameter = ptrTo(lsproto.ToNullable(uint32(len(activeSignature.Parameters) - 1))) } } @@ -915,13 +915,13 @@ func getArgumentOrParameterListAndIndex(node *ast.Node, sourceFile *ast.SourceFi case ast.KindNewExpression: arguments = node.Parent.AsNewExpression().Arguments case ast.KindParenthesizedExpression: - arguments = node.Parent.AsParenthesizedExpression().ExpressionBase.NodeBase.Node.ArgumentList() // !!! + arguments = node.Parent.AsParenthesizedExpression().ArgumentList() // !!! case ast.KindMethodDeclaration: - arguments = node.Parent.AsMethodDeclaration().FunctionLikeWithBodyBase.Parameters + arguments = node.Parent.AsMethodDeclaration().Parameters case ast.KindFunctionExpression: - arguments = node.Parent.AsFunctionExpression().FunctionLikeWithBodyBase.Parameters + arguments = node.Parent.AsFunctionExpression().Parameters case ast.KindArrowFunction: - arguments = node.Parent.AsArrowFunction().FunctionLikeWithBodyBase.Parameters + arguments = node.Parent.AsArrowFunction().Parameters } // Find the index of the argument that contains the node. argumentIndex := getArgumentIndex(node, arguments, sourceFile, c) @@ -1022,9 +1022,8 @@ func getContextualSignatureLocationInfo(node *ast.Node, sourceFile *ast.SourceFi case ast.KindBinaryExpression: highestBinary := getHighestBinary(parent.AsBinaryExpression()) contextualType := c.GetContextualType(highestBinary.AsNode(), checker.ContextFlagsNone) - argumentIndex := ptrTo(0) if node.Kind != ast.KindOpenParenToken { - argumentIndex = ptrTo(countBinaryExpressionParameters(parent.AsBinaryExpression()) - 1) + argumentIndex := ptrTo(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 5fc1f0cb74..7c898b5ac1 100644 --- a/internal/ls/utilities.go +++ b/internal/ls/utilities.go @@ -240,16 +240,12 @@ func getPossibleTypeArgumentsInfo(tokenIn *ast.Node, sourceFile *ast.SourceFile) } } remainingLessThanTokens-- - break case ast.KindGreaterThanGreaterThanGreaterThanToken: remainingLessThanTokens = +3 - break case ast.KindGreaterThanGreaterThanToken: remainingLessThanTokens = +2 - break case ast.KindGreaterThanToken: remainingLessThanTokens++ - break case ast.KindCloseBraceToken: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token @@ -257,7 +253,6 @@ func getPossibleTypeArgumentsInfo(tokenIn *ast.Node, sourceFile *ast.SourceFile) if token == nil { return nil } - break case ast.KindCloseParenToken: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token @@ -265,7 +260,6 @@ func getPossibleTypeArgumentsInfo(tokenIn *ast.Node, sourceFile *ast.SourceFile) if token == nil { return nil } - break case ast.KindCloseBracketToken: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token @@ -273,16 +267,14 @@ func getPossibleTypeArgumentsInfo(tokenIn *ast.Node, sourceFile *ast.SourceFile) if token == nil { return nil } - break // Valid tokens in a type name. Skip. case ast.KindCommaToken: nTypeArguments++ - break case ast.KindEqualsGreaterThanToken, ast.KindIdentifier, ast.KindStringLiteral, ast.KindNumericLiteral, ast.KindBigIntLiteral, ast.KindTrueKeyword, ast.KindFalseKeyword, ast.KindTypeOfKeyword, ast.KindExtendsKeyword, ast.KindKeyOfKeyword, ast.KindDotToken, ast.KindBarToken, ast.KindQuestionToken, ast.KindColonToken: - break + // Do nothing. default: if ast.IsTypeNode(token) { break @@ -663,7 +655,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 { @@ -887,7 +879,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: @@ -1125,7 +1117,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 fa05bf937c..cf940265d6 100644 --- a/internal/modulespecifiers/specifiers.go +++ b/internal/modulespecifiers/specifiers.go @@ -670,7 +670,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, @@ -779,14 +779,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, ) } @@ -796,7 +796,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, @@ -933,7 +933,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 63af1cc703..bb643165d0 100644 --- a/internal/packagejson/cache.go +++ b/internal/packagejson/cache.go @@ -20,15 +20,15 @@ type PackageJson struct { func (p *PackageJson) GetVersionPaths(trace func(string)) VersionPaths { p.once.Do(func() { - if p.Fields.TypesVersions.Type == JSONValueTypeNotPresent { + if p.TypesVersions.Type == JSONValueTypeNotPresent { if trace != nil { trace(diagnostics.X_package_json_does_not_have_a_0_field.Format("typesVersions")) } return } - if p.Fields.TypesVersions.Type != JSONValueTypeObject { + if p.TypesVersions.Type != JSONValueTypeObject { if trace != nil { - trace(diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2.Format("typesVersions", "object", p.Fields.TypesVersions.Type.String())) + trace(diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2.Format("typesVersions", "object", p.TypesVersions.Type.String())) } return } diff --git a/internal/parser/jsdoc.go b/internal/parser/jsdoc.go index e9e9604d73..797f0d043e 100644 --- a/internal/parser/jsdoc.go +++ b/internal/parser/jsdoc.go @@ -1217,7 +1217,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 fc1e70e19a..af4f0d8296 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -6576,7 +6576,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/configfileregistry.go b/internal/project/configfileregistry.go index e17a52bdf6..c51224b416 100644 --- a/internal/project/configfileregistry.go +++ b/internal/project/configfileregistry.go @@ -139,15 +139,11 @@ func (c *ConfigFileRegistry) updateRootFilesWatch(fileName string, entry *Config 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()...) entry.rootFilesWatch.update(context.Background(), rootFileGlobs) } diff --git a/internal/project/project.go b/internal/project/project.go index 6bd7227b85..0316372830 100644 --- a/internal/project/project.go +++ b/internal/project/project.go @@ -993,19 +993,19 @@ func (p *Project) GetFileNames(excludeFilesFromExternalLibraries bool, excludeCo } func (p *Project) print(writeFileNames bool, writeFileExplanation bool, writeFileVersionAndText bool, builder *strings.Builder) string { - builder.WriteString(fmt.Sprintf("\nProject '%s' (%s)\n", p.name, p.kind.String())) + fmt.Fprintf(builder, "\nProject '%s' (%s)\n", p.name, p.kind.String()) if p.initialLoadPending { builder.WriteString("\n\tFiles (0) InitialLoadPending\n") } else if p.program == nil { builder.WriteString("\n\tFiles (0) NoProgram\n") } else { sourceFiles := p.program.GetSourceFiles() - builder.WriteString(fmt.Sprintf("\n\tFiles (%d)\n", len(sourceFiles))) + fmt.Fprintf(builder, "\n\tFiles (%d)\n", len(sourceFiles)) if writeFileNames { for _, sourceFile := range sourceFiles { builder.WriteString("\n\t\t" + sourceFile.FileName()) if writeFileVersionAndText { - builder.WriteString(fmt.Sprintf(" %d %s", p.getFileVersion(sourceFile), sourceFile.Text())) + fmt.Fprintf(builder, " %d %s", p.getFileVersion(sourceFile), sourceFile.Text()) } } // !!! diff --git a/internal/project/validatepackagename.go b/internal/project/validatepackagename.go index 7b56da4b5a..7dc6afa115 100644 --- a/internal/project/validatepackagename.go +++ b/internal/project/validatepackagename.go @@ -49,7 +49,7 @@ func validatePackageNameWorker(packageName string, supportScopedPackage bool) (r if supportScopedPackage { if withoutScope, found := strings.CutPrefix(packageName, "@"); found { scope, scopedPackageName, found := strings.Cut(withoutScope, "/") - if found && len(scope) > 0 && len(scopedPackageName) > 0 && strings.Index(scopedPackageName, "/") == -1 { + if found && len(scope) > 0 && len(scopedPackageName) > 0 && !strings.Contains(scopedPackageName, "/") { scopeResult, _, _ := validatePackageNameWorker(scope /*supportScopedPackage*/, false) if scopeResult != NameOk { return scopeResult, scope, true diff --git a/internal/project/watch.go b/internal/project/watch.go index be463cec9e..c1199ec120 100644 --- a/internal/project/watch.go +++ b/internal/project/watch.go @@ -89,7 +89,6 @@ func (w *watchedFiles[T]) update(ctx context.Context, newData T) { } w.watcherID = watcherID w.p.Log(fmt.Sprintf("%s:: %s watches updated %s:\n%s", w.p.Name(), w.watchType, w.watcherID, formatFileList(w.globs, "\t", hr))) - return } func globMapperForTypingsInstaller(data map[tspath.Path]string) []string { diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index 967c44f10f..522fb12414 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -1340,10 +1340,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 1e990c2e4e..2038ab7f5d 100644 --- a/internal/testutil/harnessutil/sourcemap_recorder.go +++ b/internal/testutil/harnessutil/sourcemap_recorder.go @@ -17,7 +17,7 @@ type writerAggregator struct { } func (w *writerAggregator) WriteStringF(format string, args ...any) { - w.WriteString(fmt.Sprintf(format, args...)) + fmt.Fprintf(w, format, args...) } func (w *writerAggregator) WriteLine(s string) { @@ -58,7 +58,7 @@ func (d *sourceMapDecoder) decodeNextEncodedSourceMapSpan() *decodedMapping { sourceMapSpan: d.mappings.State(), } if mapping.error == nil { - mapping.error = errors.New("No encoded entry found") + mapping.error = errors.New("no encoded entry found") } return mapping } diff --git a/internal/testutil/projecttestutil/projecttestutil.go b/internal/testutil/projecttestutil/projecttestutil.go index 204dee8d9e..03d891930c 100644 --- a/internal/testutil/projecttestutil/projecttestutil.go +++ b/internal/testutil/projecttestutil/projecttestutil.go @@ -209,7 +209,7 @@ func appendTypesRegistryConfig(builder *strings.Builder, index int, entry string 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 newProjectServiceHost(files map[string]any) *ProjectServiceHost { diff --git a/internal/testutil/tsbaseline/error_baseline.go b/internal/testutil/tsbaseline/error_baseline.go index 7a27f6067a..7bd1b3d84f 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 081825feef..e247558862 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 647f516357..dd8cee8188 100644 --- a/internal/transformers/declarations/transform.go +++ b/internal/transformers/declarations/transform.go @@ -221,10 +221,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:] @@ -1212,7 +1209,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/jsx.go b/internal/transformers/jsx.go index e4f047016b..88c941aebb 100644 --- a/internal/transformers/jsx.go +++ b/internal/transformers/jsx.go @@ -838,14 +838,14 @@ var htmlEntityMatcher = regexp2.MustCompile(`&((#((\d+)|x([\da-fA-F]+)))|(\w+)); func htmlEntityReplacer(m regexp2.Match) string { decimal := m.GroupByNumber(3) if decimal != nil { - parsed, err := strconv.ParseInt(decimal.Capture.String(), 10, 32) + parsed, err := strconv.ParseInt(decimal.String(), 10, 32) if err == nil { return string(rune(parsed)) } } hex := m.GroupByNumber(4) if hex != nil { - parsed, err := strconv.ParseInt(hex.Capture.String(), 16, 32) + parsed, err := strconv.ParseInt(hex.String(), 16, 32) if err == nil { return string(rune(parsed)) } @@ -853,7 +853,7 @@ func htmlEntityReplacer(m regexp2.Match) string { word := m.GroupByNumber(5) if word != nil { // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) - res, ok := entities[word.Capture.String()] + res, ok := entities[word.String()] if ok { return string(res) } diff --git a/internal/transformers/namedevaluation.go b/internal/transformers/namedevaluation.go index dddd5c535d..604afe3e3c 100644 --- a/internal/transformers/namedevaluation.go +++ b/internal/transformers/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/tsoptions/tsconfigparsing.go b/internal/tsoptions/tsconfigparsing.go index 3128fa3cbc..d21760f59f 100644 --- a/internal/tsoptions/tsconfigparsing.go +++ b/internal/tsoptions/tsconfigparsing.go @@ -1047,7 +1047,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 { @@ -1246,7 +1246,7 @@ func parseJsonConfigFileContentWorker( } getProjectReferences := func(basePath string) []*core.ProjectReference { - var projectReferences []*core.ProjectReference = []*core.ProjectReference{} + projectReferences := []*core.ProjectReference{} newReferencesOfRaw := getPropFromRaw("references", func(element any) bool { return reflect.TypeOf(element) == orderedMapType }, "object") if newReferencesOfRaw.sliceValue != nil { for _, reference := range newReferencesOfRaw.sliceValue { @@ -1531,7 +1531,6 @@ func getFileNamesFromConfigSpecs( host vfs.FS, extraFileExtensions []FileExtensionInfo, ) []string { - extraFileExtensions = []FileExtensionInfo{} basePath = tspath.NormalizePath(basePath) keyMappper := func(value string) string { return tspath.GetCanonicalFileName(value, host.UseCaseSensitiveFileNames()) } // Literal file names (provided via the "files" array in tsconfig.json) are stored in a diff --git a/internal/tsoptions/tsconfigparsing_test.go b/internal/tsoptions/tsconfigparsing_test.go index 78be2a651b..42d96177e3 100644 --- a/internal/tsoptions/tsconfigparsing_test.go +++ b/internal/tsoptions/tsconfigparsing_test.go @@ -158,9 +158,8 @@ func TestParseConfigFileTextToJson(t *testing.T) { } type parseJsonConfigTestCase struct { - title string - noSubmoduleBaseline bool - input []testConfig + title string + input []testConfig } var parseJsonConfigFileTests = []parseJsonConfigTestCase{ @@ -238,8 +237,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": { @@ -442,8 +440,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", @@ -460,8 +457,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" @@ -500,8 +496,7 @@ var parseJsonConfigFileTests = []parseJsonConfigTestCase{ }}, }, { - title: "handles empty types array", - noSubmoduleBaseline: true, + title: "handles empty types array", input: []testConfig{{ jsonText: `{ "compilerOptions": { @@ -556,7 +551,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) }) } } @@ -583,7 +578,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) }) } } @@ -610,8 +605,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 @@ -767,12 +762,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) }) } } diff --git a/internal/vfs/cachedvfs/cachedvfs.go b/internal/vfs/cachedvfs/cachedvfs.go index 0e284fe043..f802bf4a9a 100644 --- a/internal/vfs/cachedvfs/cachedvfs.go +++ b/internal/vfs/cachedvfs/cachedvfs.go @@ -119,7 +119,7 @@ func (fsys *FS) Remove(path string) error { func (fsys *FS) Stat(path string) vfs.FileInfo { if fsys.enabled.Load() { if ret, ok := fsys.statCache.Load(path); ok { - return ret.(vfs.FileInfo) + return ret } }