/
sa9003.go
62 lines (57 loc) · 1.49 KB
/
sa9003.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
package sa9003
import (
"go/ast"
"golang.org/x/tools/go/analysis"
"honnef.co/go/tools/analysis/facts/generated"
"honnef.co/go/tools/analysis/lint"
"honnef.co/go/tools/analysis/report"
"honnef.co/go/tools/go/ir/irutil"
"honnef.co/go/tools/internal/passes/buildir"
)
var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
Analyzer: &analysis.Analyzer{
Name: "SA9003",
Run: run,
Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer},
},
Doc: &lint.Documentation{
Title: `Empty body in an if or else branch`,
Since: "2017.1",
NonDefault: true,
Severity: lint.SeverityWarning,
MergeIf: lint.MergeIfAny,
},
})
var Analyzer = SCAnalyzer.Analyzer
func run(pass *analysis.Pass) (interface{}, error) {
for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs {
if fn.Source() == nil {
continue
}
if irutil.IsExample(fn) {
continue
}
cb := func(node ast.Node) bool {
ifstmt, ok := node.(*ast.IfStmt)
if !ok {
return true
}
if ifstmt.Else != nil {
b, ok := ifstmt.Else.(*ast.BlockStmt)
if !ok || len(b.List) != 0 {
return true
}
report.Report(pass, ifstmt.Else, "empty branch", report.FilterGenerated(), report.ShortRange())
}
if len(ifstmt.Body.List) != 0 {
return true
}
report.Report(pass, ifstmt, "empty branch", report.FilterGenerated(), report.ShortRange())
return true
}
if source := fn.Source(); source != nil {
ast.Inspect(source, cb)
}
}
return nil, nil
}