Skip to content

Commit 4160e5b

Browse files
author
Clare Yang (zhanyang)
committed
fix #1772: EncodeType doesn't unify embedded Go struct with struct definition
Signed-off-by: Clare Yang (zhanyang) <[email protected]>
1 parent b30eb99 commit 4160e5b

File tree

2 files changed

+41
-10
lines changed

2 files changed

+41
-10
lines changed

internal/core/convert/go.go

+14-9
Original file line numberDiff line numberDiff line change
@@ -685,16 +685,21 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type)
685685
}
686686
elem = ast.NewBinExpr(token.AND, elem, v)
687687
}
688-
// TODO: if an identifier starts with __ (or otherwise is not a
689-
// valid CUE name), make it a string and create a map to a new
690-
// name for references.
691-
692-
// The GO JSON decoder always allows a value to be undefined.
693-
d := &ast.Field{Label: ast.NewIdent(name), Value: elem}
694-
if isOptional(&f) {
695-
d.Optional = token.Blank.Pos()
688+
689+
if name == "" {
690+
obj.Elts = append(obj.Elts, &ast.EmbedDecl{Expr: elem})
691+
} else {
692+
// TODO: if an identifier starts with __ (or otherwise is not a
693+
// valid CUE name), make it a string and create a map to a new
694+
// name for references.
695+
696+
// The GO JSON decoder always allows a value to be undefined.
697+
d := &ast.Field{Label: ast.NewIdent(name), Value: elem}
698+
if isOptional(&f) {
699+
d.Optional = token.Blank.Pos()
700+
}
701+
obj.Elts = append(obj.Elts, d)
696702
}
697-
obj.Elts = append(obj.Elts, d)
698703
}
699704

700705
// TODO: should we validate references here? Can be done using

internal/core/convert/go_test.go

+27-1
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,10 @@ func TestX(t *testing.T) {
263263
t.Error(got)
264264
}
265265

266+
type EmbeddedObj struct {
267+
B int `json:"b"`
268+
}
269+
266270
func TestConvertType(t *testing.T) {
267271
testCases := []struct {
268272
goTyp interface{}
@@ -369,7 +373,29 @@ func TestConvertType(t *testing.T) {
369373
}, {
370374
time.Now, // a function
371375
"_|_(unsupported Go type (func() time.Time))",
372-
}}
376+
},{
377+
struct {
378+
A string `json:"a"`
379+
EmbeddedObj
380+
C string `json:"c,omitempty"`
381+
}{},
382+
`{
383+
a: string
384+
{
385+
b: ((int & >=-9223372036854775808) & <=9223372036854775807)
386+
}
387+
c?: string
388+
}`},{
389+
struct {
390+
A string
391+
*EmbeddedObj
392+
}{},
393+
`{
394+
A: string
395+
(*null|{
396+
b: ((int & >=-9223372036854775808) & <=9223372036854775807)
397+
})
398+
}`}}
373399

374400
r := runtime.New()
375401

0 commit comments

Comments
 (0)