Skip to content

Commit

Permalink
rule optimize-operands-order: do not consider built-in len as a caller (
Browse files Browse the repository at this point in the history
  • Loading branch information
moukoublen authored Jul 2, 2024
1 parent 0df1bb0 commit 689291f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
13 changes: 11 additions & 2 deletions rule/optimize-operands-order.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,17 @@ func (w lintOptimizeOperandsOrderlExpr) Visit(node ast.Node) ast.Visitor {
}

isCaller := func(n ast.Node) bool {
_, ok := n.(*ast.CallExpr)
return ok
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
}

// check if the left sub-expression contains a function call
Expand Down
14 changes: 14 additions & 0 deletions testdata/optimize-operands-order.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ func conditionalExpr(x, y bool) bool {
return caller(x, y) && y // MATCH /for better performance 'caller(x, y) && y' might be rewritten as 'y && caller(x, y)'/
}

func conditionalExprSlice(s []string) bool {
if len(s) > 0 || s[0] == "" { // should not match, not safe
return false
}

f := func() bool {
len(s) > 1
}

if f() || s[0] == "test" { // MATCH /for better performance 'f() || s[0] == "test"' might be rewritten as 's[0] == "test" || f()'/
return true
}
}

func caller(x, y bool) bool {
return true
}

0 comments on commit 689291f

Please sign in to comment.