-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblankParam_checker.go
71 lines (60 loc) · 1.67 KB
/
blankParam_checker.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
package checkers
import (
"go/ast"
"github.com/go-lintpack/lintpack"
"github.com/go-lintpack/lintpack/astwalk"
)
func init() {
var info lintpack.CheckerInfo
info.Name = "blankParam"
info.Tags = []string{"style", "opinionated", "experimental"}
info.Summary = "Detects unused params and suggests to name them as `_` (blank)"
info.Before = `func f(a int, b float64) // b isn't used inside function body`
info.After = `func f(a int, _ float64) // everything is cool`
collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker {
return astwalk.WalkerForFuncDecl(&blankParamChecker{ctx: ctx})
})
}
type blankParamChecker struct {
astwalk.WalkHandler
ctx *lintpack.CheckerContext
}
func (c *blankParamChecker) VisitFuncDecl(decl *ast.FuncDecl) {
params := decl.Type.Params
if decl.Body == nil || params == nil || params.NumFields() == 0 {
return
}
// collect all params to map
objToIdent := make(map[*ast.Object]*ast.Ident)
for _, p := range params.List {
if len(p.Names) == 0 {
c.warnUnnamed(p)
return
}
for _, id := range p.Names {
if id.Name != "_" {
objToIdent[id.Obj] = id
}
}
}
// remove used params
// TODO(cristaloleg): we might want to have less iterations here.
for id := range c.ctx.TypesInfo.Uses {
if _, ok := objToIdent[id.Obj]; ok {
delete(objToIdent, id.Obj)
if len(objToIdent) == 0 {
return
}
}
}
// all params that are left are unused
for _, id := range objToIdent {
c.warn(id)
}
}
func (c *blankParamChecker) warn(param *ast.Ident) {
c.ctx.Warn(param, "rename `%s` to `_`", param)
}
func (c *blankParamChecker) warnUnnamed(n ast.Node) {
c.ctx.Warn(n, "consider to name parameters as `_`")
}