-
Notifications
You must be signed in to change notification settings - Fork 18k
x/tools/gopls/internal/analysis/modernize: rangeint: transformation unsound when loop variable is defined outside loop #73009
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This looks very similar to the fix in https://go.dev/cl/650815 - I'll see if I can pull that (but the test case that was added implies that incrementing |
FWIW |
Hi @riannucci , the CL650815 you mentioned is that "The range expression x is evaluated before beginning the loop" mentioned in golang spec, so if you change it in the middle, it won't take effects as This issue looks like the assignment to For example, if you use this code, it won't panic. func longestPrefix(k1, k2 string) int {
var i int
for i = range min(len(k1), len(k2)) {
if k1[i] != k2[i] {
break
}
i++
}
return i
} |
That CL includes fixes and tests for two bugs:
The first of these is the same issue you reported here: the final state of variable |
gopls version
go env
What did you do?
Given a main.go:
You can run:
(I encountered this while converting some old Go code - I accepted modernize's suggestion without thinking about it, but eventually traced the failing acceptance tests back to this transformation)
What did you see happen?
Modernize rewrote the loop to use range over int, except that this changes the loop's intended effect on the loop variable. Normally it would have had an additional increment in order to fail the
i < min(len(k1), len(k2))
comparison, but that no longer happens.I saw #72917 but this seemed subtlely different enough (and likely easy to recognize with a local syntax matcher vs looking at the loop body)
What did you expect to see?
Modernize should have left this loop alone (or - range over int should correctly affect the loop variable in this case, but not sure that this is feasible).
Editor and settings
Not applicable
Logs
Not applicable
The text was updated successfully, but these errors were encountered: