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:
17
_test/issue-1594.go
Normal file
17
_test/issue-1594.go
Normal 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
|
||||
@@ -755,7 +755,7 @@ func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string
|
||||
n.gen = nop
|
||||
src.findex = dest.findex
|
||||
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.
|
||||
src.typ = dest.typ
|
||||
src.findex = dest.findex
|
||||
|
||||
Reference in New Issue
Block a user