forked from tommy-muehle/go-mnd
/
condition.go
55 lines (44 loc) · 1.07 KB
/
condition.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
package checks
import (
"go/ast"
"go/token"
"golang.org/x/tools/go/analysis"
config "github.com/invidian/go-mnd/v2/config"
)
const ConditionCheck = "condition"
type ConditionAnalyzer struct {
pass *analysis.Pass
config *config.Config
}
func NewConditionAnalyzer(pass *analysis.Pass, config *config.Config) *ConditionAnalyzer {
return &ConditionAnalyzer{
pass: pass,
config: config,
}
}
func (a *ConditionAnalyzer) NodeFilter() []ast.Node {
return []ast.Node{
(*ast.IfStmt)(nil),
}
}
func (a *ConditionAnalyzer) Check(n ast.Node) {
expr, ok := n.(*ast.IfStmt).Cond.(*ast.BinaryExpr)
if !ok {
return
}
switch x := expr.X.(type) {
case *ast.BasicLit:
if a.isMagicNumber(x) {
a.pass.Reportf(x.Pos(), reportMsg, x.Value, ConditionCheck)
}
}
switch y := expr.Y.(type) {
case *ast.BasicLit:
if a.isMagicNumber(y) {
a.pass.Reportf(y.Pos(), reportMsg, y.Value, ConditionCheck)
}
}
}
func (a *ConditionAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
}