Skip to content

Commit

Permalink
cue: allow top level JSON marshalers in EncodeType
Browse files Browse the repository at this point in the history
Also add some tests for `EncodeType` as it wasn't called at all in the
entire code base.

I have verified that the test `TestEncodeType/CUEValue#2` fails on
master, but passes with this fix applied.

Signed-off-by: Roger Peppe <[email protected]>
Change-Id: I039a72d59d75b39c2dc1e5a2cad06c111669b6c2
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/547383
Reviewed-by: Daniel Martí <[email protected]>
Unity-Result: CUE porcuepine <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
  • Loading branch information
rogpeppe committed Nov 13, 2023
1 parent b25fc05 commit 8f796bf
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
54 changes: 54 additions & 0 deletions cue/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ import (
"cuelang.org/go/cue"
"cuelang.org/go/cue/build"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/internal/astinternal"
"cuelang.org/go/internal/cuetest"
"cuelang.org/go/internal/cuetxtar"
"cuelang.org/go/internal/tdtest"
"github.com/go-quicktest/qt"
"golang.org/x/tools/txtar"
)
Expand Down Expand Up @@ -138,6 +141,57 @@ bar: [
}
}

func TestEncodeType(t *testing.T) {
type testCase struct {
name string
x interface{}
wantErr string
out string
}
testCases := []testCase{{
name: "Struct",
x: struct {
A int `json:"a"`
B string `json:"b,omitempty"`
C []bool
}{},
out: `{a: int64, b?: string, C?: *null|[...bool]}`,
}, {
name: "CUEValue#1",
x: struct {
A cue.Value `json:"a"`
}{},
out: `{a: _}`,
}, {
name: "CUEValue#2",
x: cue.Value{},
out: `_`,
}, {
// TODO this looks like a shortcoming of EncodeType.
name: "map",
x: map[string]int{},
out: `*null|{}`,
}, {
name: "slice",
x: []int{},
out: `*null|[...int64]`,
}, {
name: "chan",
x: chan int(nil),
wantErr: `unsupported Go type \(chan int\)`,
}}
tdtest.Run(t, testCases, func(t *cuetest.T, tc *testCase) {
v := cuecontext.New().EncodeType(tc.x)
if tc.wantErr != "" {
qt.Assert(t, qt.ErrorMatches(v.Err(), tc.wantErr))
return
}
qt.Assert(t, qt.IsNil(v.Err()))
got := fmt.Sprint(astinternal.DebugStr(v.Eval().Syntax()))
t.Equal(got, tc.out)
})
}

func TestContextCheck(t *testing.T) {
qt.Assert(t, qt.PanicMatches(func() {
var c cue.Context
Expand Down
3 changes: 2 additions & 1 deletion internal/core/convert/go.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,8 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type)
// strict instances and there cannot be any tags that further constrain
// the values.
if t.Implements(jsonMarshaler) || t.Implements(textMarshaler) {
return topSentinel, nil
e = topSentinel
goto store
}

switch k := t.Kind(); k {
Expand Down

0 comments on commit 8f796bf

Please sign in to comment.