2018-01-22 04:04:41 +02:00
|
|
|
package rule
|
2017-08-28 01:57:16 +02:00
|
|
|
|
|
|
|
import (
|
2023-05-17 13:51:35 +02:00
|
|
|
"github.com/mgechev/revive/internal/ifelse"
|
2018-01-25 01:44:03 +02:00
|
|
|
"github.com/mgechev/revive/lint"
|
2017-08-28 01:57:16 +02:00
|
|
|
)
|
|
|
|
|
2018-05-27 01:14:36 +02:00
|
|
|
// IndentErrorFlowRule lints given else constructs.
|
|
|
|
type IndentErrorFlowRule struct{}
|
2017-08-28 01:57:16 +02:00
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2023-05-23 10:10:09 +02:00
|
|
|
func (e *IndentErrorFlowRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure {
|
|
|
|
return ifelse.Apply(e, file.AST, ifelse.TargetElse, args)
|
2017-08-28 01:57:16 +02:00
|
|
|
}
|
|
|
|
|
2017-11-20 03:18:16 +02:00
|
|
|
// Name returns the rule name.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*IndentErrorFlowRule) Name() string {
|
2018-05-27 01:14:36 +02:00
|
|
|
return "indent-error-flow"
|
2017-09-02 06:03:10 +02:00
|
|
|
}
|
|
|
|
|
2024-11-04 14:18:17 +02:00
|
|
|
// CheckIfElse evaluates the rule against an ifelse.Chain and returns a failure message if applicable.
|
|
|
|
func (*IndentErrorFlowRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) string {
|
2023-05-17 13:51:35 +02:00
|
|
|
if !chain.If.Deviates() {
|
|
|
|
// this rule only applies if the if-block deviates control flow
|
2024-11-04 14:18:17 +02:00
|
|
|
return ""
|
2017-11-20 05:38:28 +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
|
2024-11-04 14:18:17 +02:00
|
|
|
return ""
|
2017-11-20 05:38:28 +02:00
|
|
|
}
|
2023-05-17 13:51:35 +02:00
|
|
|
|
|
|
|
if !chain.If.Returns() {
|
|
|
|
// avoid overlapping with superfluous-else
|
2024-11-04 14:18:17 +02:00
|
|
|
return ""
|
2017-08-28 01:57:16 +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
|
2024-11-04 14:18:17 +02:00
|
|
|
return ""
|
2023-05-23 10:10:09 +02:00
|
|
|
}
|
|
|
|
|
2023-05-17 13:51:35 +02:00
|
|
|
return "if block ends with a return statement, so drop this else and outdent its block"
|
2017-08-28 01:57:16 +02:00
|
|
|
}
|