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

67 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
)
2017-08-28 06:03:59 +02:00
const (
ruleName = "no-else-return"
failure = "if block ends with a return statement, so drop this else and outdent its block"
)
2017-08-28 01:57:16 +02:00
// LintElseRule lints given else constructs.
type LintElseRule struct {
2017-11-20 03:18:16 +02:00
rule.AbstractRule
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:18:16 +02:00
r.File = file
ast.Walk(lintElse{r}, file.GetAST())
return r.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 {
return ruleName
}
2017-11-20 03:18:16 +02:00
type lintElse struct {
2017-11-20 03:35:56 +02:00
r *LintElseRule
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:35:56 +02:00
f.r.AddFailureAtNode(rule.Failure{
Failure: failure,
Type: rule.FailureTypeWarning,
}, node.Else, f.r.File)
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
}