Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checkers: add new checker stringsCompare #1195

Merged
merged 12 commits into from Feb 5, 2022
21 changes: 21 additions & 0 deletions checkers/rules/rules.go
Expand Up @@ -736,3 +736,24 @@ func dynamicFmtString(m dsl.Matcher) {
Suggest("errors.New($f($*args))").
Report(`use errors.New($f($*args)) or fmt.Errorf("%s", $f($*args)) instead`)
}

//doc:summary Detects strings.Compare usage
//doc:tags style experimental
//doc:before strings.Compare(x, y)
//doc:after x < y
func stringsCompare(m dsl.Matcher) {
m.Match(`strings.Compare($s1, $s2) == 0`, `0 == strings.Compare($s1, $s2)`).
quasilyte marked this conversation as resolved.
Show resolved Hide resolved
Suggest(`$s1 == $s2`)

m.Match(`strings.Compare($s1, $s2) == -1`,
`-1 == strings.Compare($s1, $s2)`,
`strings.Compare($s1, $s2) < 0`,
`0 > strings.Compare($s1, $s2)`).
Suggest(`$s1 < $s2`)

m.Match(`strings.Compare($s1, $s2) == 1`,
`1 == strings.Compare($s1, $s2)`,
`strings.Compare($s1, $s2) > 0`,
`0 < strings.Compare($s1, $s2)`).
Suggest(`$s1 > $s2`)
}
45 changes: 45 additions & 0 deletions checkers/rulesdata/rulesdata.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions checkers/testdata/stringsCompare/negative_tests.go
@@ -0,0 +1,21 @@
package checker_test

import (
"bytes"
)

type s []string

func (s) Compare(x, y string) int {
if x < y {
return 1
}
return 0
}

func negative() {
bytes.Compare([]byte{}, []byte{})

strings := s{}
_ = strings.Compare("1", "3") == 0
}
39 changes: 39 additions & 0 deletions checkers/testdata/stringsCompare/positive_tests.go
@@ -0,0 +1,39 @@
package checker_test

import (
"strings"
)

func warning() {
f, b := "aaa", "bbb"

/*! suggestion: f == b */
if strings.Compare(f, b) == 0 {
}

/*! suggestion: f == b */
if 0 == strings.Compare(f, b) {
}

/*! suggestion: f > b */
switch foo := strings.Compare(f, b) > 0; foo {
case true:
print(0)
case false:
print(1)
}

/*! suggestion: "s" < "ww" */
_ = strings.Compare("s", "ww") < 0
/*! suggestion: "s" == "ww" */
_ = strings.Compare("s", "ww") == 0
/*! suggestion: "s" > "ww" */
_ = strings.Compare("s", "ww") > 0

/*! suggestion: "s" < "ww" */
_ = 0 > strings.Compare("s", "ww")
/*! suggestion: "s" == "ww" */
_ = 0 == strings.Compare("s", "ww")
/*! suggestion: "s" > "ww" */
_ = 0 < strings.Compare("s", "ww")
}