Skip to content

Commit

Permalink
encoding/jsonschema: decode contains as list.MatchN
Browse files Browse the repository at this point in the history
The `contains` keyword accepts any valid JSON Schema which is decoded
as a non-concrete constraint. However the `list.Contains` validator
checks for equality and expects its second argument to be concrete.

This change uses `list.MatchN` to support the `contains` keyword.

Fixes #3367

Change-Id: I454a1f6166db3195e4003eb2512e6d550e041cdf
Signed-off-by: haoqixu <[email protected]>
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1199603
Reviewed-by: Roger Peppe <[email protected]>
Unity-Result: CUE porcuepine <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
  • Loading branch information
haoqixu authored and mvdan committed Aug 27, 2024
1 parent 221cfaf commit 3138301
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
11 changes: 6 additions & 5 deletions encoding/jsonschema/constraints_array.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,12 @@ func constraintAdditionalItems(key string, n cue.Value, s *state) {

func constraintContains(key string, n cue.Value, s *state) {
list := s.addImport(n, "list")
// TODO: Passing non-concrete values is not yet supported in CUE.
if x := s.schema(n); !isAny(x) {
x := ast.NewCall(ast.NewSel(list, "Contains"), clearPos(x))
s.add(n, arrayType, x)
}
x := s.schema(n)
x = ast.NewCall(ast.NewSel(list, "MatchN"), &ast.UnaryExpr{
Op: token.GEQ,
X: ast.NewLit(token.INT, "1"),
}, clearPos(x))
s.add(n, arrayType, x)
}

func constraintItems(key string, n cue.Value, s *state) {
Expand Down
13 changes: 13 additions & 0 deletions encoding/jsonschema/testdata/contains.txtar
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- schema.yaml --
type: object
properties:
p1:
type: array
contains: {}

additionalProperties: false

-- out/decode/extract --
import "list"

p1?: list.MatchN(>=1, _)
8 changes: 7 additions & 1 deletion encoding/jsonschema/testdata/list.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ properties:
contains:
const: 3

too:
type: array
contains:
type: string

size:
type: array
minItems: 3
Expand All @@ -40,7 +45,8 @@ import "list"

foo?: [...string]
tuple?: [string, int, 2]
has?: list.Contains(3)
has?: list.MatchN(>=1, 3)
too?: list.MatchN(>=1, string)
size?: list.UniqueItems() & list.MaxItems(9) & [_, _, _, ...]
additional?: [int, int, ...string]
-- out/decode/testerr/err-foo-not-string --
Expand Down

0 comments on commit 3138301

Please sign in to comment.