Skip to content

Commit fec8580

Browse files
adonovangopherbot
authored andcommitted
gopls/internal/analysis/modernize: replace loop with slices.Contains
This CL adds a modernizer pass for slices.Contains{,Func}. Example: func assignTrueBreak(slice []int, needle int) { found := false for _, elem := range slice { // want "Loop can be simplified using strings.Contains" if elem == needle { found = true break } } print(found) } => func assignTrueBreak(slice []int, needle int) { found := slices.Contains(slice, needle) print(found) } Updates golang/go#70815 Change-Id: I72ad1c099481b6c9ae6f732e2d81674a98b79a9f Reviewed-on: https://go-review.googlesource.com/c/tools/+/640576 Auto-Submit: Alan Donovan <[email protected]> Reviewed-by: Robert Findley <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Commit-Queue: Alan Donovan <[email protected]>
1 parent ee36e77 commit fec8580

File tree

7 files changed

+591
-2
lines changed

7 files changed

+591
-2
lines changed

gopls/internal/analysis/modernize/modernize.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ func run(pass *analysis.Pass) (any, error) {
4949
}
5050
report := pass.Report
5151
pass.Report = func(diag analysis.Diagnostic) {
52+
if diag.Category == "" {
53+
panic("Diagnostic.Category is unset")
54+
}
5255
if _, ok := generated[pass.Fset.File(diag.Pos)]; ok {
5356
return // skip checking if it's generated code
5457
}
@@ -62,6 +65,7 @@ func run(pass *analysis.Pass) (any, error) {
6265
fmtappendf(pass)
6366
mapsloop(pass)
6467
minmax(pass)
68+
slicescontains(pass)
6569
sortslice(pass)
6670
testingContext(pass)
6771

@@ -120,7 +124,9 @@ var (
120124
builtinAny = types.Universe.Lookup("any")
121125
builtinAppend = types.Universe.Lookup("append")
122126
builtinBool = types.Universe.Lookup("bool")
127+
builtinFalse = types.Universe.Lookup("false")
123128
builtinMake = types.Universe.Lookup("make")
124129
builtinNil = types.Universe.Lookup("nil")
130+
builtinTrue = types.Universe.Lookup("true")
125131
byteSliceType = types.NewSlice(types.Typ[types.Byte])
126132
)

gopls/internal/analysis/modernize/modernize_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ func Test(t *testing.T) {
1919
"fmtappendf",
2020
"mapsloop",
2121
"minmax",
22+
"slicescontains",
2223
"sortslice",
2324
"testingcontext",
2425
)

gopls/internal/analysis/modernize/slices.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package modernize
66

77
// This file defines modernizers that use the "slices" package.
8+
// TODO(adonovan): actually let's split them up and rename this file.
89

910
import (
1011
"fmt"

0 commit comments

Comments
 (0)