Skip to content

Commit

Permalink
fix: don't panic in map range if assigned value is _
Browse files Browse the repository at this point in the history
Ensure that the code generated for `for s, _ = range ...`
is the same as `for s = range ...`.

Fixes 1622.
  • Loading branch information
mvertes committed Apr 25, 2024
1 parent 3fbebb3 commit 9d81815
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
13 changes: 13 additions & 0 deletions _test/map31.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package main

func main() {
myMap := map[string]int{"a":2}

for s, _ := range myMap {
_ = s
}
println("ok")
}

// Output:
// ok
3 changes: 3 additions & 0 deletions interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string
var k, v, o *node
if len(n.anc.child) == 4 {
k, v, o = n.anc.child[0], n.anc.child[1], n.anc.child[2]
if v.ident == "_" {
v = nil // Do not assign to _ value.
}
} else {
k, o = n.anc.child[0], n.anc.child[1]
}
Expand Down
8 changes: 3 additions & 5 deletions interp/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -2901,11 +2901,10 @@ func rangeMap(n *node) {
index2 := index0 - 1 // iterator for range, always just behind index0
fnext := getExec(n.fnext)
tnext := getExec(n.tnext)
value := genValue(n.child[len(n.child)-2]) // map value

var value func(*frame) reflect.Value
if len(n.child) == 4 {
index1 := n.child[1].findex // map value location in frame
value = genValue(n.child[2]) // map
if len(n.child) == 4 && n.child[1].ident != "_" {
index1 := n.child[1].findex // map value location in frame
n.exec = func(f *frame) bltn {
iter := f.data[index2].Interface().(*reflect.MapIter)
if !iter.Next() {
Expand All @@ -2916,7 +2915,6 @@ func rangeMap(n *node) {
return tnext
}
} else {
value = genValue(n.child[1]) // map
n.exec = func(f *frame) bltn {
iter := f.data[index2].Interface().(*reflect.MapIter)
if !iter.Next() {
Expand Down

0 comments on commit 9d81815

Please sign in to comment.