-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswitchcases.go
76 lines (59 loc) · 1.47 KB
/
switchcases.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
package consistent
import (
"go/ast"
"go/token"
"github.com/go-toolsmith/astcast"
"golang.org/x/tools/go/analysis"
)
const (
switchCasesComma = "comma"
switchCasesOR = "or"
)
var switchCasesFlagAllowedValues = []string{flagIgnore, switchCasesComma, switchCasesOR}
func checkSwitchCases(pass *analysis.Pass, stmt *ast.SwitchStmt, mode string) {
if mode == flagIgnore {
return
}
if stmt.Tag != nil {
return
}
for _, clause := range stmt.Body.List {
checkSwitchCase(pass, astcast.ToCaseClause(clause), mode)
}
}
func checkSwitchCase(pass *analysis.Pass, clause *ast.CaseClause, mode string) {
switch mode {
case switchCasesComma:
for _, expr := range clause.List {
log, ok := toLogical(expr)
if !ok {
continue
}
if !isLogicalORRecursive(log) {
continue
}
reportf(pass, expr.Pos(), "separate cases with comma instead of using logical OR")
}
case switchCasesOR:
if len(clause.List) <= 1 {
return
}
reportf(pass, clause.Pos(), "use logical OR instead of separating cases with comma")
}
}
func toLogical(expr ast.Expr) (*ast.BinaryExpr, bool) {
bin := astcast.ToBinaryExpr(expr)
return bin, bin.Op == token.LAND || bin.Op == token.LOR
}
func isLogicalORRecursive(expr *ast.BinaryExpr) bool {
if expr.Op != token.LOR {
return false
}
if log, ok := toLogical(expr.X); ok && !isLogicalORRecursive(log) {
return false
}
if log, ok := toLogical(expr.Y); ok && !isLogicalORRecursive(log) {
return false
}
return true
}