2020-05-08 20:14:21 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
2022-11-27 14:23:51 +02:00
|
|
|
"fmt"
|
2020-05-08 20:14:21 +02:00
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
"github.com/mgechev/revive/internal/ifelse"
|
2020-05-08 20:14:21 +02:00
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
2022-11-27 14:23:51 +02:00
|
|
|
// EarlyReturnRule finds opportunities to reduce nesting by inverting
|
|
|
|
// the condition of an "if" block.
|
2020-05-08 20:14:21 +02:00
|
|
|
type EarlyReturnRule struct{}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2023-05-23 10:10:09 +02:00
|
|
|
func (e *EarlyReturnRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure {
|
|
|
|
return ifelse.Apply(e, file.AST, ifelse.TargetIf, args)
|
2020-05-08 20:14:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*EarlyReturnRule) Name() string {
|
2020-05-08 20:14:21 +02:00
|
|
|
return "early-return"
|
|
|
|
}
|
|
|
|
|
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 (*EarlyReturnRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) {
|
2023-05-17 13:51:35 +02:00
|
|
|
if !chain.Else.Deviates() {
|
|
|
|
// this rule only applies if the else-block deviates control flow
|
2022-11-27 14:23:51 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
if chain.HasPriorNonDeviating && !chain.If.IsEmpty() {
|
|
|
|
// if we de-indent this block then a previous branch
|
|
|
|
// might flow into it, affecting program behaviour
|
|
|
|
return
|
2022-11-27 14:23:51 +02:00
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
if chain.If.Deviates() {
|
|
|
|
// avoid overlapping with superfluous-else
|
|
|
|
return
|
2022-11-27 14:23:51 +02:00
|
|
|
}
|
|
|
|
|
2023-05-23 10:10:09 +02:00
|
|
|
if args.PreserveScope && !chain.AtBlockEnd && (chain.HasInitializer || chain.If.HasDecls) {
|
|
|
|
// avoid increasing variable scope
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
if chain.If.IsEmpty() {
|
|
|
|
return fmt.Sprintf("if c { } else { %[1]v } can be simplified to if !c { %[1]v }", chain.Else)
|
2022-11-27 14:23:51 +02:00
|
|
|
}
|
2023-05-17 13:51:35 +02:00
|
|
|
return fmt.Sprintf("if c { ... } else { %[1]v } can be simplified to if !c { %[1]v } ...", chain.Else)
|
2020-05-08 20:14:21 +02:00
|
|
|
}
|