Skip to content

Commit b31dda4

Browse files
adonovangopherbot
authored andcommitted
gopls/internal/analysis/modernize: fix bug in mapsloop
A loop body of m[k] += v was spuriously matched because I forgot to check the assignment operator. + test Updates golang/go#70815 Change-Id: If74dcbb0ba920ebd475b1d0bd9191c9b44661a1a Reviewed-on: https://go-review.googlesource.com/c/tools/+/642076 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Robert Findley <[email protected]> Auto-Submit: Alan Donovan <[email protected]>
1 parent c1a7fcf commit b31dda4

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

gopls/internal/analysis/modernize/maps.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,11 @@ func mapsloop(pass *analysis.Pass) {
179179

180180
if rng.Tok == token.DEFINE && rng.Key != nil && rng.Value != nil && len(rng.Body.List) == 1 {
181181
// Have: for k, v := range x { S }
182-
if assign, ok := rng.Body.List[0].(*ast.AssignStmt); ok && len(assign.Lhs) == 1 {
182+
if assign, ok := rng.Body.List[0].(*ast.AssignStmt); ok &&
183+
assign.Tok == token.ASSIGN &&
184+
len(assign.Lhs) == 1 {
185+
// Have: for k, v := range x { lhs = rhs }
186+
183187
if index, ok := assign.Lhs[0].(*ast.IndexExpr); ok &&
184188
equalSyntax(rng.Key, index.Index) &&
185189
equalSyntax(rng.Value, assign.Rhs[0]) {

gopls/internal/analysis/modernize/testdata/src/mapsloop/mapsloop.go

+8
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,11 @@ func nopeBodyNotASingleton(src map[int]string) {
138138
println() // nope: other things in the loop body
139139
}
140140
}
141+
142+
// Regression test for https://github.com/golang/go/issues/70815#issuecomment-2581999787.
143+
func nopeAssignmentHasIncrementOperator(src map[int]int) {
144+
dst := make(map[int]int)
145+
for k, v := range src {
146+
dst[k] += v
147+
}
148+
}

gopls/internal/analysis/modernize/testdata/src/mapsloop/mapsloop.go.golden

+8
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,11 @@ func nopeBodyNotASingleton(src map[int]string) {
110110
println() // nope: other things in the loop body
111111
}
112112
}
113+
114+
// Regression test for https://github.com/golang/go/issues/70815#issuecomment-2581999787.
115+
func nopeAssignmentHasIncrementOperator(src map[int]int) {
116+
dst := make(map[int]int)
117+
for k, v := range src {
118+
dst[k] += v
119+
}
120+
}

0 commit comments

Comments
 (0)