From 5dafc456d29ae0fd76896993a3cd6ce8b2b86d3c Mon Sep 17 00:00:00 2001 From: "Iskander (Alex) Sharipov" Date: Sat, 2 Feb 2019 00:02:13 +0300 Subject: [PATCH] checkers: fix equalFold false positive (#788) 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 --- checkers/equalFold_checker.go | 9 +++++++-- checkers/testdata/equalFold/negative_tests.go | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/checkers/equalFold_checker.go b/checkers/equalFold_checker.go index 3f4fb914b..265b2f79b 100644 --- a/checkers/equalFold_checker.go +++ b/checkers/equalFold_checker.go @@ -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() { @@ -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) { @@ -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) { diff --git a/checkers/testdata/equalFold/negative_tests.go b/checkers/testdata/equalFold/negative_tests.go index 35d041a50..1f6981b1a 100644 --- a/checkers/testdata/equalFold/negative_tests.go +++ b/checkers/testdata/equalFold/negative_tests.go @@ -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"))