Skip to content

Commit

Permalink
cue: fix EncodeType doesn't unify embedded Go struct with struct defi…
Browse files Browse the repository at this point in the history
…nition

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]>
  • Loading branch information
Clare Yang (zhanyang) committed Jun 28, 2022
1 parent b30eb99 commit fbf40b8
Show file tree
Hide file tree
Showing 2 changed files with 44 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
31 changes: 30 additions & 1 deletion internal/core/convert/go_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,11 @@ func TestX(t *testing.T) {
t.Error(got)
}

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

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

r := runtime.New()

Expand Down

0 comments on commit fbf40b8

Please sign in to comment.