From 4160e5b7497d2170be00c308dff2b11487b3a71c Mon Sep 17 00:00:00 2001 From: "Clare Yang (zhanyang)" Date: Sat, 25 Jun 2022 16:07:21 +0800 Subject: [PATCH] fix #1772: EncodeType doesn't unify embedded Go struct with struct definition Signed-off-by: Clare Yang (zhanyang) --- internal/core/convert/go.go | 23 ++++++++++++++--------- internal/core/convert/go_test.go | 28 +++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/internal/core/convert/go.go b/internal/core/convert/go.go index b6cc20db25b..af52dc9188e 100644 --- a/internal/core/convert/go.go +++ b/internal/core/convert/go.go @@ -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 diff --git a/internal/core/convert/go_test.go b/internal/core/convert/go_test.go index 0b46873a643..52be82ecdc1 100644 --- a/internal/core/convert/go_test.go +++ b/internal/core/convert/go_test.go @@ -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{} @@ -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()