1
0
mirror of https://github.com/mgechev/revive.git synced 2025-10-30 23:37:49 +02:00

fix(1438): enforce-switch-style - false positive with pure return based switch (#1446)

This commit is contained in:
chavacava
2025-07-28 21:30:13 +02:00
committed by GitHub
parent 5a1e5fda4c
commit 6b060cd03a
2 changed files with 43 additions and 6 deletions

View File

@@ -3,6 +3,7 @@ package rule
import (
"fmt"
"go/ast"
"go/token"
"github.com/mgechev/revive/lint"
)
@@ -58,12 +59,14 @@ func (r *EnforceSwitchStyleRule) Apply(file *lint.File, _ lint.Arguments) []lint
if !hasDefault && !r.allowNoDefault {
// switch without default
failures = append(failures, lint.Failure{
Confidence: 1,
Node: switchNode,
Category: lint.FailureCategoryStyle,
Failure: "switch must have a default case clause",
})
if !r.allBranchesEndWithJumpStmt(switchNode) {
failures = append(failures, lint.Failure{
Confidence: 1,
Node: switchNode,
Category: lint.FailureCategoryStyle,
Failure: "switch must have a default case clause",
})
}
return true
}
@@ -100,6 +103,31 @@ func (*EnforceSwitchStyleRule) seekDefaultCase(body *ast.BlockStmt) (defaultClau
return defaultClause, defaultClause == last
}
func (*EnforceSwitchStyleRule) allBranchesEndWithJumpStmt(switchStmt *ast.SwitchStmt) bool {
for _, stmt := range switchStmt.Body.List {
caseClause := stmt.(*ast.CaseClause) // safe to assume stmt is a case clause
caseBody := caseClause.Body
if caseBody == nil {
return false
}
lastStmt := caseBody[len(caseBody)-1]
if _, ok := lastStmt.(*ast.ReturnStmt); ok {
continue
}
if jump, ok := lastStmt.(*ast.BranchStmt); ok && jump.Tok == token.BREAK {
continue
}
return false
}
return true
}
// Name returns the rule name.
func (*EnforceSwitchStyleRule) Name() string {
return "enforce-switch-style"

View File

@@ -15,4 +15,13 @@ func enforceSwitchStyle3() {
switch expression { // MATCH /switch must have a default case clause/
case condition:
}
// Must not fail when all branches jump
switch expression {
case condition:
break
case condition:
print()
return
}
}