2018-06-08 21:41:49 +02:00
|
|
|
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.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*EmptyBlockRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
2018-06-08 21:41:49 +02:00
|
|
|
var failures []lint.Failure
|
|
|
|
|
|
|
|
onFailure := func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
}
|
|
|
|
|
2021-09-26 08:28:58 +02:00
|
|
|
w := lintEmptyBlock{make(map[*ast.BlockStmt]bool), onFailure}
|
2018-06-08 21:41:49 +02:00
|
|
|
ast.Walk(w, file.AST)
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*EmptyBlockRule) Name() string {
|
2018-06-08 21:41:49 +02:00
|
|
|
return "empty-block"
|
|
|
|
}
|
|
|
|
|
|
|
|
type lintEmptyBlock struct {
|
2020-05-11 02:43:56 +02:00
|
|
|
ignore map[*ast.BlockStmt]bool
|
2018-06-08 21:41:49 +02:00
|
|
|
onFailure func(lint.Failure)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w lintEmptyBlock) Visit(node ast.Node) ast.Visitor {
|
2020-05-11 02:43:56 +02:00
|
|
|
switch n := node.(type) {
|
|
|
|
case *ast.FuncDecl:
|
|
|
|
w.ignore[n.Body] = true
|
2018-06-11 21:08:59 +02:00
|
|
|
return w
|
2020-05-11 02:43:56 +02:00
|
|
|
case *ast.FuncLit:
|
|
|
|
w.ignore[n.Body] = true
|
2018-06-11 21:08:59 +02:00
|
|
|
return w
|
2023-03-16 22:39:52 +02:00
|
|
|
case *ast.SelectStmt:
|
|
|
|
w.ignore[n.Body] = true
|
|
|
|
return w
|
2023-04-28 15:38:51 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
2020-05-11 02:43:56 +02:00
|
|
|
case *ast.RangeStmt:
|
2020-05-20 19:59:50 +02:00
|
|
|
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)
|
2020-05-11 02:43:56 +02:00
|
|
|
}
|
|
|
|
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",
|
|
|
|
})
|
|
|
|
}
|
2018-06-08 21:41:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|