forked from alecthomas/gometalinter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.go
458 lines (424 loc) · 10.4 KB
/
check.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// Copyright (c) 2017, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
// Package check implements the unparam linter. Note that its API is not
// stable.
package check // import "mvdan.cc/unparam/check"
import (
"fmt"
"go/ast"
"go/constant"
"go/parser"
"go/token"
"go/types"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"golang.org/x/tools/go/callgraph"
"golang.org/x/tools/go/callgraph/cha"
"golang.org/x/tools/go/loader"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/ssautil"
"github.com/kisielk/gotool"
"mvdan.cc/lint"
)
func UnusedParams(tests, debug bool, args ...string) ([]string, error) {
wd, err := os.Getwd()
if err != nil {
return nil, err
}
c := &Checker{
wd: wd,
tests: tests,
}
if debug {
c.debugLog = os.Stderr
}
return c.lines(args...)
}
type Checker struct {
lprog *loader.Program
prog *ssa.Program
wd string
tests bool
debugLog io.Writer
cachedDeclCounts map[string]map[string]int
}
var (
_ lint.Checker = (*Checker)(nil)
_ lint.WithSSA = (*Checker)(nil)
skipValue = new(ssa.Value)
)
func (c *Checker) lines(args ...string) ([]string, error) {
paths := gotool.ImportPaths(args)
var conf loader.Config
if _, err := conf.FromArgs(paths, c.tests); err != nil {
return nil, err
}
lprog, err := conf.Load()
if err != nil {
return nil, err
}
prog := ssautil.CreateProgram(lprog, 0)
prog.Build()
c.Program(lprog)
c.ProgramSSA(prog)
issues, err := c.Check()
if err != nil {
return nil, err
}
lines := make([]string, len(issues))
for i, issue := range issues {
fpos := prog.Fset.Position(issue.Pos()).String()
if strings.HasPrefix(fpos, c.wd) {
fpos = fpos[len(c.wd)+1:]
}
lines[i] = fmt.Sprintf("%s: %s", fpos, issue.Message())
}
return lines, nil
}
type Issue struct {
pos token.Pos
msg string
}
func (i Issue) Pos() token.Pos { return i.pos }
func (i Issue) Message() string { return i.msg }
func (c *Checker) Program(lprog *loader.Program) {
c.lprog = lprog
}
func (c *Checker) ProgramSSA(prog *ssa.Program) {
c.prog = prog
}
func (c *Checker) debug(format string, a ...interface{}) {
if c.debugLog != nil {
fmt.Fprintf(c.debugLog, format, a...)
}
}
func (c *Checker) Check() ([]lint.Issue, error) {
c.cachedDeclCounts = make(map[string]map[string]int)
wantPkg := make(map[*types.Package]*loader.PackageInfo)
for _, info := range c.lprog.InitialPackages() {
wantPkg[info.Pkg] = info
}
cg := cha.CallGraph(c.prog)
var issues []lint.Issue
funcLoop:
for fn := range ssautil.AllFunctions(c.prog) {
if fn.Pkg == nil { // builtin?
continue
}
if len(fn.Blocks) == 0 { // stub
continue
}
info := wantPkg[fn.Pkg.Pkg]
if info == nil { // not part of given pkgs
continue
}
c.debug("func %s\n", fn.String())
if dummyImpl(fn.Blocks[0]) { // panic implementation
c.debug(" skip - dummy implementation\n")
continue
}
for _, edge := range cg.Nodes[fn].In {
switch edge.Site.Common().Value.(type) {
case *ssa.Function:
default:
// called via a parameter or field, type
// is set in stone.
c.debug(" skip - type is required via call\n")
continue funcLoop
}
}
if c.multipleImpls(info, fn) {
c.debug(" skip - multiple implementations via build tags\n")
continue
}
callers := cg.Nodes[fn].In
results := fn.Signature.Results()
// skip exported funcs, as well as those that are
// entirely unused
if !ast.IsExported(fn.Name()) && len(callers) > 0 {
resLoop:
for i := 0; i < results.Len(); i++ {
for _, edge := range callers {
val := edge.Site.Value()
if val == nil { // e.g. go statement
continue
}
for _, instr := range *val.Referrers() {
extract, ok := instr.(*ssa.Extract)
if !ok {
continue resLoop // direct, real use
}
if extract.Index != i {
continue // not the same result param
}
if len(*extract.Referrers()) > 0 {
continue resLoop // real use after extraction
}
}
}
res := results.At(i)
name := paramDesc(i, res)
issues = append(issues, Issue{
pos: res.Pos(),
msg: fmt.Sprintf("result %s is never used", name),
})
}
}
seen := make([]constant.Value, results.Len())
numRets := 0
for _, block := range fn.Blocks {
last := block.Instrs[len(block.Instrs)-1]
ret, ok := last.(*ssa.Return)
if !ok {
continue
}
for i, val := range ret.Results {
cnst, ok := val.(*ssa.Const)
switch {
case !ok:
seen[i] = nil
case numRets == 0:
seen[i] = cnst.Value
case seen[i] == nil:
case !constant.Compare(seen[i], token.EQL, cnst.Value):
seen[i] = nil
}
}
numRets++
}
if numRets > 1 {
for i, val := range seen {
if val == nil {
continue
}
res := results.At(i)
name := paramDesc(i, res)
issues = append(issues, Issue{
pos: res.Pos(),
msg: fmt.Sprintf("result %s is always %s", name, val.String()),
})
}
}
for i, par := range fn.Params {
if i == 0 && fn.Signature.Recv() != nil { // receiver
continue
}
c.debug("%s\n", par.String())
switch par.Object().Name() {
case "", "_": // unnamed
c.debug(" skip - unnamed\n")
continue
}
reason := "is unused"
if cv := receivesSameValue(cg.Nodes[fn].In, par, i); cv != nil {
reason = fmt.Sprintf("always receives %v", cv)
} else if anyRealUse(par, i) {
c.debug(" skip - used somewhere in the func body\n")
continue
}
issues = append(issues, Issue{
pos: par.Pos(),
msg: fmt.Sprintf("%s %s", par.Name(), reason),
})
}
}
// TODO: replace by sort.Slice once we drop Go 1.7 support
sort.Sort(byNamePos{c.prog.Fset, issues})
return issues, nil
}
type byNamePos struct {
fset *token.FileSet
l []lint.Issue
}
func (p byNamePos) Len() int { return len(p.l) }
func (p byNamePos) Swap(i, j int) { p.l[i], p.l[j] = p.l[j], p.l[i] }
func (p byNamePos) Less(i, j int) bool {
p1 := p.fset.Position(p.l[i].Pos())
p2 := p.fset.Position(p.l[j].Pos())
if p1.Filename == p2.Filename {
return p1.Offset < p2.Offset
}
return p1.Filename < p2.Filename
}
func receivesSameValue(in []*callgraph.Edge, par *ssa.Parameter, pos int) constant.Value {
if ast.IsExported(par.Parent().Name()) {
// we might not have all call sites for an exported func
return nil
}
var seen constant.Value
for _, edge := range in {
call := edge.Site.Common()
cnst, ok := call.Args[pos].(*ssa.Const)
if !ok {
return nil // not a constant
}
if seen == nil {
seen = cnst.Value // first constant
} else if !constant.Compare(seen, token.EQL, cnst.Value) {
return nil // different constants
}
}
return seen
}
func anyRealUse(par *ssa.Parameter, pos int) bool {
refLoop:
for _, ref := range *par.Referrers() {
switch x := ref.(type) {
case *ssa.Call:
if x.Call.Value != par.Parent() {
return true // not a recursive call
}
for i, arg := range x.Call.Args {
if arg != par {
continue
}
if i == pos {
// reused directly in a recursive call
continue refLoop
}
}
return true
case *ssa.Store:
if insertedStore(x) {
continue // inserted by go/ssa, not from the code
}
return true
default:
return true
}
}
return false
}
func insertedStore(instr ssa.Instruction) bool {
if instr.Pos() != token.NoPos {
return false
}
store, ok := instr.(*ssa.Store)
if !ok {
return false
}
alloc, ok := store.Addr.(*ssa.Alloc)
// we want exactly one use of this alloc value for it to be
// inserted by ssa and dummy - the alloc instruction itself.
return ok && len(*alloc.Referrers()) == 1
}
var rxHarmlessCall = regexp.MustCompile(`(?i)\b(log(ger)?|errors)\b|\bf?print`)
// dummyImpl reports whether a block is a dummy implementation. This is
// true if the block will almost immediately panic, throw or return
// constants only.
func dummyImpl(blk *ssa.BasicBlock) bool {
var ops [8]*ssa.Value
for _, instr := range blk.Instrs {
if insertedStore(instr) {
continue // inserted by go/ssa, not from the code
}
for _, val := range instr.Operands(ops[:0]) {
switch x := (*val).(type) {
case nil, *ssa.Const, *ssa.ChangeType, *ssa.Alloc,
*ssa.MakeInterface, *ssa.Function,
*ssa.Global, *ssa.IndexAddr, *ssa.Slice,
*ssa.UnOp:
case *ssa.Call:
if rxHarmlessCall.MatchString(x.Call.Value.String()) {
continue
}
default:
return false
}
}
switch x := instr.(type) {
case *ssa.Alloc, *ssa.Store, *ssa.UnOp, *ssa.BinOp,
*ssa.MakeInterface, *ssa.MakeMap, *ssa.Extract,
*ssa.IndexAddr, *ssa.FieldAddr, *ssa.Slice,
*ssa.Lookup, *ssa.ChangeType, *ssa.TypeAssert,
*ssa.Convert, *ssa.ChangeInterface:
// non-trivial expressions in panic/log/print
// calls
case *ssa.Return, *ssa.Panic:
return true
case *ssa.Call:
if rxHarmlessCall.MatchString(x.Call.Value.String()) {
continue
}
return x.Call.Value.Name() == "throw" // runtime's panic
default:
return false
}
}
return false
}
func (c *Checker) declCounts(pkgDir string, pkgName string) map[string]int {
if m := c.cachedDeclCounts[pkgDir]; m != nil {
return m
}
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, pkgDir, nil, 0)
if err != nil {
panic(err.Error())
return nil
}
pkg := pkgs[pkgName]
count := make(map[string]int)
for _, file := range pkg.Files {
for _, decl := range file.Decls {
fd, _ := decl.(*ast.FuncDecl)
if fd == nil {
continue
}
name := astPrefix(fd.Recv) + fd.Name.Name
count[name]++
}
}
c.cachedDeclCounts[pkgDir] = count
return count
}
func astPrefix(recv *ast.FieldList) string {
if recv == nil {
return ""
}
expr := recv.List[0].Type
for {
star, _ := expr.(*ast.StarExpr)
if star == nil {
break
}
expr = star.X
}
id := expr.(*ast.Ident)
return id.Name + "."
}
func (c *Checker) multipleImpls(info *loader.PackageInfo, fn *ssa.Function) bool {
if fn.Parent() != nil { // nested func
return false
}
path := c.prog.Fset.Position(fn.Pos()).Filename
if path == "" { // generated func, like init
return false
}
count := c.declCounts(filepath.Dir(path), info.Pkg.Name())
name := fn.Name()
if fn.Signature.Recv() != nil {
tp := fn.Params[0].Type()
for {
point, _ := tp.(*types.Pointer)
if point == nil {
break
}
tp = point.Elem()
}
named := tp.(*types.Named)
name = named.Obj().Name() + "." + name
}
return count[name] > 1
}
func paramDesc(i int, v *types.Var) string {
name := v.Name()
if name != "" {
return name
}
return fmt.Sprintf("%d (%s)", i, v.Type().String())
}