1
0
mirror of https://github.com/mgechev/revive.git synced 2025-07-09 00:45:52 +02:00
Files
revive/rule/indent_error_flow.go

71 lines
1.8 KiB
Go
Raw Permalink Normal View History

2018-01-21 18:04:41 -08:00
package rule
2017-08-27 16:57:16 -07:00
import (
"github.com/mgechev/revive/internal/ifelse"
2018-01-24 15:44:03 -08:00
"github.com/mgechev/revive/lint"
2017-08-27 16:57:16 -07:00
)
2024-12-01 17:44:41 +02:00
// IndentErrorFlowRule prevents redundant else statements.
type IndentErrorFlowRule struct {
// preserveScope prevents suggestions that would enlarge variable scope.
preserveScope bool
}
// Configure validates the rule configuration, and configures the rule accordingly.
//
// Configuration implements the [lint.ConfigurableRule] interface.
func (e *IndentErrorFlowRule) Configure(arguments lint.Arguments) error {
for _, arg := range arguments {
sarg, ok := arg.(string)
if !ok {
continue
}
if isRuleOption(sarg, "preserveScope") {
e.preserveScope = true
}
}
return nil
}
2017-08-27 16:57:16 -07:00
// Apply applies the rule to given file.
func (e *IndentErrorFlowRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
return ifelse.Apply(e.checkIfElse, file.AST, ifelse.TargetElse, ifelse.Args{
PreserveScope: e.preserveScope,
// AllowJump is not used by this rule
})
2017-08-27 16:57:16 -07:00
}
2017-11-19 17:18:16 -08:00
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*IndentErrorFlowRule) Name() string {
2018-05-26 16:14:36 -07:00
return "indent-error-flow"
}
func (e *IndentErrorFlowRule) checkIfElse(chain ifelse.Chain) (string, bool) {
if !chain.HasElse {
return "", false
}
if !chain.If.Deviates() {
// this rule only applies if the if-block deviates control flow
return "", false
2017-11-19 19:38:28 -08:00
}
if chain.HasPriorNonDeviating {
// if we de-indent the "else" block then a previous branch
// might flow into it, affecting program behavior
return "", false
2017-11-19 19:38:28 -08:00
}
if !chain.If.Returns() {
// avoid overlapping with superfluous-else
return "", false
2017-08-27 16:57:16 -07:00
}
if e.preserveScope && !chain.AtBlockEnd && (chain.HasInitializer || chain.Else.HasDecls()) {
// avoid increasing variable scope
return "", false
}
return "if block ends with a return statement, so drop this else and outdent its block", true
2017-08-27 16:57:16 -07:00
}