Skip to content

Commit

Permalink
gopls/internal/analysis/modernize: fix rangeint bug
Browse files Browse the repository at this point in the history
info.Defs[v] is nil if the loop variable is not declared
(for i = 0 instead of for i := 0).

+ test

Updates golang/go#71847

Change-Id: I28f82188e813f2d4f1ddc9335f0c13bd90c31ec1
Reviewed-on: https://go-review.googlesource.com/c/tools/+/650815
Auto-Submit: Alan Donovan <adonovan@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Findley <rfindley@google.com>
  • Loading branch information
adonovan authored and gopherbot committed Feb 19, 2025
1 parent 8a39d47 commit 300465c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion gopls/internal/analysis/modernize/rangeint.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func rangeint(pass *analysis.Pass) {
// Have: for i = 0; i < limit; i++ {}

// Find references to i within the loop body.
v := info.Defs[index]
v := info.ObjectOf(index)
used := false
for curId := range curLoop.Child(loop.Body).Preorder((*ast.Ident)(nil)) {
id := curId.Node().(*ast.Ident)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ func _(i int, s struct{ i int }, slice []int) {
for i := 0; i < len(slice); i++ { // want "for loop can be modernized using range over int"
println(slice[i])
}
for i := 0; i < len(""); i++ { // want "for loop can be modernized using range over int"
// NB: not simplified to range ""
}

// nope
for i := 0; i < 10; { // nope: missing increment
Expand All @@ -38,3 +41,13 @@ func _(i int, s struct{ i int }, slice []int) {
}

func f() int { return 0 }

// Repro for part of #71847: ("for range n is invalid if the loop body contains i++"):
func _(s string) {
var i int // (this is necessary)
for i = 0; i < len(s); i++ { // nope: loop body increments i
if true {
i++ // nope
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ func _(i int, s struct{ i int }, slice []int) {
for i := range slice { // want "for loop can be modernized using range over int"
println(slice[i])
}
for range len("") { // want "for loop can be modernized using range over int"
// NB: not simplified to range ""
}

// nope
for i := 0; i < 10; { // nope: missing increment
Expand All @@ -38,3 +41,13 @@ func _(i int, s struct{ i int }, slice []int) {
}

func f() int { return 0 }

// Repro for part of #71847: ("for range n is invalid if the loop body contains i++"):
func _(s string) {
var i int // (this is necessary)
for i = 0; i < len(s); i++ { // nope: loop body increments i
if true {
i++ // nope
}
}
}

0 comments on commit 300465c

Please sign in to comment.