Merge pull request #2644 from nspcc-dev/fix-gen-decl

compiler: allow multi-return variables declaration
This commit is contained in:
Roman Khimov 2022-08-18 17:44:50 +03:00 committed by GitHub
commit 06f50630ac
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 2 deletions

View file

@ -582,6 +582,7 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
for _, spec := range n.Specs {
switch t := spec.(type) {
case *ast.ValueSpec:
multiRet := n.Tok == token.VAR && len(t.Values) != 0 && len(t.Names) != len(t.Values)
for _, id := range t.Names {
if id.Name != "_" {
if c.scope == nil {
@ -590,12 +591,16 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
} else {
c.scope.newLocal(id.Name)
}
c.registerDebugVariable(id.Name, t.Type)
if !multiRet {
c.registerDebugVariable(id.Name, t.Type)
}
}
}
for i := range t.Names {
if len(t.Values) != 0 {
ast.Walk(c, t.Values[i])
if i == 0 || !multiRet {
ast.Walk(c, t.Values[i])
}
} else {
c.emitDefault(c.typeOf(t.Type))
}

View file

@ -0,0 +1,31 @@
package compiler_test
import (
"math/big"
"testing"
)
func TestGenDeclWithMultiRet(t *testing.T) {
t.Run("global var decl", func(t *testing.T) {
src := `package foo
func Main() int {
var a, b = f()
return a + b
}
func f() (int, int) {
return 1, 2
}`
eval(t, src, big.NewInt(3))
})
t.Run("local var decl", func(t *testing.T) {
src := `package foo
var a, b = f()
func Main() int {
return a + b
}
func f() (int, int) {
return 1, 2
}`
eval(t, src, big.NewInt(3))
})
}