dgryski/semgrep-go

Replace sort usage with slices equivalents

dnwe opened this issue · 0 comments

dnwe commented

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?