This repository was archived by the owner on Dec 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunlambda_checker.go
69 lines (58 loc) · 1.56 KB
/
unlambda_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
package checkers
import (
"go/ast"
"go/types"
"github.com/go-critic/checkers/internal/lintutil"
"github.com/go-lintpack/lintpack"
"github.com/go-lintpack/lintpack/astwalk"
"github.com/go-toolsmith/astequal"
)
func init() {
var info lintpack.CheckerInfo
info.Name = "unlambda"
info.Tags = []string{"style"}
info.Summary = "Detects function literals that can be simplified"
info.Before = `func(x int) int { return fn(x) }`
info.After = `fn`
collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker {
return astwalk.WalkerForExpr(&unlambdaChecker{ctx: ctx})
})
}
type unlambdaChecker struct {
astwalk.WalkHandler
ctx *lintpack.CheckerContext
}
func (c *unlambdaChecker) VisitExpr(x ast.Expr) {
fn, ok := x.(*ast.FuncLit)
if !ok || len(fn.Body.List) != 1 {
return
}
ret, ok := fn.Body.List[0].(*ast.ReturnStmt)
if !ok || len(ret.Results) != 1 {
return
}
result := lintutil.AsCallExpr(ret.Results[0])
callable := qualifiedName(result.Fun)
if callable == "" {
return // Skip tricky cases; only handle simple calls
}
fnType := c.ctx.TypesInfo.TypeOf(fn)
resultType := c.ctx.TypesInfo.TypeOf(result.Fun)
if !types.Identical(fnType, resultType) {
return
}
// Now check that all arguments match the parameters.
n := 0
for _, params := range fn.Type.Params.List {
for _, id := range params.Names {
if !astequal.Expr(id, result.Args[n]) {
return
}
n++
}
}
c.warn(fn, callable)
}
func (c *unlambdaChecker) warn(cause ast.Node, suggestion string) {
c.ctx.Warn(cause, "replace `%s` with `%s`", cause, suggestion)
}