2021-10-23 09:29:14 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"go/ast"
|
|
|
|
"go/token"
|
|
|
|
|
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
2024-12-01 17:44:41 +02:00
|
|
|
// OptimizeOperandsOrderRule checks inefficient conditional expressions.
|
2021-10-23 09:29:14 +02:00
|
|
|
type OptimizeOperandsOrderRule struct{}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*OptimizeOperandsOrderRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
2021-10-23 09:29:14 +02:00
|
|
|
var failures []lint.Failure
|
|
|
|
|
|
|
|
onFailure := func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
}
|
|
|
|
w := lintOptimizeOperandsOrderlExpr{
|
|
|
|
onFailure: onFailure,
|
|
|
|
}
|
|
|
|
ast.Walk(w, file.AST)
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*OptimizeOperandsOrderRule) Name() string {
|
2021-10-23 09:29:14 +02:00
|
|
|
return "optimize-operands-order"
|
|
|
|
}
|
|
|
|
|
|
|
|
type lintOptimizeOperandsOrderlExpr struct {
|
|
|
|
onFailure func(failure lint.Failure)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Visit checks boolean AND and OR expressions to determine
|
|
|
|
// if swapping their operands may result in an execution speedup.
|
|
|
|
func (w lintOptimizeOperandsOrderlExpr) Visit(node ast.Node) ast.Visitor {
|
|
|
|
binExpr, ok := node.(*ast.BinaryExpr)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
switch binExpr.Op {
|
|
|
|
case token.LAND, token.LOR:
|
|
|
|
default:
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
isCaller := func(n ast.Node) bool {
|
2024-07-02 08:22:13 +02:00
|
|
|
ce, ok := n.(*ast.CallExpr)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
ident, isIdent := ce.Fun.(*ast.Ident)
|
|
|
|
if !isIdent {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return ident.Name != "len" || ident.Obj != nil
|
2021-10-23 09:29:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// check if the left sub-expression contains a function call
|
2023-11-06 12:01:38 +02:00
|
|
|
nodes := pick(binExpr.X, isCaller)
|
2021-10-23 09:29:14 +02:00
|
|
|
if len(nodes) < 1 {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
// check if the right sub-expression does not contain a function call
|
2023-11-06 12:01:38 +02:00
|
|
|
nodes = pick(binExpr.Y, isCaller)
|
2021-10-23 09:29:14 +02:00
|
|
|
if len(nodes) > 0 {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
newExpr := ast.BinaryExpr{X: binExpr.Y, Y: binExpr.X, Op: binExpr.Op}
|
|
|
|
w.onFailure(lint.Failure{
|
|
|
|
Failure: fmt.Sprintf("for better performance '%v' might be rewritten as '%v'", gofmt(binExpr), gofmt(&newExpr)),
|
|
|
|
Node: node,
|
|
|
|
Category: "optimization",
|
|
|
|
Confidence: 0.3,
|
|
|
|
})
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|