forked from mgechev/revive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathempty_block.go
75 lines (65 loc) · 1.64 KB
/
empty_block.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
package rule
import (
"go/ast"
"github.com/mgechev/revive/lint"
)
// EmptyBlockRule warns on empty code blocks.
type EmptyBlockRule struct{}
// Apply applies the rule to given file.
func (*EmptyBlockRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
onFailure := func(failure lint.Failure) {
failures = append(failures, failure)
}
w := lintEmptyBlock{map[*ast.BlockStmt]bool{}, onFailure}
ast.Walk(w, file.AST)
return failures
}
// Name returns the rule name.
func (*EmptyBlockRule) Name() string {
return "empty-block"
}
type lintEmptyBlock struct {
ignore map[*ast.BlockStmt]bool
onFailure func(lint.Failure)
}
func (w lintEmptyBlock) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {
case *ast.FuncDecl:
w.ignore[n.Body] = true
return w
case *ast.FuncLit:
w.ignore[n.Body] = true
return w
case *ast.SelectStmt:
w.ignore[n.Body] = true
return w
case *ast.ForStmt:
if len(n.Body.List) == 0 && n.Init == nil && n.Post == nil && n.Cond != nil {
if _, isCall := n.Cond.(*ast.CallExpr); isCall {
w.ignore[n.Body] = true
return w
}
}
case *ast.RangeStmt:
if len(n.Body.List) == 0 {
w.onFailure(lint.Failure{
Confidence: 0.9,
Node: n,
Category: "logic",
Failure: "this block is empty, you can remove it",
})
return nil // skip visiting the range subtree (it will produce a duplicated failure)
}
case *ast.BlockStmt:
if !w.ignore[n] && len(n.List) == 0 {
w.onFailure(lint.Failure{
Confidence: 1,
Node: n,
Category: "logic",
Failure: "this block is empty, you can remove it",
})
}
}
return w
}