2020-05-08 22:08:00 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
|
|
|
|
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
|
|
|
// IdenticalBranchesRule warns on constant logical expressions.
|
|
|
|
type IdenticalBranchesRule struct{}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*IdenticalBranchesRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
2020-05-08 22:08:00 +02:00
|
|
|
var failures []lint.Failure
|
|
|
|
|
|
|
|
onFailure := func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
}
|
|
|
|
|
|
|
|
astFile := file.AST
|
|
|
|
w := &lintIdenticalBranches{astFile, onFailure}
|
|
|
|
ast.Walk(w, astFile)
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*IdenticalBranchesRule) Name() string {
|
2020-05-08 22:08:00 +02:00
|
|
|
return "identical-branches"
|
|
|
|
}
|
|
|
|
|
|
|
|
type lintIdenticalBranches struct {
|
|
|
|
file *ast.File
|
|
|
|
onFailure func(lint.Failure)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *lintIdenticalBranches) Visit(node ast.Node) ast.Visitor {
|
|
|
|
n, ok := node.(*ast.IfStmt)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
2024-10-01 12:14:02 +02:00
|
|
|
noElseBranch := n.Else == nil
|
|
|
|
if noElseBranch {
|
2020-05-08 22:08:00 +02:00
|
|
|
return w
|
|
|
|
}
|
2024-10-01 12:14:02 +02:00
|
|
|
|
2020-05-08 22:08:00 +02:00
|
|
|
branches := []*ast.BlockStmt{n.Body}
|
|
|
|
|
|
|
|
elseBranch, ok := n.Else.(*ast.BlockStmt)
|
|
|
|
if !ok { // if-else-if construction
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
branches = append(branches, elseBranch)
|
|
|
|
|
|
|
|
if w.identicalBranches(branches) {
|
|
|
|
w.newFailure(n, "both branches of the if are identical")
|
|
|
|
}
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
2022-04-10 11:55:13 +02:00
|
|
|
func (lintIdenticalBranches) identicalBranches(branches []*ast.BlockStmt) bool {
|
2020-05-08 22:08:00 +02:00
|
|
|
if len(branches) < 2 {
|
2024-10-01 12:14:02 +02:00
|
|
|
return false // only one branch to compare thus we return
|
2020-05-08 22:08:00 +02:00
|
|
|
}
|
|
|
|
|
2024-10-01 12:14:02 +02:00
|
|
|
referenceBranch := gofmt(branches[0])
|
|
|
|
referenceBranchSize := len(branches[0].List)
|
2020-05-08 22:08:00 +02:00
|
|
|
for i := 1; i < len(branches); i++ {
|
2024-10-01 12:14:02 +02:00
|
|
|
currentBranch := branches[i]
|
|
|
|
currentBranchSize := len(currentBranch.List)
|
|
|
|
if currentBranchSize != referenceBranchSize || gofmt(currentBranch) != referenceBranch {
|
2020-05-08 22:08:00 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w lintIdenticalBranches) newFailure(node ast.Node, msg string) {
|
|
|
|
w.onFailure(lint.Failure{
|
|
|
|
Confidence: 1,
|
|
|
|
Node: node,
|
|
|
|
Category: "logic",
|
|
|
|
Failure: msg,
|
|
|
|
})
|
|
|
|
}
|