compiler: allow to inline global variables

This commit is contained in:
Evgeniy Stratonikov 2021-02-08 17:25:42 +03:00
parent 6e560c6c9f
commit cf459002f7
3 changed files with 36 additions and 0 deletions

View file

@ -53,6 +53,10 @@ func (c *codegen) inlineCall(f *funcScope, n *ast.CallExpr) {
c.scope.vars.locals = newScope c.scope.vars.locals = newScope
c.scope.vars.addAlias(name, varLocal, unspecifiedVarIndex, types.TypeAndValue{}) c.scope.vars.addAlias(name, varLocal, unspecifiedVarIndex, types.TypeAndValue{})
continue 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]) ast.Walk(c, n.Args[i])

View file

@ -40,6 +40,7 @@ func TestInline(t *testing.T) {
func sum(a, b int) int { func sum(a, b int) int {
return 42 return 42
} }
var Num = 1
func Main() int { func Main() int {
%s %s
}` }`
@ -107,6 +108,11 @@ func TestInline(t *testing.T) {
checkCallCount(t, src, 0, 1) checkCallCount(t, src, 0, 1)
eval(t, src, big.NewInt(42)) 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) { func TestInlineConversion(t *testing.T) {
@ -133,3 +139,25 @@ func TestInlineConversion(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, b2, b1) 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)
}

View file

@ -38,3 +38,7 @@ func VarSum(a int, b ...int) int {
} }
return sum return sum
} }
func Concat(n int) int {
return n*100 + b.A*10 + A
}