Debian Codegraph @

gopls/internal/analysis/unusedvariable/unusedvariable.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package unusedvariable defines an analyzer that checks for unused variables.
6 package unusedvariable
7
8 import (
9 "fmt"
10 "go/ast"
11 "regexp"
12 "strings"
13
14 "golang.org/x/tools/go/analysis"
15 "golang.org/x/tools/go/analysis/passes/inspect"
16 "golang.org/x/tools/go/ast/inspector"
17 "golang.org/x/tools/internal/refactor"
18 )
19
20 const Doc = `check for unused variables and suggest fixes`
21
22 var Analyzer = &analysis.Analyzer{
23 Name: "unusedvariable",
24 Doc: Doc,
25 Requires: []*analysis.Analyzer{inspect.Analyzer},
26 Run: run,
27 RunDespiteErrors: true, // an unusedvariable diagnostic is a compile error
28 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedvariable",
29 }
30
31 // The suffix for this error message changed in Go 1.20 and Go 1.23.
32 var unusedVariableRegexp = []*regexp.Regexp{
33 regexp.MustCompile("^(.*) declared and not used$"), // Go 1.20+
34 regexp.MustCompile("^declared and not used: (.*)$"), // Go 1.23+
35 }
36
37 func run(pass *analysis.Pass) (any, error) {
38 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
39
40 for _, typeErr := range pass.TypeErrors {
41 for _, re := range unusedVariableRegexp {
42 match := re.FindStringSubmatch(typeErr.Msg)
43 if len(match) == 0 {
44 continue
45 }
46 // Since Go 1.23, go/types' error messages quote vars as `v'.
47 varName := strings.Trim(match[1], "`'")
48
49 curId, ok := inspect.Root().FindByPos(typeErr.Pos, typeErr.Pos)
50 if !ok {
51 continue // can't find error node
52 }
53 ident, ok := curId.Node().(*ast.Ident)
54 if !ok || ident.Name != varName {
55 continue // not the right identifier
56 }
57
58 tokFile := pass.Fset.File(ident.Pos())
59 edits := refactor.DeleteVar(tokFile, pass.TypesInfo, curId)
60 if len(edits) > 0 {
61 pass.Report(analysis.Diagnostic{
62 Pos: ident.Pos(),
63 End: ident.End(),
64 Message: typeErr.Msg,
65 SuggestedFixes: []analysis.SuggestedFix{{
66 Message: fmt.Sprintf("Remove variable %s", ident.Name),
67 TextEdits: edits,
68 }},
69 })
70 }
71 }
72 }
73
74 return nil, nil
75 }