1
0
mirror of https://github.com/mgechev/revive.git synced 2024-11-24 08:32:22 +02:00
revive/rule/no-else-return-rule.go

75 lines
1.7 KiB
Go
Raw Normal View History

2018-01-22 04:04:41 +02:00
package rule
2017-08-28 01:57:16 +02:00
import (
"go/ast"
"go/token"
2018-01-22 04:04:41 +02:00
"github.com/mgechev/revive/linter"
2017-08-28 01:57:16 +02:00
)
// LintElseRule lints given else constructs.
2017-11-20 03:58:28 +02:00
type LintElseRule struct{}
2017-08-28 01:57:16 +02:00
// Apply applies the rule to given file.
2018-01-22 04:04:41 +02:00
func (r *LintElseRule) Apply(file *linter.File, arguments linter.Arguments) []linter.Failure {
var failures []linter.Failure
2017-11-20 05:38:28 +02:00
2018-01-22 04:04:41 +02:00
onFailure := func(failure linter.Failure) {
2017-11-20 03:58:28 +02:00
failures = append(failures, failure)
2017-11-20 05:38:28 +02:00
}
w := lintElse{make(map[*ast.IfStmt]bool), onFailure}
ast.Walk(w, file.GetAST())
2017-11-20 03:58:28 +02:00
return failures
2017-08-28 01:57:16 +02:00
}
2017-11-20 03:18:16 +02:00
// Name returns the rule name.
func (r *LintElseRule) Name() string {
2017-11-20 04:23:01 +02:00
return "no-else-return"
}
2017-11-20 05:38:28 +02:00
type lintElse struct {
ignore map[*ast.IfStmt]bool
2018-01-22 04:04:41 +02:00
onFailure func(linter.Failure)
2017-11-20 05:38:28 +02:00
}
2017-08-28 01:57:16 +02:00
2017-11-20 05:38:28 +02:00
func (w lintElse) Visit(node ast.Node) ast.Visitor {
ifStmt, ok := node.(*ast.IfStmt)
if !ok || ifStmt.Else == nil {
return w
}
if w.ignore[ifStmt] {
return w
}
if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok {
w.ignore[elseif] = true
return w
}
if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok {
// only care about elses without conditions
return w
}
if len(ifStmt.Body.List) == 0 {
return w
}
shortDecl := false // does the if statement have a ":=" initialization statement?
if ifStmt.Init != nil {
if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE {
shortDecl = true
2017-11-20 03:18:16 +02:00
}
2017-11-20 05:38:28 +02:00
}
lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1]
if _, ok := lastStmt.(*ast.ReturnStmt); ok {
extra := ""
if shortDecl {
extra = " (move short variable declaration to its own line if necessary)"
2017-08-28 01:57:16 +02:00
}
2018-01-22 04:04:41 +02:00
w.onFailure(linter.Failure{
2017-11-20 05:38:28 +02:00
Failure: "if block ends with a return statement, so drop this else and outdent its block" + extra,
2018-01-22 04:04:41 +02:00
Type: linter.FailureTypeWarning,
2017-11-20 05:38:28 +02:00
Node: ifStmt.Else,
})
2017-08-28 01:57:16 +02:00
}
2017-11-20 05:38:28 +02:00
return w
2017-08-28 01:57:16 +02:00
}