From bdf9be81c4ee059aba32a5a9e4770ec543d6eac0 Mon Sep 17 00:00:00 2001 From: Roger Peppe Date: Fri, 9 Aug 2024 15:05:31 +0100 Subject: [PATCH] encoding/encoding/jsonschema: allow type number with int enum MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This change adjusts the jsonschema logic to allow a number type to be combined with a numeric enum. Fixes #3173. Signed-off-by: Roger Peppe Change-Id: I4e2c63a51135fa3a59ec92d401b03295dc991306 Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1199214 Unity-Result: CUE porcuepine Reviewed-by: Daniel Martí TryBot-Result: CUEcueckoo --- encoding/jsonschema/decode.go | 13 ++++++++++--- encoding/jsonschema/testdata/numericenum.txtar | 5 ++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/encoding/jsonschema/decode.go b/encoding/jsonschema/decode.go index bf6af2bbe6f..163b438f90a 100644 --- a/encoding/jsonschema/decode.go +++ b/encoding/jsonschema/decode.go @@ -243,7 +243,7 @@ const ( var coreToCUE = []cue.Kind{ nullType: cue.NullKind, boolType: cue.BoolKind, - numType: cue.FloatKind, + numType: cue.NumberKind, // Note: both int and float. stringType: cue.StringKind, arrayType: cue.ListKind, objectType: cue.StructKind, @@ -256,8 +256,12 @@ func kindToAST(k cue.Kind) ast.Expr { return ast.NewNull() case cue.BoolKind: return ast.NewIdent("bool") - case cue.FloatKind: + case cue.NumberKind: return ast.NewIdent("number") + case cue.IntKind: + return ast.NewIdent("int") + case cue.FloatKind: + return ast.NewIdent("float") case cue.StringKind: return ast.NewIdent("string") case cue.ListKind: @@ -265,7 +269,7 @@ func kindToAST(k cue.Kind) ast.Expr { case cue.StructKind: return ast.NewStruct(&ast.Ellipsis{}) } - return nil + panic(fmt.Errorf("unexpected kind %v", k)) } var coreTypeName = []string{ @@ -303,6 +307,9 @@ func (s *state) add(n cue.Value, t coreType, x ast.Expr) { } func (s *state) setTypeUsed(n cue.Value, t coreType) { + if int(t) >= len(s.types) { + panic(fmt.Errorf("type out of range %v/%v", int(t), len(s.types))) + } s.types[t].setTypeUsed(n, t) } diff --git a/encoding/jsonschema/testdata/numericenum.txtar b/encoding/jsonschema/testdata/numericenum.txtar index 043826338eb..9059dfb3fdc 100644 --- a/encoding/jsonschema/testdata/numericenum.txtar +++ b/encoding/jsonschema/testdata/numericenum.txtar @@ -8,6 +8,5 @@ "type": "number", "enum": [ 1, 2, 3] } --- out/decode/err -- -constraint not allowed because type number is excluded: - type.json:2:5 +-- out/decode/cue -- +1 | 2 | 3