Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix for issue #1634 -- for passing a closure to exported Go function #1646

Merged
merged 4 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions interp/interp_issue_1634_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package interp

import (
"bytes"
"io"
"os"
"reflect"
"testing"
)

func TestExportClosureArg(t *testing.T) {
outExp := []byte("0\n1\n2\n")
// catch stdout
backupStdout := os.Stdout
defer func() {
os.Stdout = backupStdout
}()
r, w, _ := os.Pipe()
os.Stdout = w

i := New(Options{})
err := i.Use(Exports{
"tmp/tmp": map[string]reflect.Value{
"Func": reflect.ValueOf(func(s *[]func(), f func()) { *s = append(*s, f) }),
},
})
if err != nil {
t.Error(err)
}
i.ImportUsed()

_, err = i.Eval(`
func main() {
fs := []func(){}

for i := 0; i < 3; i++ {
i := i
tmp.Func(&fs, func() { println(i) })
}
for _, f := range fs {
f()
}
}
`)
if err != nil {
t.Error(err)
}
// read stdout
if err = w.Close(); err != nil {
t.Fatal(err)
}
outInterp, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(outInterp, outExp) {
t.Errorf("\nGot: %q,\n want: %q", string(outInterp), string(outExp))
}
}
13 changes: 13 additions & 0 deletions interp/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -987,7 +987,20 @@ func genFunctionWrapper(n *node) func(*frame) reflect.Value {
}
funcType := n.typ.TypeOf()

value := genValue(n)
isDefer := false
if n.anc != nil && n.anc.anc != nil && n.anc.anc.kind == deferStmt {
isDefer = true
}

return func(f *frame) reflect.Value {
v := value(f)
if !isDefer && v.Kind() == reflect.Func {
// fixes #1634, if v is already a func, then don't re-wrap
// because original wrapping cloned the frame but this doesn't
return v
}

return reflect.MakeFunc(funcType, func(in []reflect.Value) []reflect.Value {
// Allocate and init local frame. All values to be settable and addressable.
fr := newFrame(f, len(def.types), f.runid())
Expand Down
Loading