Skip to content

Commit

Permalink
Merge pull request #449 from visualfc/embed
Browse files Browse the repository at this point in the history
CodeBuilder.Member: fix find embed field
  • Loading branch information
xushiwei authored Nov 12, 2024
2 parents 0d78c4d + 6dafe85 commit 4616789
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 10 deletions.
24 changes: 14 additions & 10 deletions codebuild.go
Original file line number Diff line number Diff line change
Expand Up @@ -1474,6 +1474,7 @@ func (p *CodeBuilder) refMember(typ types.Type, name string, argVal ast.Expr, sr
}

func (p *CodeBuilder) fieldRef(x ast.Expr, o *types.Struct, name string, src ast.Node) bool {
var embed []*types.Var
for i, n := 0, o.NumFields(); i < n; i++ {
fld := o.Field(i)
if fld.Name() == name {
Expand All @@ -1486,16 +1487,19 @@ func (p *CodeBuilder) fieldRef(x ast.Expr, o *types.Struct, name string, src ast
})
return true
} else if fld.Embedded() {
fldt := fld.Type()
if o, ok := fldt.(*types.Pointer); ok {
fldt = o.Elem()
}
if t, ok := fldt.(*types.Named); ok {
u := p.getUnderlying(t)
if struc, ok := u.(*types.Struct); ok {
if p.fieldRef(x, struc, name, src) {
return true
}
embed = append(embed, fld)
}
}
for _, fld := range embed {
fldt := fld.Type()
if o, ok := fldt.(*types.Pointer); ok {
fldt = o.Elem()
}
if t, ok := fldt.(*types.Named); ok {
u := p.getUnderlying(t)
if struc, ok := u.(*types.Struct); ok {
if p.fieldRef(x, struc, name, src) {
return true
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions internal/bar/bar.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,8 @@ func Gops_Game_New() *Game {
return nil
}

type Info struct {
id int
}

// -----------------------------------------------------------------------------
26 changes: 26 additions & 0 deletions package_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2896,6 +2896,32 @@ func foo(t *testing.T) {
`)
}

func TestEmbbedField(t *testing.T) {
pkg := newMainPackage()
bar := pkg.Import("github.com/goplus/gogen/internal/bar")
fields := []*types.Var{
types.NewField(token.NoPos, pkg.Types, "", bar.Ref("Info").Type(), true),
types.NewField(token.NoPos, pkg.Types, "id", types.Typ[types.String], false),
}
st := types.NewStruct(fields, nil)
typ := pkg.NewParam(token.NoPos, "t", types.NewPointer(st))
pkg.NewFunc(nil, "foo", types.NewTuple(typ), nil, false).BodyStart(pkg).
Val(ctxRef(pkg, "t")).
MemberRef("id").Val("0").Assign(1).
End()
domTest(t, pkg, `package main
import "github.com/goplus/gogen/internal/bar"
func foo(t *struct {
bar.Info
id string
}) {
t.id = "0"
}
`)
}

func TestMemberAutoProperty(t *testing.T) {
pkg := newMainPackage()
test := pkg.Import("testing")
Expand Down

0 comments on commit 4616789

Please sign in to comment.