From 381e045966b079ca0ac364ba111fcb603226a74b Mon Sep 17 00:00:00 2001 From: Larry Clapp Date: Tue, 30 Apr 2024 13:04:04 -0400 Subject: [PATCH] interp: allow assignment to exported variables If you `(*interp.Interpreter).Use` a variable, you should be able to assign to it. Fixes #1623 --- interp/cfg.go | 2 +- interp/interp_eval_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/interp/cfg.go b/interp/cfg.go index f177b5fb8..f557fc556 100644 --- a/interp/cfg.go +++ b/interp/cfg.go @@ -654,7 +654,7 @@ func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string var sym *symbol var level int - if dest.rval.IsValid() && isConstType(dest.typ) { + if dest.rval.IsValid() && !dest.rval.CanSet() && isConstType(dest.typ) { err = n.cfgErrorf("cannot assign to %s (%s constant)", dest.rval, dest.typ.str) break } diff --git a/interp/interp_eval_test.go b/interp/interp_eval_test.go index 87ced850a..63f015538 100644 --- a/interp/interp_eval_test.go +++ b/interp/interp_eval_test.go @@ -1906,3 +1906,27 @@ func TestIssue1383(t *testing.T) { t.Fatal(err) } } + +func TestIssue1623(t *testing.T) { + var f float64 + var j int + var s string = "foo" + + i := interp.New(interp.Options{}) + if err := i.Use(interp.Exports{ + "pkg/pkg": map[string]reflect.Value{ + "F": reflect.ValueOf(&f).Elem(), + "J": reflect.ValueOf(&j).Elem(), + "S": reflect.ValueOf(&s).Elem(), + }, + }); err != nil { + t.Fatal(err) + } + i.ImportUsed() + + runTests(t, i, []testCase{ + {desc: "pkg.F = 2.0", src: "pkg.F = 2.0; pkg.F", res: "2"}, + {desc: "pkg.J = 3", src: "pkg.J = 3; pkg.J", res: "3"}, + {desc: `pkg.S = "bar"`, src: `pkg.S = "bar"; pkg.S`, res: "bar"}, + }) +}