Skip to content

Commit

Permalink
interp: fix issue where a var is reused instead of redefined
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mvertes committed Sep 21, 2023
1 parent 8a6061c commit 79b7420
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
17 changes: 17 additions & 0 deletions _test/issue-1594.go
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 79b7420

Please sign in to comment.