dgryski / semgrep-go

Go rules for semgrep and go-ruleguard
MIT License
457 stars 37 forks source link

Replace sort usage with slices equivalents #63

Open dnwe opened 1 year ago

dnwe commented 1 year ago

As per https://go.dev/blog/go1.21 :

the new slices package (neé golang.org/x/slices) includes sorting functions that are generally faster and more ergonomic than the sort package

Doing this in ruleguard for sort.Strings is quite trivial:

// sort.Strings => slices.Sort
func sortStrings(m dsl.Matcher) {
    m.Match(
        `sort.Strings($s)`,
    ).Where(m["s"].Type.Is("[]string")).
        Report(`As of Go 1.21, slices.Sort is a faster and more ergonomic choice.`).
        Suggest(`slices.Sort($s)`)
}

But sort.Func --> slices.SortFunc is a little trickier as you need the type of the slice to use as the param type in the cmp func e.g.,

-   sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
+   slices.SortFunc(keys, func(a, b int32) int { return int(a - b) })

and I don't think it's possible for ruleguard to infer this?