From cf459002f77c84f2986962d7b17d59e4733b37b6 Mon Sep 17 00:00:00 2001 From: Evgeniy Stratonikov Date: Mon, 8 Feb 2021 17:25:42 +0300 Subject: [PATCH] compiler: allow to inline global variables --- pkg/compiler/inline.go | 4 ++++ pkg/compiler/inline_test.go | 28 ++++++++++++++++++++++++++ pkg/compiler/testdata/inline/inline.go | 4 ++++ 3 files changed, 36 insertions(+) diff --git a/pkg/compiler/inline.go b/pkg/compiler/inline.go index 6d2ba8cf1..92d89652b 100644 --- a/pkg/compiler/inline.go +++ b/pkg/compiler/inline.go @@ -53,6 +53,10 @@ func (c *codegen) inlineCall(f *funcScope, n *ast.CallExpr) { c.scope.vars.locals = newScope c.scope.vars.addAlias(name, varLocal, unspecifiedVarIndex, types.TypeAndValue{}) continue + } else if index, ok := c.globals[c.getIdentName("", arg.Name)]; ok { + c.scope.vars.locals = newScope + c.scope.vars.addAlias(name, varGlobal, index, types.TypeAndValue{}) + continue } } ast.Walk(c, n.Args[i]) diff --git a/pkg/compiler/inline_test.go b/pkg/compiler/inline_test.go index ed9c16b3e..9035a8d2a 100644 --- a/pkg/compiler/inline_test.go +++ b/pkg/compiler/inline_test.go @@ -40,6 +40,7 @@ func TestInline(t *testing.T) { func sum(a, b int) int { return 42 } + var Num = 1 func Main() int { %s }` @@ -107,6 +108,11 @@ func TestInline(t *testing.T) { checkCallCount(t, src, 0, 1) eval(t, src, big.NewInt(42)) }) + t.Run("globals", func(t *testing.T) { + src := fmt.Sprintf(srcTmpl, `return inline.Concat(Num)`) + checkCallCount(t, src, 0, 1) + eval(t, src, big.NewInt(221)) + }) } func TestInlineConversion(t *testing.T) { @@ -133,3 +139,25 @@ func TestInlineConversion(t *testing.T) { require.NoError(t, err) require.Equal(t, b2, b1) } + +func TestInlineConversionQualified(t *testing.T) { + src1 := `package foo + import "github.com/nspcc-dev/neo-go/pkg/compiler/testdata/inline" + var A = 1 + func Main() int { + return inline.Concat(A) + }` + b1, err := compiler.Compile("foo.go", strings.NewReader(src1)) + require.NoError(t, err) + + src2 := `package foo + import "github.com/nspcc-dev/neo-go/pkg/compiler/testdata/inline" + import "github.com/nspcc-dev/neo-go/pkg/compiler/testdata/inline/b" + var A = 1 + func Main() int { + return A * 100 + b.A * 10 + inline.A + }` + b2, err := compiler.Compile("foo.go", strings.NewReader(src2)) + require.NoError(t, err) + require.Equal(t, b2, b1) +} diff --git a/pkg/compiler/testdata/inline/inline.go b/pkg/compiler/testdata/inline/inline.go index 13201acaf..c319c6b1d 100644 --- a/pkg/compiler/testdata/inline/inline.go +++ b/pkg/compiler/testdata/inline/inline.go @@ -38,3 +38,7 @@ func VarSum(a int, b ...int) int { } return sum } + +func Concat(n int) int { + return n*100 + b.A*10 + A +}