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

61 lines
1.4 KiB
Go
Raw Normal View History

2017-08-29 19:47:29 +02:00
package defaultrule
2017-08-28 01:57:16 +02:00
import (
"go/ast"
"go/token"
2017-08-28 06:02:59 +02:00
"github.com/mgechev/revive/file"
2017-08-29 19:47:29 +02:00
"github.com/mgechev/revive/rule"
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.
2017-09-02 03:36:47 +02:00
func (r *LintElseRule) Apply(file *file.File, arguments rule.Arguments) []rule.Failure {
2017-11-20 03:58:28 +02:00
var failures []rule.Failure
ast.Walk(lintElse(func(failure rule.Failure) {
failures = append(failures, failure)
}), file.GetAST())
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 03:58:28 +02:00
type lintElse func(rule.Failure)
2017-08-28 01:57:16 +02:00
2017-11-20 03:18:16 +02:00
func (f lintElse) Visit(n ast.Node) ast.Visitor {
node, ok := n.(*ast.IfStmt)
if ok {
if node.Else == nil {
return f
}
if _, ok := node.Else.(*ast.BlockStmt); !ok {
// only care about elses without conditions
return f
}
if len(node.Body.List) == 0 {
return f
}
// shortDecl := false // does the if statement have a ":=" initialization statement?
if node.Init != nil {
if as, ok := node.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE {
// shortDecl = true
}
}
lastStmt := node.Body.List[len(node.Body.List)-1]
if _, ok := lastStmt.(*ast.ReturnStmt); ok {
2017-11-20 03:58:28 +02:00
f(rule.Failure{
2017-11-20 04:23:01 +02:00
Failure: "if block ends with a return statement, so drop this else and outdent its block",
2017-11-20 03:35:56 +02:00
Type: rule.FailureTypeWarning,
2017-11-20 03:58:28 +02:00
Node: node.Else,
})
2017-11-20 03:18:16 +02:00
return f
2017-08-28 01:57:16 +02:00
}
}
2017-11-20 03:18:16 +02:00
return f
2017-08-28 01:57:16 +02:00
}