Skip to content

Commit

Permalink
fix #1772: EncodeType doesn't unify embedded Go struct with struct de…
Browse files Browse the repository at this point in the history
…finition

Signed-off-by: Clare Yang (zhanyang) <zhanyang@cisco.com>
  • Loading branch information
Clare Yang (zhanyang) committed Jun 25, 2022
1 parent b30eb99 commit 4160e5b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 10 deletions.
23 changes: 14 additions & 9 deletions internal/core/convert/go.go
Original file line number Diff line number Diff line change
Expand Up @@ -685,16 +685,21 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type)
}
elem = ast.NewBinExpr(token.AND, elem, v)
}
// TODO: if an identifier starts with __ (or otherwise is not a
// valid CUE name), make it a string and create a map to a new
// name for references.

// The GO JSON decoder always allows a value to be undefined.
d := &ast.Field{Label: ast.NewIdent(name), Value: elem}
if isOptional(&f) {
d.Optional = token.Blank.Pos()

if name == "" {
obj.Elts = append(obj.Elts, &ast.EmbedDecl{Expr: elem})
} else {
// TODO: if an identifier starts with __ (or otherwise is not a
// valid CUE name), make it a string and create a map to a new
// name for references.

// The GO JSON decoder always allows a value to be undefined.
d := &ast.Field{Label: ast.NewIdent(name), Value: elem}
if isOptional(&f) {
d.Optional = token.Blank.Pos()
}
obj.Elts = append(obj.Elts, d)
}
obj.Elts = append(obj.Elts, d)
}

// TODO: should we validate references here? Can be done using
Expand Down
28 changes: 27 additions & 1 deletion internal/core/convert/go_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,10 @@ func TestX(t *testing.T) {
t.Error(got)
}

type EmbeddedObj struct {
B int `json:"b"`
}

func TestConvertType(t *testing.T) {
testCases := []struct {
goTyp interface{}
Expand Down Expand Up @@ -369,7 +373,29 @@ func TestConvertType(t *testing.T) {
}, {
time.Now, // a function
"_|_(unsupported Go type (func() time.Time))",
}}
},{
struct {
A string `json:"a"`
EmbeddedObj
C string `json:"c,omitempty"`
}{},
`{
a: string
{
b: ((int & >=-9223372036854775808) & <=9223372036854775807)
}
c?: string
}`},{
struct {
A string
*EmbeddedObj
}{},
`{
A: string
(*null|{
b: ((int & >=-9223372036854775808) & <=9223372036854775807)
})
}`}}

r := runtime.New()

Expand Down

0 comments on commit 4160e5b

Please sign in to comment.