compiler: support nested struct fielid assignment
This commit is contained in:
parent
1e40f9dac0
commit
051e3608ff
2 changed files with 24 additions and 11 deletions
|
@ -407,20 +407,17 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
|
|||
c.emitStoreVar(t.Name)
|
||||
|
||||
case *ast.SelectorExpr:
|
||||
switch expr := t.X.(type) {
|
||||
case *ast.Ident:
|
||||
if !isAssignOp {
|
||||
ast.Walk(c, n.Rhs[i])
|
||||
}
|
||||
if strct, ok := c.typeOf(expr).Underlying().(*types.Struct); ok {
|
||||
c.emitLoadVar(expr.Name) // load the struct
|
||||
i := indexOfStruct(strct, t.Sel.Name) // get the index of the field
|
||||
c.emitStoreStructField(i) // store the field
|
||||
}
|
||||
default:
|
||||
if !isAssignOp {
|
||||
ast.Walk(c, n.Rhs[i])
|
||||
}
|
||||
strct, ok := c.typeOf(t.X).Underlying().(*types.Struct)
|
||||
if !ok {
|
||||
c.prog.Err = fmt.Errorf("nested selector assigns not supported yet")
|
||||
return nil
|
||||
}
|
||||
ast.Walk(c, t.X) // load the struct
|
||||
i := indexOfStruct(strct, t.Sel.Name) // get the index of the field
|
||||
c.emitStoreStructField(i) // store the field
|
||||
|
||||
// Assignments to index expressions.
|
||||
// slice[0] = 10
|
||||
|
|
|
@ -352,6 +352,22 @@ var structTestCases = []testCase{
|
|||
}`,
|
||||
big.NewInt(3),
|
||||
},
|
||||
{
|
||||
"nested selectors (simple write)",
|
||||
`package foo
|
||||
type S1 struct { x S2 }
|
||||
type S2 struct { a int }
|
||||
func Main() int {
|
||||
s1 := S1{
|
||||
x: S2 {
|
||||
a: 3,
|
||||
},
|
||||
}
|
||||
s1.x.a = 11
|
||||
return s1.x.a
|
||||
}`,
|
||||
big.NewInt(11),
|
||||
},
|
||||
}
|
||||
|
||||
func TestStructs(t *testing.T) {
|
||||
|
|
Loading…
Reference in a new issue