interp: fix issue where a var is reused instead of redefined

Avoid a spurious optimisation which forces a variable to be reused instead of redefined for assignment operation. This ensures that a variable defined in a loop is re-allocated, preserving the previous instance when used by a closure for example.

Fix #1594
This commit is contained in:
Marc Vertes
2023-09-21 23:00:06 +02:00
committed by GitHub
parent 8a6061cc86
commit 79b7420ee1
2 changed files with 18 additions and 1 deletions

17
_test/issue-1594.go Normal file
View File

@@ -0,0 +1,17 @@
package main
func main() {
var fns []func()
for _, v := range []int{1, 2, 3} {
x := v*100 + v
fns = append(fns, func() { println(x) })
}
for _, fn := range fns {
fn()
}
}
// Output:
// 101
// 202
// 303

View File

@@ -755,7 +755,7 @@ func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string
n.gen = nop n.gen = nop
src.findex = dest.findex src.findex = dest.findex
src.level = level src.level = level
case len(n.child) < 4 && isArithmeticAction(src) && !isInterface(dest.typ): case len(n.child) < 4 && n.kind != defineStmt && isArithmeticAction(src) && !isInterface(dest.typ):
// Optimize single assignments from some arithmetic operations. // Optimize single assignments from some arithmetic operations.
src.typ = dest.typ src.typ = dest.typ
src.findex = dest.findex src.findex = dest.findex