Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable staticcheck #717

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ linters:
- perfsprint
- predeclared
- reassign
- staticcheck
- testableexamples
- tparallel
- unconvert
Expand All @@ -52,7 +53,6 @@ linters:
# - gocritic
# - gosec
# - revive
# - staticcheck
# - testifylint
# - unparam
# - unused
Expand All @@ -62,6 +62,20 @@ linters:
customlint:
type: module

staticcheck:
checks:
- all
- -QF1001
- -QF1003
- -SA6005
- -SA9003
- -ST1000
- -ST1003
- -ST1016
- -ST1020
- -ST1021
- -ST1022

exclusions:
presets:
- comments
Expand Down
10 changes: 5 additions & 5 deletions internal/astnav/tokens_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,15 @@ func writeRangeDiff(output *strings.Builder, file *ast.SourceFile, diff tokenDif
output.WriteString("\n\n")
}

output.WriteString(fmt.Sprintf("〚Positions: [%d, %d]〛\n", rng.Pos(), rng.End()))
output.WriteString(fmt.Sprintf("【TS: %s [%d, %d)】\n", diff.tsToken.Kind, diff.tsToken.Pos, diff.tsToken.End))
output.WriteString(fmt.Sprintf("《Go: %s [%d, %d)》\n", diff.goToken.Kind, diff.goToken.Pos, diff.goToken.End))
fmt.Fprintf(output, "〚Positions: [%d, %d]〛\n", rng.Pos(), rng.End())
fmt.Fprintf(output, "【TS: %s [%d, %d)】\n", diff.tsToken.Kind, diff.tsToken.Pos, diff.tsToken.End)
fmt.Fprintf(output, "《Go: %s [%d, %d)》\n", diff.goToken.Kind, diff.goToken.Pos, diff.goToken.End)
for line := contextStart; line <= contextEnd; line++ {
if truncate, skipTo := shouldTruncate(line); truncate {
output.WriteString(fmt.Sprintf("%s │........ %d lines omitted ........\n", strings.Repeat(" ", digits), skipTo-line+1))
fmt.Fprintf(output, "%s │........ %d lines omitted ........\n", strings.Repeat(" ", digits), skipTo-line+1)
line = skipTo
}
output.WriteString(fmt.Sprintf("%*d │", digits, line+1))
fmt.Fprintf(output, "%*d │", digits, line+1)
end := len(file.Text()) + 1
if line < len(lines)-1 {
end = int(lines[line+1])
Expand Down
6 changes: 3 additions & 3 deletions internal/binder/binder.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,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
}
Expand All @@ -261,7 +261,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
}
Expand Down Expand Up @@ -2035,7 +2035,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) {
Expand Down
45 changes: 19 additions & 26 deletions internal/checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -1594,13 +1594,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*/)
}
Expand Down Expand Up @@ -10194,10 +10187,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
Expand Down Expand Up @@ -12406,10 +12399,10 @@ func (c *Checker) checkObjectLiteral(node *ast.Node, checkMode CheckMode) *Type
}
if ast.IsPropertyAssignment(memberDecl) || ast.IsShorthandPropertyAssignment(memberDecl) || ast.IsObjectLiteralMethod(memberDecl) {
var t *Type
switch {
case memberDecl.Kind == ast.KindPropertyAssignment:
switch memberDecl.Kind {
case ast.KindPropertyAssignment:
t = c.checkPropertyAssignment(memberDecl, checkMode)
case memberDecl.Kind == ast.KindShorthandPropertyAssignment:
case ast.KindShorthandPropertyAssignment:
var expr *ast.Node
if !inDestructuringPattern {
expr = memberDecl.AsShorthandPropertyAssignment().ObjectAssignmentInitializer
Expand Down Expand Up @@ -15562,7 +15555,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 {
Expand Down Expand Up @@ -17041,12 +17034,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})
Expand Down Expand Up @@ -18469,7 +18462,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)
Expand Down Expand Up @@ -19480,7 +19473,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]
Expand Down Expand Up @@ -27501,10 +27494,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
Expand Down Expand Up @@ -28874,10 +28867,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
Expand Down
2 changes: 1 addition & 1 deletion internal/checker/flow.go
Original file line number Diff line number Diff line change
Expand Up @@ -1976,7 +1976,7 @@ func (c *Checker) getSwitchClauseTypeOfWitnesses(node *ast.Node) []string {

// Return the combined not-equal type facts for all cases except those between the start and end indices.
func (c *Checker) getNotEqualFactsFromTypeofSwitch(start int, end int, witnesses []string) TypeFacts {
var facts TypeFacts = TypeFactsNone
facts := TypeFactsNone
for i, witness := range witnesses {
if (i < start || i >= end) && witness != "" {
f, ok := typeofNEFacts[witness]
Expand Down
12 changes: 6 additions & 6 deletions internal/checker/grammarchecks.go
Original file line number Diff line number Diff line change
Expand Up @@ -1491,7 +1491,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)
Expand Down Expand Up @@ -1794,14 +1794,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")
Expand Down
6 changes: 3 additions & 3 deletions internal/checker/inference.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion internal/checker/jsx.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme
}
// We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
if parent != nil && parent.AsJsxElement().OpeningElement == openingLikeElement && len(getSemanticJsxChildren(parent.AsJsxElement().Children.Nodes)) != 0 {
var childTypes []*Type = c.checkJsxChildren(parent, checkMode)
var childTypes = c.checkJsxChildren(parent, checkMode)
if !hasSpreadAnyType && jsxChildrenPropertyName != ast.InternalSymbolNameMissing && jsxChildrenPropertyName != "" {
// Error if there is a attribute named "children" explicitly specified and children element.
// This is because children element will overwrite the value from attributes.
Expand Down
6 changes: 3 additions & 3 deletions internal/checker/relater.go
Original file line number Diff line number Diff line change
Expand Up @@ -4453,10 +4453,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 {
Expand Down
6 changes: 3 additions & 3 deletions internal/compiler/packagejson/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion internal/parser/jsdoc.go
Original file line number Diff line number Diff line change
Expand Up @@ -1423,7 +1423,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.
Expand Down
2 changes: 1 addition & 1 deletion internal/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6601,7 +6601,7 @@ func processPragmasIntoFields(context *ast.SourceFile /* !!! reportDiagnostic fu
case "ts-check", "ts-nocheck":
// _last_ of either nocheck or check in a file is the "winner"
for _, directive := range context.Pragmas {
if context.CheckJsDirective == nil || directive.TextRange.Pos() > context.CheckJsDirective.Range.Pos() {
if context.CheckJsDirective == nil || directive.Pos() > context.CheckJsDirective.Range.Pos() {
context.CheckJsDirective = &ast.CheckJsDirective{
Enabled: directive.Name == "ts-check",
Range: directive.CommentRange,
Expand Down
6 changes: 2 additions & 4 deletions internal/scanner/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -1361,10 +1361,8 @@ func (s *Scanner) ScanJSDocToken() ast.Kind {

if isIdentifierStart(ch, s.languageVersion) {
char := ch
for {
if s.pos >= len(s.text) {
break
}
for s.pos < len(s.text) {

char, size = s.charAndSize()
if !isIdentifierPart(char, s.languageVersion) && char != '-' {
break
Expand Down
4 changes: 2 additions & 2 deletions internal/testutil/harnessutil/sourcemap_recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion internal/testutil/tsbaseline/error_baseline.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 1 addition & 5 deletions internal/testutil/tsbaseline/sourcemap_baseline.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,7 @@ func createSourceMapPreviewLink(sourceMap *harnessutil.TestFile, result *harness
return ""
}

var sourceTDs []*harnessutil.TestFile
////if len(sourcemapJSON.Sources) == len(inputsAndOutputs.Inputs) {
//// sourceTDs = inputsAndOutputs.Inputs
////} else {
sourceTDs = core.Map(sourcemapJSON.Sources, func(s string) *harnessutil.TestFile {
var sourceTDs = core.Map(sourcemapJSON.Sources, func(s string) *harnessutil.TestFile {
return core.Find(result.Inputs(), func(td *harnessutil.TestFile) bool {
return strings.HasSuffix(td.UnitName, s)
})
Expand Down
5 changes: 2 additions & 3 deletions internal/tsoptions/tsconfigparsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,7 @@ func parseConfig(
if ownConfig.extendedConfigPath != nil {
// copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
resolutionStack = append(resolutionStack, resolvedPath)
var result *extendsResult = &extendsResult{
result := &extendsResult{
options: &core.CompilerOptions{},
}
if reflect.TypeOf(ownConfig.extendedConfigPath).Kind() == reflect.String {
Expand Down Expand Up @@ -1152,7 +1152,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 {
Expand Down Expand Up @@ -1430,7 +1430,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
Expand Down
Loading
Loading