From 9d81815110044686b055db44ab01f0e89eb56914 Mon Sep 17 00:00:00 2001 From: Marc Vertes Date: Thu, 25 Apr 2024 19:32:48 +0200 Subject: [PATCH] fix: don't panic in map range if assigned value is _ Ensure that the code generated for `for s, _ = range ...` is the same as `for s = range ...`. Fixes 1622. --- _test/map31.go | 13 +++++++++++++ interp/cfg.go | 3 +++ interp/run.go | 8 +++----- 3 files changed, 19 insertions(+), 5 deletions(-) create mode 100644 _test/map31.go diff --git a/_test/map31.go b/_test/map31.go new file mode 100644 index 000000000..c649b8c3e --- /dev/null +++ b/_test/map31.go @@ -0,0 +1,13 @@ +package main + +func main() { + myMap := map[string]int{"a":2} + + for s, _ := range myMap { + _ = s + } + println("ok") +} + +// Output: +// ok diff --git a/interp/cfg.go b/interp/cfg.go index 39133a4c8..f177b5fb8 100644 --- a/interp/cfg.go +++ b/interp/cfg.go @@ -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] } diff --git a/interp/run.go b/interp/run.go index 1ec676092..9ff81f952 100644 --- a/interp/run.go +++ b/interp/run.go @@ -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() { @@ -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() {