2020-04-04 00:59:12 +05:30
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
|
|
|
|
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
|
|
|
// EmptyBlockRule lints given else constructs.
|
|
|
|
type EmptyBlockRule struct{}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
|
|
|
func (r *EmptyBlockRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
|
|
|
var failures []lint.Failure
|
|
|
|
|
|
|
|
onFailure := func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
}
|
|
|
|
|
2020-09-22 22:32:16 +05:30
|
|
|
w := lintEmptyBlock{make(map[*ast.BlockStmt]bool, 0), onFailure}
|
2020-04-04 00:59:12 +05:30
|
|
|
ast.Walk(w, file.AST)
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
|
|
|
func (r *EmptyBlockRule) Name() string {
|
|
|
|
return "empty-block"
|
|
|
|
}
|
|
|
|
|
|
|
|
type lintEmptyBlock struct {
|
2020-09-22 22:32:16 +05:30
|
|
|
ignore map[*ast.BlockStmt]bool
|
2020-04-04 00:59:12 +05:30
|
|
|
onFailure func(lint.Failure)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w lintEmptyBlock) Visit(node ast.Node) ast.Visitor {
|
2020-09-22 22:32:16 +05:30
|
|
|
switch n := node.(type) {
|
|
|
|
case *ast.FuncDecl:
|
|
|
|
w.ignore[n.Body] = true
|
2020-04-04 00:59:12 +05:30
|
|
|
return w
|
2020-09-22 22:32:16 +05:30
|
|
|
case *ast.FuncLit:
|
|
|
|
w.ignore[n.Body] = true
|
2020-04-04 00:59:12 +05:30
|
|
|
return w
|
2020-09-22 22:32:16 +05:30
|
|
|
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",
|
|
|
|
})
|
|
|
|
}
|
2020-04-04 00:59:12 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|