Debian Codegraph @

gopls/internal/analysis/unusedfunc/unusedfunc.go

raw symbols SCIP
1 // Copyright 2024 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 unusedfunc
6
7 import (
8 _ "embed"
9 "fmt"
10 "go/ast"
11 "go/token"
12 "go/types"
13 "strings"
14
15 "golang.org/x/tools/go/analysis"
16 "golang.org/x/tools/go/analysis/passes/inspect"
17 "golang.org/x/tools/go/ast/edge"
18 "golang.org/x/tools/go/ast/inspector"
19 "golang.org/x/tools/internal/analysis/analyzerutil"
20 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
21 "golang.org/x/tools/internal/astutil"
22 "golang.org/x/tools/internal/packagepath"
23 "golang.org/x/tools/internal/refactor"
24 "golang.org/x/tools/internal/typesinternal/typeindex"
25 )
26
27 // Assumptions
28 //
29 // Like unusedparams, this analyzer depends on the invariant of the
30 // gopls analysis driver that only the "widest" package (the one with
31 // the most files) for a given file is analyzed. This invariant allows
32 // the algorithm to make "closed world" assumptions about the target
33 // package. (In general, analysis of Go test packages cannot make that
34 // assumption because in-package tests add new files to existing
35 // packages, potentially invalidating results.) Consequently, running
36 // this analyzer in, say, unitchecker or multichecker may produce
37 // incorrect results.
38 //
39 // A function is unreferenced if it is never referenced except within
40 // its own declaration, and it is unexported. (Exported functions must
41 // be assumed to be referenced from other packages.)
42 //
43 // For methods, we assume that the receiver type is "live" (variables
44 // of that type are created) and "address taken" (its rtype ends up in
45 // an at least one interface value). This means exported methods may
46 // be called via reflection or by interfaces defined in other
47 // packages, so again we are concerned only with unexported methods.
48 //
49 // To discount the possibility of a method being called via an
50 // interface, we must additionally ensure that no literal interface
51 // type within the package has a method of the same name.
52 // (Unexported methods cannot be called through interfaces declared
53 // in other packages because each package has a private namespace
54 // for unexported identifiers.)
55 //
56 // Types (sans methods), constants, and vars are more straightforward.
57 //
58 // For enums (defined here as const decls where all consts have the same type),
59 // we only require that one of the names in the group is used, since it is
60 // common for at least some values to be unused when they are added for
61 // symmetry, future use, or to conform to some external pattern.
62
63 //go:embed doc.go
64 var doc string
65
66 var Analyzer = &analysis.Analyzer{
67 Name: "unusedfunc",
68 Doc: analyzerutil.MustExtractDoc(doc, "unusedfunc"),
69 Requires: []*analysis.Analyzer{inspect.Analyzer, typeindexanalyzer.Analyzer},
70 Run: run,
71 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedfunc",
72 }
73
74 func run(pass *analysis.Pass) (any, error) {
75 // The standard library makes heavy use of intrinsics, linknames, etc,
76 // that confuse this algorithm; so skip it (#74130).
77 if packagepath.IsStdPackage(pass.Pkg.Path()) {
78 return nil, nil
79 }
80
81 var (
82 inspect = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
83 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
84 )
85
86 // Gather names of unexported interface methods declared in this package.
87 localIfaceMethods := make(map[string]bool)
88 nodeFilter := []ast.Node{(*ast.InterfaceType)(nil)}
89 inspect.Preorder(nodeFilter, func(n ast.Node) {
90 iface := n.(*ast.InterfaceType)
91 for _, field := range iface.Methods.List {
92 if len(field.Names) > 0 {
93 id := field.Names[0]
94 if !id.IsExported() {
95 // TODO(adonovan): check not just name but signature too.
96 localIfaceMethods[id.Name] = true
97 }
98 }
99 }
100 })
101
102 // used reports whether the object declared at id is (potentially) used.
103 // References within curSelf are ignored.
104 used := func(id *ast.Ident, curSelf inspector.Cursor) bool {
105 // Exported functions may be called from other packages.
106 if id.IsExported() {
107 return true
108 }
109
110 // Blank functions are exempt from diagnostics.
111 if id.Name == "_" {
112 return true
113 }
114
115 // Check for uses (including selections).
116 obj := pass.TypesInfo.Defs[id]
117 for curId := range index.Uses(obj) {
118 // Ignore self references.
119 if !curSelf.Contains(curId) {
120 return true // symbol is referenced
121 }
122 }
123 return false
124 }
125
126 // checkUnused reports a diagnostic if the object declared at id
127 // is unexported and unused. References within curSelf are ignored.
128 checkUnused := func(noun string, id *ast.Ident, curSelf inspector.Cursor, delete func() []analysis.TextEdit) {
129 if used(id, curSelf) {
130 return
131 }
132
133 pass.Report(analysis.Diagnostic{
134 Pos: id.Pos(),
135 End: id.End(),
136 Message: fmt.Sprintf("%s %q is unused", noun, id.Name),
137 SuggestedFixes: []analysis.SuggestedFix{{
138 Message: fmt.Sprintf("Delete %s %q", noun, id.Name),
139 TextEdits: delete(),
140 }},
141 })
142 }
143
144 // isEnum returns true if the decl curGenDecl is a const decl with more than one
145 // spec where all consts are the same type.
146 isEnum := func(curGenDecl inspector.Cursor) bool {
147 decl := curGenDecl.Node().(*ast.GenDecl)
148 if decl.Tok != token.CONST || len(decl.Specs) < 2 {
149 return false
150 }
151 var prevType types.Type
152 for _, spec := range decl.Specs {
153 spec := spec.(*ast.ValueSpec)
154 for _, id := range spec.Names {
155 curType := pass.TypesInfo.TypeOf(id)
156 if prevType != nil && !types.Identical(curType, prevType) {
157 return false
158 }
159 prevType = curType
160 }
161 }
162 return true
163 }
164
165 // Check each package-level declaration (and method) for uses.
166 for curFile := range inspect.Root().Preorder((*ast.File)(nil)) {
167 file := curFile.Node().(*ast.File)
168 if ast.IsGenerated(file) {
169 continue // skip generated files
170 }
171 tokFile := pass.Fset.File(file.Pos())
172
173 nextDecl:
174 for i := range file.Decls {
175 curDecl := curFile.ChildAt(edge.File_Decls, i)
176 decl := curDecl.Node().(ast.Decl)
177
178 // Skip if there's a preceding //go:linkname directive.
179 // (This is relevant only to func and var decls.)
180 //
181 // (A program can link fine without such a directive,
182 // but it is bad style; and the directive may
183 // appear anywhere, not just on the preceding line,
184 // but again that is poor form.)
185 if doc := astutil.DocComment(decl); doc != nil {
186 for _, comment := range doc.List {
187 // TODO(adonovan): use ast.ParseDirective when #68021 lands.
188 if strings.HasPrefix(comment.Text, "//go:linkname ") {
189 continue nextDecl
190 }
191 }
192 }
193
194 switch decl := decl.(type) {
195 case *ast.FuncDecl:
196 id := decl.Name
197 // An (unexported) method whose name matches an
198 // interface method declared in the same package
199 // may be dynamically called via that interface.
200 if decl.Recv != nil && localIfaceMethods[id.Name] {
201 continue
202 }
203
204 // main and init functions are implicitly always used
205 if decl.Recv == nil && (id.Name == "init" || id.Name == "main") {
206 continue
207 }
208
209 noun := cond(decl.Recv == nil, "function", "method")
210 checkUnused(noun, decl.Name, curDecl, func() []analysis.TextEdit {
211 return refactor.DeleteDecl(tokFile, curDecl)
212 })
213
214 case *ast.GenDecl:
215 switch decl.Tok {
216 case token.TYPE:
217 for i, spec := range decl.Specs {
218 var (
219 spec = spec.(*ast.TypeSpec)
220 id = spec.Name
221 curSpec = curDecl.ChildAt(edge.GenDecl_Specs, i)
222 )
223 checkUnused("type", id, curSpec, func() []analysis.TextEdit {
224 return refactor.DeleteSpec(tokFile, curSpec)
225 })
226 }
227
228 case token.CONST, token.VAR:
229 if isEnum(curDecl) {
230 // For enum-like constants, a use of any
231 // name acts as a use of the whole.
232 // TODO(mkalil): This results in false negatives, for example:
233 // const (
234 // a = 0
235 // b = a + 1
236 // )
237 // We report that a is "used" even though is not used outside the const
238 // decl, and since we do not report errors in enums that have at least one
239 // used name, we do not report a diagnostic at all.
240 allUnused := true
241 for i, spec := range decl.Specs {
242 curSpec := curDecl.ChildAt(edge.GenDecl_Specs, i)
243 for _, id := range spec.(*ast.ValueSpec).Names {
244 if used(id, curSpec) {
245 allUnused = false
246 break
247 }
248 }
249 }
250 if allUnused {
251 edits := refactor.DeleteDecl(tokFile, curDecl)
252 pass.Report(analysis.Diagnostic{
253 Pos: decl.Pos(),
254 End: decl.End(),
255 Message: "all values in this set of constants are unused",
256 SuggestedFixes: []analysis.SuggestedFix{{
257 Message: "Delete the constants declaration",
258 TextEdits: edits,
259 }},
260 })
261 }
262 } else {
263 for i, spec := range decl.Specs {
264 spec := spec.(*ast.ValueSpec)
265 curSpec := curDecl.ChildAt(edge.GenDecl_Specs, i)
266
267 for j, id := range spec.Names {
268 checkUnused(decl.Tok.String(), id, curSpec, func() []analysis.TextEdit {
269 curId := curSpec.ChildAt(edge.ValueSpec_Names, j)
270 return refactor.DeleteVar(tokFile, pass.TypesInfo, curId)
271 })
272 }
273 }
274 }
275 }
276 }
277 }
278 }
279
280 return nil, nil
281 }
282
283 func cond[T any](cond bool, t, f T) T {
284 if cond {
285 return t
286 } else {
287 return f
288 }
289 }