2018-06-08 16:06:29 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
2018-06-24 09:24:50 +02:00
|
|
|
"fmt"
|
2023-05-17 13:51:35 +02:00
|
|
|
"github.com/mgechev/revive/internal/ifelse"
|
2018-06-08 16:06:29 +02:00
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
|
|
|
// SuperfluousElseRule lints given else constructs.
|
|
|
|
type SuperfluousElseRule struct{}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2023-05-23 10:10:09 +02:00
|
|
|
func (e *SuperfluousElseRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure {
|
|
|
|
return ifelse.Apply(e, file.AST, ifelse.TargetElse, args)
|
2018-06-08 16:06:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*SuperfluousElseRule) Name() string {
|
2018-06-08 16:06:29 +02:00
|
|
|
return "superfluous-else"
|
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
// CheckIfElse evaluates the rule against an ifelse.Chain.
|
2023-09-24 08:55:14 +02:00
|
|
|
func (*SuperfluousElseRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) {
|
2023-05-17 13:51:35 +02:00
|
|
|
if !chain.If.Deviates() {
|
|
|
|
// this rule only applies if the if-block deviates control flow
|
|
|
|
return
|
2018-06-08 16:06:29 +02:00
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
if chain.HasPriorNonDeviating {
|
|
|
|
// if we de-indent the "else" block then a previous branch
|
|
|
|
// might flow into it, affecting program behaviour
|
|
|
|
return
|
2018-06-08 16:06:29 +02:00
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
if chain.If.Returns() {
|
|
|
|
// avoid overlapping with indent-error-flow
|
|
|
|
return
|
2018-06-24 09:24:50 +02:00
|
|
|
}
|
2023-05-17 13:51:35 +02:00
|
|
|
|
2023-05-23 10:10:09 +02:00
|
|
|
if args.PreserveScope && !chain.AtBlockEnd && (chain.HasInitializer || chain.Else.HasDecls) {
|
|
|
|
// avoid increasing variable scope
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
return fmt.Sprintf("if block ends with %v, so drop this else and outdent its block", chain.If.LongString())
|
2018-06-24 09:24:50 +02:00
|
|
|
}
|