Skip to content

Commit fbf40b8

Browse files
author
Clare Yang (zhanyang)
committed
cue: fix EncodeType doesn't unify embedded Go struct with struct definition
This actually fixes a bug in GoTypeToExpr under internal/core/convert, it doesn't unify embedded Go struct with struct definition, and add two test cases to verify this fix working well. Fixes: #1772 Signed-off-by: Clare Yang (zhanyang) <[email protected]>
1 parent b30eb99 commit fbf40b8

File tree

2 files changed

+44
-10
lines changed

2 files changed

+44
-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

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

266+
type EmbeddedObj struct {
267+
B int `json:"b"`
268+
D string
269+
}
270+
266271
func TestConvertType(t *testing.T) {
267272
testCases := []struct {
268273
goTyp interface{}
@@ -369,7 +374,31 @@ func TestConvertType(t *testing.T) {
369374
}, {
370375
time.Now, // a function
371376
"_|_(unsupported Go type (func() time.Time))",
372-
}}
377+
}, {
378+
struct {
379+
A string `json:"a"`
380+
EmbeddedObj `json:",inline"`
381+
C string `json:"c,omitempty"`
382+
}{},
383+
`{
384+
a: string
385+
{
386+
b: ((int & >=-9223372036854775808) & <=9223372036854775807)
387+
D: string
388+
}
389+
c?: string
390+
}`}, {
391+
struct {
392+
A string
393+
*EmbeddedObj
394+
}{},
395+
`{
396+
A: string
397+
(*null|{
398+
b: ((int & >=-9223372036854775808) & <=9223372036854775807)
399+
D: string
400+
})
401+
}`}}
373402

374403
r := runtime.New()
375404

0 commit comments

Comments
 (0)