/
argument.go
107 lines (89 loc) · 2.25 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
106
107
package checks
import (
"go/ast"
"go/token"
"golang.org/x/tools/go/analysis"
config "github.com/tommy-muehle/go-mnd/config"
)
const ArgumentCheck = "argument"
// Known excludes for the argument check.
var argumentExcludes = map[string]string{
// package: function
"time": "Date", // https://golang.org/pkg/time/#Date
}
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.CallExpr)(nil),
}
}
func (a *ArgumentAnalyzer) Check(n ast.Node) {
expr, ok := n.(*ast.CallExpr)
if !ok {
return
}
// Don't check if package and function combination is excluded
if s, ok := expr.Fun.(*ast.SelectorExpr); ok && a.isExcluded(s) {
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 x.Value != "1" {
a.pass.Reportf(x.Pos(), reportMsg, x.Value, ArgumentCheck)
}
}
}
case *ast.BinaryExpr:
a.checkBinaryExpr(x)
}
}
}
func (a *ArgumentAnalyzer) isExcluded(expr *ast.SelectorExpr) bool {
var p string
switch x := expr.X.(type) {
case *ast.Ident:
p = x.Name
}
if v, ok := argumentExcludes[p]; ok && v == expr.Sel.Name {
return true
}
return false
}
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)
}