-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathargument.go
105 lines (90 loc) · 2.36 KB
/
argument.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
package checks
import (
"go/ast"
"go/token"
"golang.org/x/tools/go/analysis"
config "github.com/tommy-muehle/go-mnd/config"
)
const ArgumentCheck = "argument"
// constantDefinitions is used to save lines (by number) which contain a constant definition.
var constantDefinitions = map[int]bool{}
type ArgumentAnalyzer struct {
config *config.Config
pass *analysis.Pass
}
func NewArgumentAnalyzer(pass *analysis.Pass, config *config.Config) *ArgumentAnalyzer {
return &ArgumentAnalyzer{
pass: pass,
config: config,
}
}
func (a *ArgumentAnalyzer) NodeFilter() []ast.Node {
return []ast.Node{
(*ast.GenDecl)(nil),
(*ast.CallExpr)(nil),
}
}
func (a *ArgumentAnalyzer) Check(n ast.Node) {
switch expr := n.(type) {
case *ast.CallExpr:
a.checkCallExpr(expr)
case *ast.GenDecl:
if expr.Tok.String() == "const" {
constantDefinitions[a.pass.Fset.Position(expr.TokPos).Line] = true
}
}
}
func (a *ArgumentAnalyzer) checkCallExpr(expr *ast.CallExpr) {
if ok := constantDefinitions[a.pass.Fset.Position(expr.Pos()).Line]; ok {
return
}
switch f := expr.Fun.(type) {
case *ast.SelectorExpr:
switch prefix := f.X.(type) {
case *ast.Ident:
if a.config.IsIgnoredFunction(prefix.Name + "." + f.Sel.Name) {
return
}
}
}
for i, arg := range expr.Args {
switch x := arg.(type) {
case *ast.BasicLit:
if !a.isMagicNumber(x) {
continue
}
// If it's a magic number and has no previous element, report it
if i == 0 {
a.pass.Reportf(x.Pos(), reportMsg, x.Value, ArgumentCheck)
} else {
// Otherwise check the previous element type
switch expr.Args[i-1].(type) {
case *ast.ChanType:
// When it's not a simple buffered channel, report it
if a.isMagicNumber(x) {
a.pass.Reportf(x.Pos(), reportMsg, x.Value, ArgumentCheck)
}
}
}
case *ast.BinaryExpr:
a.checkBinaryExpr(x)
}
}
}
func (a *ArgumentAnalyzer) checkBinaryExpr(expr *ast.BinaryExpr) {
switch x := expr.X.(type) {
case *ast.BasicLit:
if a.isMagicNumber(x) {
a.pass.Reportf(x.Pos(), reportMsg, x.Value, ArgumentCheck)
}
}
switch y := expr.Y.(type) {
case *ast.BasicLit:
if a.isMagicNumber(y) {
a.pass.Reportf(y.Pos(), reportMsg, y.Value, ArgumentCheck)
}
}
}
func (a *ArgumentAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
}