compiler: allow to declare multiple compound types in a var decl

This commit is contained in:
Evgenii Stratonikov 2020-05-19 16:50:20 +03:00
parent b4bad11699
commit 2cc58c3c9e
2 changed files with 18 additions and 14 deletions

View file

@ -360,27 +360,19 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
} }
c.registerDebugVariable(id.Name, t.Type) c.registerDebugVariable(id.Name, t.Type)
} }
for i := range t.Names {
if len(t.Values) != 0 { if len(t.Values) != 0 {
for i, val := range t.Values { ast.Walk(c, t.Values[i])
ast.Walk(c, val) } else if typ := c.typeOf(t.Type); isCompoundSlice(typ) {
c.emitStoreVar(t.Names[i].Name)
}
} else {
typ := c.typeOf(t.Type)
if isCompoundSlice(typ) {
emit.Opcode(c.prog.BinWriter, opcode.PUSH0) emit.Opcode(c.prog.BinWriter, opcode.PUSH0)
emit.Opcode(c.prog.BinWriter, opcode.NEWARRAY) emit.Opcode(c.prog.BinWriter, opcode.NEWARRAY)
c.emitStoreVar(t.Names[0].Name)
} else if s, ok := typ.Underlying().(*types.Struct); ok { } else if s, ok := typ.Underlying().(*types.Struct); ok {
emit.Int(c.prog.BinWriter, int64(s.NumFields())) emit.Int(c.prog.BinWriter, int64(s.NumFields()))
emit.Opcode(c.prog.BinWriter, opcode.NEWSTRUCT) emit.Opcode(c.prog.BinWriter, opcode.NEWSTRUCT)
c.emitStoreVar(t.Names[0].Name)
} else { } else {
for _, id := range t.Names {
c.emitDefault(t.Type) c.emitDefault(t.Type)
c.emitStoreVar(id.Name)
}
} }
c.emitStoreVar(t.Names[i].Name)
} }
} }
} }

View file

@ -43,3 +43,15 @@ func TestMultiDeclarationLocal(t *testing.T) {
}` }`
eval(t, src, big.NewInt(6)) eval(t, src, big.NewInt(6))
} }
func TestMultiDeclarationLocalCompound(t *testing.T) {
src := `package foo
func Main() int {
var a, b, c []int
a = append(a, 1)
b = append(b, 2)
c = append(c, 3)
return a[0] + b[0] + c[0]
}`
eval(t, src, big.NewInt(6))
}