Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix #1772: EncodeType doesn't unify embedded Go struct with struct definition #1775

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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