From e21015233be634d6feb1a66df7983913f908a505 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Fri, 8 May 2020 16:10:33 +0300 Subject: [PATCH] compiler: implement shadowing of global variables Before introducing slots it was hard to change global variables preserving changes across multiple function calls. This commit implements such possibility. Closes #638. --- pkg/compiler/codegen.go | 3 +++ pkg/compiler/global_test.go | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 pkg/compiler/global_test.go diff --git a/pkg/compiler/codegen.go b/pkg/compiler/codegen.go index 7d2f6e86e..ca1766d97 100644 --- a/pkg/compiler/codegen.go +++ b/pkg/compiler/codegen.go @@ -410,6 +410,9 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { if !multiRet { c.registerDebugVariable(t.Name, n.Rhs[i]) } + if t.Name != "_" { + c.scope.newLocal(t.Name) + } fallthrough default: if i == 0 || !multiRet { diff --git a/pkg/compiler/global_test.go b/pkg/compiler/global_test.go new file mode 100644 index 000000000..ede29b849 --- /dev/null +++ b/pkg/compiler/global_test.go @@ -0,0 +1,21 @@ +package compiler_test + +import ( + "math/big" + "testing" +) + +func TestChangeGlobal(t *testing.T) { + src := `package foo + var a int + func Main() int { + setLocal() + set42() + setLocal() + return a + } + func set42() { a = 42 } + func setLocal() { a := 10; _ = a }` + + eval(t, src, big.NewInt(42)) +}