Debian Codegraph @

gopls/internal/analysis/unusedparams/unusedparams.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 unusedparams
6
7 import (
8 _ "embed"
9 "fmt"
10 "go/ast"
11 "go/types"
12
13 "golang.org/x/tools/go/analysis"
14 "golang.org/x/tools/go/analysis/passes/inspect"
15 "golang.org/x/tools/go/ast/edge"
16 "golang.org/x/tools/go/ast/inspector"
17 "golang.org/x/tools/gopls/internal/util/moreslices"
18 "golang.org/x/tools/internal/analysis/analyzerutil"
19 "golang.org/x/tools/internal/astutil"
20 "golang.org/x/tools/internal/typesinternal"
21 )
22
23 //go:embed doc.go
24 var doc string
25
26 var Analyzer = &analysis.Analyzer{
27 Name: "unusedparams",
28 Doc: analyzerutil.MustExtractDoc(doc, "unusedparams"),
29 Requires: []*analysis.Analyzer{inspect.Analyzer},
30 Run: run,
31 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedparams",
32 }
33
34 const FixCategory = "unusedparams" // recognized by gopls ApplyFix
35
36 func run(pass *analysis.Pass) (any, error) {
37 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
38
39 // First find all "address-taken" functions.
40 // We must conservatively assume that their parameters
41 // are all required to conform to some signature.
42 //
43 // A named function is address-taken if it is somewhere
44 // used not in call position:
45 //
46 // f(...) // not address-taken
47 // use(f) // address-taken
48 //
49 // A literal function is address-taken if it is not
50 // immediately bound to a variable, or if that variable is
51 // used not in call position:
52 //
53 // f := func() { ... }; f() used only in call position
54 // var f func(); f = func() { ...f()... }; f() ditto
55 // use(func() { ... }) address-taken
56 //
57
58 // Note: this algorithm relies on the assumption that the
59 // analyzer is called only for the "widest" package for a
60 // given file: that is, p_test in preference to p, if both
61 // exist. Analyzing only package p may produce diagnostics
62 // that would be falsified based on declarations in p_test.go
63 // files. The gopls analysis driver does this, but most
64 // drivers to not, so running this command in, say,
65 // unitchecker or multichecker may produce incorrect results.
66
67 // Gather global information:
68 // - uses of functions not in call position
69 // - unexported interface methods
70 // - all referenced variables
71
72 usesOutsideCall := make(map[types.Object][]*ast.Ident)
73 unexportedIMethodNames := make(map[string]bool)
74 {
75 callPosn := make(map[*ast.Ident]bool) // all idents f appearing in f() calls
76 filter := []ast.Node{
77 (*ast.CallExpr)(nil),
78 (*ast.InterfaceType)(nil),
79 }
80 inspect.Preorder(filter, func(n ast.Node) {
81 switch n := n.(type) {
82 case *ast.CallExpr:
83 id := typesinternal.UsedIdent(pass.TypesInfo, n.Fun)
84 // Find object:
85 // record non-exported function, method, or func-typed var.
86 if id != nil && !id.IsExported() {
87 switch pass.TypesInfo.Uses[id].(type) {
88 case *types.Func, *types.Var:
89 callPosn[id] = true
90 }
91 }
92
93 case *ast.InterfaceType:
94 // Record the set of names of unexported interface methods.
95 // (It would be more precise to record signatures but
96 // generics makes it tricky, and this conservative
97 // heuristic is close enough.)
98 t := pass.TypesInfo.TypeOf(n).(*types.Interface)
99 for m := range t.ExplicitMethods() {
100 if !m.Exported() && m.Name() != "_" {
101 unexportedIMethodNames[m.Name()] = true
102 }
103 }
104 }
105 })
106
107 for id, obj := range pass.TypesInfo.Uses {
108 if !callPosn[id] {
109 // This includes "f = func() {...}", which we deal with below.
110 usesOutsideCall[obj] = append(usesOutsideCall[obj], id)
111 }
112 }
113 }
114
115 // Find all vars (notably parameters) that are used.
116 usedVars := make(map[*types.Var]bool)
117 for _, obj := range pass.TypesInfo.Uses {
118 if v, ok := obj.(*types.Var); ok {
119 if v.IsField() {
120 continue // no point gathering these
121 }
122 usedVars[v] = true
123 }
124 }
125
126 // Check each non-address-taken function's parameters are all used.
127 funcloop:
128 for c := range inspect.Root().Preorder((*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) {
129 var (
130 fn types.Object // function symbol (*Func, possibly *Var for a FuncLit)
131 ftype *ast.FuncType
132 body *ast.BlockStmt
133 )
134 switch n := c.Node().(type) {
135 case *ast.FuncDecl:
136 // We can't analyze non-Go functions.
137 if n.Body == nil {
138 continue
139 }
140
141 // Ignore exported functions and methods: we
142 // must assume they may be address-taken in
143 // another package.
144 if n.Name.IsExported() {
145 continue
146 }
147
148 // Ignore methods that match the name of any
149 // interface method declared in this package,
150 // as the method's signature may need to conform
151 // to the interface.
152 if n.Recv != nil && unexportedIMethodNames[n.Name.Name] {
153 continue
154 }
155
156 fn = pass.TypesInfo.Defs[n.Name].(*types.Func)
157 ftype, body = n.Type, n.Body
158
159 case *ast.FuncLit:
160 // Find the symbol for the variable (if any)
161 // to which the FuncLit is bound.
162 // (We don't bother to allow ParenExprs.)
163 switch parent := c.Parent().Node().(type) {
164 case *ast.AssignStmt:
165 // f = func() {...}
166 // f := func() {...}
167 if ek, idx := c.ParentEdge(); ek == edge.AssignStmt_Rhs {
168 // Inv: n == AssignStmt.Rhs[idx]
169 if id, ok := parent.Lhs[idx].(*ast.Ident); ok {
170 fn = pass.TypesInfo.ObjectOf(id)
171
172 // Edge case: f = func() {...}
173 // should not count as a use.
174 if pass.TypesInfo.Uses[id] != nil {
175 usesOutsideCall[fn] = moreslices.Remove(usesOutsideCall[fn], id)
176 }
177
178 if fn == nil && id.Name == "_" {
179 // Edge case: _ = func() {...}
180 // has no local var. Fake one.
181 v := types.NewVar(id.Pos(), pass.Pkg, id.Name, pass.TypesInfo.TypeOf(n))
182 v.SetKind(types.LocalVar)
183 fn = v
184 }
185 }
186 }
187
188 case *ast.ValueSpec:
189 // var f = func() { ... }
190 // (unless f is an exported package-level var)
191 for i, val := range parent.Values {
192 if val == n {
193 v := pass.TypesInfo.Defs[parent.Names[i]]
194 if !(v.Parent() == pass.Pkg.Scope() && v.Exported()) {
195 fn = v
196 }
197 break
198 }
199 }
200 }
201
202 ftype, body = n.Type, n.Body
203 }
204
205 // Ignore address-taken functions and methods: unused
206 // parameters may be needed to conform to a func type.
207 if fn == nil || len(usesOutsideCall[fn]) > 0 {
208 continue
209 }
210
211 // If there are no parameters, there are no unused parameters.
212 if ftype.Params.NumFields() == 0 {
213 continue
214 }
215
216 // To reduce false positives, ignore functions with an
217 // empty or panic body.
218 //
219 // We choose not to ignore functions whose body is a
220 // single return statement (as earlier versions did)
221 // func f() { return }
222 // func f() { return g(...) }
223 // as we suspect that was just heuristic to reduce
224 // false positives in the earlier unsound algorithm.
225 switch len(body.List) {
226 case 0:
227 // Empty body. Although the parameter is
228 // unnecessary, it's pretty obvious to the
229 // reader that that's the case, so we allow it.
230 continue // func f() {}
231 case 1:
232 if stmt, ok := body.List[0].(*ast.ExprStmt); ok {
233 // We allow a panic body, as it is often a
234 // placeholder for a future implementation:
235 // func f() { panic(...) }
236 if call, ok := stmt.X.(*ast.CallExpr); ok {
237 if fun, ok := call.Fun.(*ast.Ident); ok && fun.Name == "panic" {
238 continue
239 }
240 }
241 }
242 }
243
244 // Don't report diagnostics on generated files.
245 // (We can't skip analysis of generated files, though.)
246 if ast.IsGenerated(astutil.EnclosingFile(c)) {
247 continue funcloop
248 }
249
250 // Report each unused parameter.
251 for _, field := range ftype.Params.List {
252 for _, id := range field.Names {
253 if id.Name == "_" {
254 continue
255 }
256 param := pass.TypesInfo.Defs[id].(*types.Var)
257 if !usedVars[param] {
258 start, end := field.Pos(), field.End()
259 if len(field.Names) > 1 {
260 start, end = id.Pos(), id.End()
261 }
262
263 // This diagnostic carries both an edit-based fix to
264 // rename the unused parameter, and a command-based fix
265 // to remove it (see golang.RemoveUnusedParameter).
266 pass.Report(analysis.Diagnostic{
267 Pos: start,
268 End: end,
269 Message: fmt.Sprintf("unused parameter: %s", id.Name),
270 Category: FixCategory,
271 SuggestedFixes: []analysis.SuggestedFix{
272 {
273 Message: `Rename parameter to "_"`,
274 TextEdits: []analysis.TextEdit{{
275 Pos: id.Pos(),
276 End: id.End(),
277 NewText: []byte("_"),
278 }},
279 },
280 {
281 Message: fmt.Sprintf("Remove unused parameter %q", id.Name),
282 // No TextEdits => computed by gopls command
283 },
284 },
285 })
286 }
287 }
288 }
289 }
290 return nil, nil
291 }