Skip to content

Commit

Permalink
checkers: fix equalFold false positive (go-critic#788)
Browse files Browse the repository at this point in the history
The following code makes sense and is correct:

	strings.ToLower(x) == x

Previously, equalFold would trigger on that.
Added a check that upper/lower casing call
operand is not the same as LHS/RHS.

Signed-off-by: Iskander Sharipov <[email protected]>
  • Loading branch information
quasilyte authored Feb 1, 2019
1 parent dfcf754 commit 5dafc45
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
9 changes: 7 additions & 2 deletions checkers/equalFold_checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/go-lintpack/lintpack"
"github.com/go-lintpack/lintpack/astwalk"
"github.com/go-toolsmith/astcast"
"github.com/go-toolsmith/astequal"
)

func init() {
Expand Down Expand Up @@ -57,7 +58,9 @@ func (c *equalFoldChecker) checkBytes(expr *ast.CallExpr) {
if !ok1 && !ok2 {
return
}
c.warnBytes(expr, x, y)
if !astequal.Expr(x, y) {
c.warnBytes(expr, x, y)
}
}

func (c *equalFoldChecker) checkStrings(expr *ast.BinaryExpr) {
Expand All @@ -70,7 +73,9 @@ func (c *equalFoldChecker) checkStrings(expr *ast.BinaryExpr) {
if !ok1 && !ok2 {
return
}
c.warnStrings(expr, x, y)
if !astequal.Expr(x, y) {
c.warnStrings(expr, x, y)
}
}

func (c *equalFoldChecker) warnStrings(cause ast.Node, x, y ast.Expr) {
Expand Down
17 changes: 17 additions & 0 deletions checkers/testdata/equalFold/negative_tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,23 @@ import (
"strings"
)

func changeCaseOfSameExpr(x string, b []byte) {
_ = strings.ToLower(x) == x
_ = x == strings.ToLower(x)
_ = strings.ToLower(x) != x
_ = x != strings.ToLower(x)

_ = strings.ToUpper(x) == x
_ = x == strings.ToUpper(x)
_ = strings.ToUpper(x) != x
_ = x != strings.ToUpper(x)

_ = bytes.Equal(bytes.ToLower(b), b)
_ = bytes.Equal(b, bytes.ToLower(b))
_ = bytes.Equal(bytes.ToUpper(b), b)
_ = bytes.Equal(b, bytes.ToUpper(b))
}

func stringsEqualFold(x, y string) {
_ = strings.EqualFold(x, y)
_ = strings.EqualFold(x, concat(y, "123"))
Expand Down

0 comments on commit 5dafc45

Please sign in to comment.