Skip to content

Commit 689291f

Browse files
authored
rule optimize-operands-order: do not consider built-in len as a caller (#1005)
1 parent 0df1bb0 commit 689291f

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

rule/optimize-operands-order.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,17 @@ func (w lintOptimizeOperandsOrderlExpr) Visit(node ast.Node) ast.Visitor {
4949
}
5050

5151
isCaller := func(n ast.Node) bool {
52-
_, ok := n.(*ast.CallExpr)
53-
return ok
52+
ce, ok := n.(*ast.CallExpr)
53+
if !ok {
54+
return false
55+
}
56+
57+
ident, isIdent := ce.Fun.(*ast.Ident)
58+
if !isIdent {
59+
return true
60+
}
61+
62+
return ident.Name != "len" || ident.Obj != nil
5463
}
5564

5665
// check if the left sub-expression contains a function call

testdata/optimize-operands-order.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,20 @@ func conditionalExpr(x, y bool) bool {
2727
return caller(x, y) && y // MATCH /for better performance 'caller(x, y) && y' might be rewritten as 'y && caller(x, y)'/
2828
}
2929

30+
func conditionalExprSlice(s []string) bool {
31+
if len(s) > 0 || s[0] == "" { // should not match, not safe
32+
return false
33+
}
34+
35+
f := func() bool {
36+
len(s) > 1
37+
}
38+
39+
if f() || s[0] == "test" { // MATCH /for better performance 'f() || s[0] == "test"' might be rewritten as 's[0] == "test" || f()'/
40+
return true
41+
}
42+
}
43+
3044
func caller(x, y bool) bool {
3145
return true
3246
}

0 commit comments

Comments
 (0)