forked from cue-lang/cue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.go
1305 lines (1153 loc) · 31.5 KB
/
build.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package openapi
import (
"fmt"
"math"
"path"
"regexp"
"sort"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/token"
"cuelang.org/go/internal"
"cuelang.org/go/internal/core/adt"
)
type buildContext struct {
inst cue.Value
instExt cue.Value
refPrefix string
path []cue.Selector
errs errors.Error
expandRefs bool
structural bool
exclusiveBool bool
nameFunc func(inst cue.Value, path cue.Path) string
descFunc func(v cue.Value) string
fieldFilter *regexp.Regexp
schemas *orderedMap
// Track external schemas.
externalRefs map[string]*externalType
// Used for cycle detection in case of using ExpandReferences. At the
// moment, CUE does not detect cycles when a user forcefully steps into a
// pattern constraint.
//
// TODO: consider an option in the CUE API where optional fields are
// recursively evaluated.
cycleNodes []*adt.Vertex
}
type externalType struct {
ref string
inst cue.Value
path cue.Path
value cue.Value
}
type typeFunc func(b *builder, a cue.Value)
func schemas(g *Generator, inst cue.InstanceOrValue) (schemas *ast.StructLit, err error) {
val := inst.Value()
var fieldFilter *regexp.Regexp
if g.FieldFilter != "" {
fieldFilter, err = regexp.Compile(g.FieldFilter)
if err != nil {
return nil, errors.Newf(token.NoPos, "invalid field filter: %v", err)
}
// verify that certain elements are still passed.
for _, f := range strings.Split(
"version,title,allOf,anyOf,not,enum,Schema/properties,Schema/items"+
"nullable,type", ",") {
if fieldFilter.MatchString(f) {
return nil, errors.Newf(token.NoPos, "field filter may not exclude %q", f)
}
}
}
if g.Version == "" {
g.Version = "3.0.0"
}
c := &buildContext{
inst: val,
instExt: val,
refPrefix: "components/schemas",
expandRefs: g.ExpandReferences,
structural: g.ExpandReferences,
nameFunc: g.NameFunc,
descFunc: g.DescriptionFunc,
schemas: &orderedMap{},
externalRefs: map[string]*externalType{},
fieldFilter: fieldFilter,
}
switch g.Version {
case "3.0.0":
c.exclusiveBool = true
case "3.1.0":
default:
return nil, errors.Newf(token.NoPos, "unsupported version %s", g.Version)
}
defer func() {
switch x := recover().(type) {
case nil:
case *openapiError:
err = x
default:
panic(x)
}
}()
// Although paths is empty for now, it makes it valid OpenAPI spec.
i, err := inst.Value().Fields(cue.Definitions(true))
if err != nil {
return nil, err
}
for i.Next() {
sel := i.Selector()
if !sel.IsDefinition() {
continue
}
// message, enum, or constant.
if c.isInternal(sel) {
continue
}
ref := c.makeRef(val, cue.MakePath(sel))
if ref == "" {
continue
}
c.schemas.setExpr(ref, c.build(sel, i.Value()))
}
// keep looping until a fixed point is reached.
for done := 0; len(c.externalRefs) != done; {
done = len(c.externalRefs)
// From now on, all references need to be expanded
external := []string{}
for k := range c.externalRefs {
external = append(external, k)
}
sort.Strings(external)
for _, k := range external {
ext := c.externalRefs[k]
c.instExt = ext.inst
sels := ext.path.Selectors()
last := len(sels) - 1
c.path = sels[:last]
name := sels[last]
c.schemas.setExpr(ext.ref, c.build(name, cue.Dereference(ext.value)))
}
}
a := c.schemas.Elts
sort.Slice(a, func(i, j int) bool {
x, _, _ := ast.LabelName(a[i].(*ast.Field).Label)
y, _, _ := ast.LabelName(a[j].(*ast.Field).Label)
return x < y
})
return (*ast.StructLit)(c.schemas), c.errs
}
func (c *buildContext) build(name cue.Selector, v cue.Value) *ast.StructLit {
return newCoreBuilder(c).schema(nil, name, v)
}
// isInternal reports whether or not to include this type.
func (c *buildContext) isInternal(sel cue.Selector) bool {
// TODO: allow a regexp filter in Config. If we have closed structs and
// definitions, this will likely be unnecessary.
return sel.Type().LabelType() == cue.DefinitionLabel &&
strings.HasSuffix(sel.String(), "_value")
}
func (b *builder) failf(v cue.Value, format string, args ...interface{}) {
panic(&openapiError{
errors.NewMessagef(format, args...),
cue.MakePath(b.ctx.path...),
v.Pos(),
})
}
func (b *builder) unsupported(v cue.Value) {
if b.format == "" {
// Not strictly an error, but consider listing it as a warning
// in strict mode.
}
}
func (b *builder) checkArgs(a []cue.Value, n int) {
if len(a)-1 != n {
b.failf(a[0], "%v must be used with %d arguments", a[0], len(a)-1)
}
}
func (b *builder) schema(core *builder, name cue.Selector, v cue.Value) *ast.StructLit {
oldPath := b.ctx.path
b.ctx.path = append(b.ctx.path, name)
defer func() { b.ctx.path = oldPath }()
var c *builder
if core == nil && b.ctx.structural {
c = newCoreBuilder(b.ctx)
c.buildCore(v) // initialize core structure
c.coreSchema()
} else {
c = newRootBuilder(b.ctx)
c.core = core
}
return c.fillSchema(v)
}
func (b *builder) getDoc(v cue.Value) {
doc := []string{}
if b.ctx.descFunc != nil {
if str := b.ctx.descFunc(v); str != "" {
doc = append(doc, str)
}
} else {
for _, d := range v.Doc() {
doc = append(doc, d.Text())
}
}
if len(doc) > 0 {
str := strings.TrimSpace(strings.Join(doc, "\n\n"))
b.setSingle("description", ast.NewString(str), true)
}
}
func (b *builder) fillSchema(v cue.Value) *ast.StructLit {
if b.filled != nil {
return b.filled
}
b.setValueType(v)
b.format = extractFormat(v)
b.deprecated = getDeprecated(v)
if b.core == nil || len(b.core.values) > 1 {
isRef := b.value(v, nil)
if isRef {
b.typ = ""
}
if !isRef && !b.ctx.structural {
b.getDoc(v)
}
}
schema := b.finish()
s := (*ast.StructLit)(schema)
simplify(b, s)
sortSchema(s)
b.filled = s
return s
}
func label(d ast.Decl) string {
f := d.(*ast.Field)
s, _, _ := ast.LabelName(f.Label)
return s
}
func value(d ast.Decl) ast.Expr {
return d.(*ast.Field).Value
}
func sortSchema(s *ast.StructLit) {
sort.Slice(s.Elts, func(i, j int) bool {
iName := label(s.Elts[i])
jName := label(s.Elts[j])
pi := fieldOrder[iName]
pj := fieldOrder[jName]
if pi != pj {
return pi > pj
}
return iName < jName
})
}
var fieldOrder = map[string]int{
"description": 31,
"type": 30,
"format": 29,
"required": 28,
"properties": 27,
"minProperties": 26,
"maxProperties": 25,
"minimum": 24,
"exclusiveMinimum": 23,
"maximum": 22,
"exclusiveMaximum": 21,
"minItems": 18,
"maxItems": 17,
"minLength": 16,
"maxLength": 15,
"items": 14,
"enum": 13,
"default": 12,
}
func (b *builder) value(v cue.Value, f typeFunc) (isRef bool) {
b.pushNode(v)
defer b.popNode()
count := 0
disallowDefault := false
var values cue.Value
if b.ctx.expandRefs || b.format != "" {
values = cue.Dereference(v)
count = 1
} else {
dedup := map[string]bool{}
hasNoRef := false
accept := v
conjuncts := appendSplit(nil, cue.AndOp, v)
for _, v := range conjuncts {
// This may be a reference to an enum. So we need to check references before
// dissecting them.
switch v1, path := v.ReferencePath(); {
case len(path.Selectors()) > 0:
ref := b.ctx.makeRef(v1, path)
if ref == "" {
v = cue.Dereference(v)
break
}
if dedup[ref] {
continue
}
dedup[ref] = true
b.addRef(v, v1, path)
disallowDefault = true
continue
}
hasNoRef = true
count++
values = values.UnifyAccept(v, accept)
}
isRef = !hasNoRef && len(dedup) == 1
}
if count > 0 { // TODO: implement IsAny.
// TODO: perhaps find optimal representation. For now we assume the
// representation as is already optimized for human consumption.
if values.IncompleteKind()&cue.StructKind != cue.StructKind && !isRef {
values = values.Eval()
}
conjuncts := appendSplit(nil, cue.AndOp, values)
for i, v := range conjuncts {
switch {
case isConcrete(v):
b.dispatch(f, v)
if !b.isNonCore() {
b.set("enum", ast.NewList(b.decode(v)))
}
default:
a := appendSplit(nil, cue.OrOp, v)
for i, v := range a {
if _, r := v.Reference(); len(r) == 0 {
a[i] = v.Eval()
}
}
_ = i
// TODO: it matters here whether a conjunct is obtained
// from embedding or normal unification. Fix this at some
// point.
//
// if len(a) > 1 {
// // Filter disjuncts that cannot unify with other conjuncts,
// // and thus can never be satisfied.
// // TODO: there should be generalized simplification logic
// // in CUE (outside of the usual implicit simplifications).
// k := 0
// outer:
// for _, d := range a {
// for j, w := range conjuncts {
// if i == j {
// continue
// }
// if d.Unify(w).Err() != nil {
// continue outer
// }
// }
// a[k] = d
// k++
// }
// a = a[:k]
// }
switch len(a) {
case 0:
// Conjunct entirely eliminated.
case 1:
v = a[0]
if err := v.Err(); err != nil {
b.failf(v, "openapi: %v", err)
return
}
b.dispatch(f, v)
default:
b.disjunction(a, f)
}
}
}
}
if v, ok := v.Default(); ok && v.IsConcrete() && !disallowDefault {
// TODO: should we show the empty list default? This would be correct
// but perhaps a bit too pedantic and noisy.
switch {
case v.Kind() == cue.ListKind:
iter, _ := v.List()
if !iter.Next() {
// Don't show default for empty list.
break
}
fallthrough
default:
if !b.isNonCore() {
e := v.Syntax(cue.Concrete(true)).(ast.Expr)
b.setFilter("Schema", "default", e)
}
}
}
return isRef
}
func appendSplit(a []cue.Value, splitBy cue.Op, v cue.Value) []cue.Value {
op, args := v.Expr()
// dedup elements.
k := 1
outer:
for i := 1; i < len(args); i++ {
for j := 0; j < k; j++ {
if args[i].Subsume(args[j], cue.Raw()) == nil &&
args[j].Subsume(args[i], cue.Raw()) == nil {
continue outer
}
}
args[k] = args[i]
k++
}
args = args[:k]
if op == cue.NoOp && len(args) == 1 {
// TODO: this is to deal with default value removal. This may change
// when we completely separate default values from values.
a = append(a, args...)
} else if op != splitBy {
a = append(a, v)
} else {
for _, v := range args {
a = appendSplit(a, splitBy, v)
}
}
return a
}
// isConcrete reports whether v is concrete and not a struct (recursively).
// structs are not supported as the result of a struct enum depends on how
// conjunctions and disjunctions are distributed. We could consider still doing
// this if we define a normal form.
func isConcrete(v cue.Value) bool {
if !v.IsConcrete() {
return false
}
if v.Kind() == cue.StructKind || v.Kind() == cue.ListKind {
return false // TODO: handle struct and list kinds
}
return true
}
func (b *builder) disjunction(a []cue.Value, f typeFunc) {
disjuncts := []cue.Value{}
enums := []ast.Expr{} // TODO: unique the enums
nullable := false // Only supported in OpenAPI, not JSON schema
for _, v := range a {
switch {
case v.Null() == nil:
// TODO: for JSON schema, we need to fall through.
nullable = true
case isConcrete(v):
enums = append(enums, b.decode(v))
default:
disjuncts = append(disjuncts, v)
}
}
// Only one conjunct?
if len(disjuncts) == 0 || (len(disjuncts) == 1 && len(enums) == 0) {
if len(disjuncts) == 1 {
b.value(disjuncts[0], f)
}
if len(enums) > 0 && !b.isNonCore() {
b.set("enum", ast.NewList(enums...))
}
if nullable {
b.setSingle("nullable", ast.NewBool(true), true) // allowed in Structural
}
return
}
anyOf := []ast.Expr{}
if len(enums) > 0 {
anyOf = append(anyOf, b.kv("enum", ast.NewList(enums...)))
}
if nullable {
b.setSingle("nullable", ast.NewBool(true), true)
}
schemas := make([]*ast.StructLit, len(disjuncts))
for i, v := range disjuncts {
c := newOASBuilder(b)
c.value(v, f)
t := c.finish()
schemas[i] = (*ast.StructLit)(t)
if len(t.Elts) == 0 {
if c.typ == "" {
return
}
}
}
for i, v := range disjuncts {
// In OpenAPI schema are open by default. To ensure forward compatibility,
// we do not represent closed structs with additionalProperties: false
// (this is discouraged and often disallowed by implementions), but
// rather enforce this by ensuring uniqueness of the disjuncts.
//
// TODO: subsumption may currently give false negatives. We are extra
// conservative in these instances.
subsumed := []ast.Expr{}
for j, w := range disjuncts {
if i == j {
continue
}
err := v.Subsume(w, cue.Schema())
if err == nil || errors.Is(err, internal.ErrInexact) {
subsumed = append(subsumed, schemas[j])
}
}
t := schemas[i]
if len(subsumed) > 0 {
// TODO: elide anyOf if there is only one element. This should be
// rare if originating from oneOf.
exclude := ast.NewStruct("not",
ast.NewStruct("anyOf", ast.NewList(subsumed...)))
if len(t.Elts) == 0 {
t = exclude
} else {
t = ast.NewStruct("allOf", ast.NewList(t, exclude))
}
}
anyOf = append(anyOf, t)
}
b.set("oneOf", ast.NewList(anyOf...))
}
func (b *builder) setValueType(v cue.Value) {
if b.core != nil {
return
}
k := v.IncompleteKind() &^ adt.NullKind
switch k {
case cue.BoolKind:
b.typ = "boolean"
case cue.FloatKind, cue.NumberKind:
b.typ = "number"
case cue.IntKind:
b.typ = "integer"
case cue.BytesKind:
b.typ = "string"
case cue.StringKind:
b.typ = "string"
case cue.StructKind:
b.typ = "object"
case cue.ListKind:
b.typ = "array"
}
}
func (b *builder) dispatch(f typeFunc, v cue.Value) {
if f != nil {
f(b, v)
return
}
switch v.IncompleteKind() {
case cue.NullKind:
// TODO: for JSON schema we would set the type here. For OpenAPI,
// it must be nullable.
b.setSingle("nullable", ast.NewBool(true), true)
case cue.BoolKind:
b.setType("boolean", "")
// No need to call.
case cue.FloatKind, cue.NumberKind:
// TODO:
// Common Name type format Comments
// float number float
// double number double
b.setType("number", "") // may be overridden to integer
b.number(v)
case cue.IntKind:
// integer integer int32 signed 32 bits
// long integer int64 signed 64 bits
b.setType("integer", "") // may be overridden to integer
b.number(v)
// TODO: for JSON schema, consider adding multipleOf: 1.
case cue.BytesKind:
// byte string byte base64 encoded characters
// binary string binary any sequence of octets
b.setType("string", "byte")
b.bytes(v)
case cue.StringKind:
// date string date As defined by full-date - RFC3339
// dateTime string date-time As defined by date-time - RFC3339
// password string password A hint to UIs to obscure input
b.setType("string", "")
b.string(v)
case cue.StructKind:
b.setType("object", "")
b.object(v)
case cue.ListKind:
b.setType("array", "")
b.array(v)
}
}
// object supports the following
// - maxProperties: maximum allowed fields in this struct.
// - minProperties: minimum required fields in this struct.
// - patternProperties: [regexp]: schema
// TODO: we can support this once .kv(key, value) allow
// foo [=~"pattern"]: type
// An instance field must match all schemas for which a regexp matches.
// Even though it is not supported in OpenAPI, we should still accept it
// when receiving from OpenAPI. We could possibly use disjunctions to encode
// this.
// - dependencies: what?
// - propertyNames: schema
// every property name in the enclosed schema matches that of
func (b *builder) object(v cue.Value) {
// TODO: discriminator objects: we could theoretically derive discriminator
// objects automatically: for every object in a oneOf/allOf/anyOf, or any
// object composed of the same type, if a property is required and set to a
// constant value for each type, it is a discriminator.
switch op, a := v.Expr(); op {
case cue.CallOp:
name := fmt.Sprint(a[0])
switch name {
case "struct.MinFields":
b.checkArgs(a, 1)
b.setFilter("Schema", "minProperties", b.int(a[1]))
return
case "struct.MaxFields":
b.checkArgs(a, 1)
b.setFilter("Schema", "maxProperties", b.int(a[1]))
return
default:
b.unsupported(a[0])
return
}
case cue.NoOp:
// TODO: extract format from specific type.
default:
b.failf(v, "unsupported op %v for object type (%v)", op, v)
return
}
required := []ast.Expr{}
for i, _ := v.Fields(); i.Next(); {
required = append(required, ast.NewString(i.Label()))
}
if len(required) > 0 {
b.setFilter("Schema", "required", ast.NewList(required...))
}
var properties *orderedMap
if b.singleFields != nil {
properties = b.singleFields.getMap("properties")
}
hasProps := properties != nil
if !hasProps {
properties = &orderedMap{}
}
for i, _ := v.Fields(cue.Optional(true), cue.Definitions(true)); i.Next(); {
sel := i.Selector()
if b.ctx.isInternal(sel) {
continue
}
label := selectorLabel(sel)
var core *builder
if b.core != nil {
core = b.core.properties[label]
}
schema := b.schema(core, sel, i.Value())
switch {
case sel.IsDefinition():
ref := b.ctx.makeRef(b.ctx.instExt, cue.MakePath(append(b.ctx.path, sel)...))
if ref == "" {
continue
}
b.ctx.schemas.setExpr(ref, schema)
case !b.isNonCore() || len(schema.Elts) > 0:
properties.setExpr(label, schema)
}
}
if !hasProps && properties.len() > 0 {
b.setSingle("properties", (*ast.StructLit)(properties), false)
}
if t, ok := v.Elem(); ok &&
(b.core == nil || b.core.items == nil) && b.checkCycle(t) {
schema := b.schema(nil, cue.AnyString, t)
if len(schema.Elts) > 0 {
b.setSingle("additionalProperties", schema, true) // Not allowed in structural.
}
}
// TODO: maxProperties, minProperties: can be done once we allow cap to
// unify with structs.
}
// List constraints:
//
// Max and min items.
// - maxItems: int (inclusive)
// - minItems: int (inclusive)
// - items (item type)
// schema: applies to all items
// array of schemas:
// schema at pos must match if both value and items are defined.
// - additional items:
// schema: where items must be an array of schemas, intstance elements
// succeed for if they match this value for any value at a position
// greater than that covered by items.
// - uniqueItems: bool
// TODO: support with list.Unique() unique() or comprehensions.
// For the latter, we need equality for all values, which is doable,
// but not done yet.
//
// NOT SUPPORTED IN OpenAPI:
// - contains:
// schema: an array instance is valid if at least one element matches
// this schema.
func (b *builder) array(v cue.Value) {
switch op, a := v.Expr(); op {
case cue.CallOp:
name := fmt.Sprint(a[0])
switch name {
case "list.UniqueItems", "list.UniqueItems()":
b.checkArgs(a, 0)
b.setFilter("Schema", "uniqueItems", ast.NewBool(true))
return
case "list.MinItems":
b.checkArgs(a, 1)
b.setFilter("Schema", "minItems", b.int(a[1]))
return
case "list.MaxItems":
b.checkArgs(a, 1)
b.setFilter("Schema", "maxItems", b.int(a[1]))
return
default:
b.unsupported(a[0])
return
}
case cue.NoOp:
// TODO: extract format from specific type.
default:
b.failf(v, "unsupported op %v for array type", op)
return
}
// Possible conjuncts:
// - one list (CUE guarantees merging all conjuncts)
// - no cap: is unified with list
// - unique items: at most one, but idempotent if multiple.
// There is never a need for allOf or anyOf. Note that a CUE list
// corresponds almost one-to-one to OpenAPI lists.
items := []ast.Expr{}
count := 0
for i, _ := v.List(); i.Next(); count++ {
items = append(items, b.schema(nil, cue.Index(count), i.Value()))
}
if len(items) > 0 {
// TODO: per-item schema are not allowed in OpenAPI, only in JSON Schema.
// Perhaps we should turn this into an OR after first normalizing
// the entries.
b.set("items", ast.NewList(items...))
// panic("per-item types not supported in OpenAPI")
}
// TODO:
// A CUE cap can be a set of discontinuous ranges. If we encounter this,
// we can create an allOf(list type, anyOf(ranges)).
cap := v.Len()
hasMax := false
maxLength := int64(math.MaxInt64)
if n, capErr := cap.Int64(); capErr == nil {
maxLength = n
hasMax = true
} else {
b.value(cap, (*builder).listCap)
}
if !hasMax || int64(len(items)) < maxLength {
if typ, ok := v.Elem(); ok && b.checkCycle(typ) {
var core *builder
if b.core != nil {
core = b.core.items
}
t := b.schema(core, cue.AnyString, typ)
if len(items) > 0 {
b.setFilter("Schema", "additionalItems", t) // Not allowed in structural.
} else if !b.isNonCore() || len(t.Elts) > 0 {
b.setSingle("items", t, true)
}
}
}
}
func (b *builder) listCap(v cue.Value) {
switch op, a := v.Expr(); op {
case cue.LessThanOp:
b.setFilter("Schema", "maxItems", b.inta(a[0], -1))
case cue.LessThanEqualOp:
b.setFilter("Schema", "maxItems", b.inta(a[0], 0))
case cue.GreaterThanOp:
b.setFilter("Schema", "minItems", b.inta(a[0], 1))
case cue.GreaterThanEqualOp:
if b.int64(a[0]) > 0 {
b.setFilter("Schema", "minItems", b.inta(a[0], 0))
}
case cue.NoOp:
// must be type, so okay.
case cue.NotEqualOp:
i := b.int(a[0])
b.setNot("allOff", ast.NewList(
b.kv("minItems", i),
b.kv("maxItems", i),
))
default:
b.failf(v, "unsupported op for list capacity %v", op)
return
}
}
func (b *builder) number(v cue.Value) {
// Multiple conjuncts mostly means just additive constraints.
// Type may be number of float.
switch op, a := v.Expr(); op {
case cue.LessThanOp:
if b.ctx.exclusiveBool {
b.setFilter("Schema", "exclusiveMaximum", ast.NewBool(true))
b.setFilter("Schema", "maximum", b.big(a[0]))
} else {
b.setFilter("Schema", "exclusiveMaximum", b.big(a[0]))
}
case cue.LessThanEqualOp:
b.setFilter("Schema", "maximum", b.big(a[0]))
case cue.GreaterThanOp:
if b.ctx.exclusiveBool {
b.setFilter("Schema", "exclusiveMinimum", ast.NewBool(true))
b.setFilter("Schema", "minimum", b.big(a[0]))
} else {
b.setFilter("Schema", "exclusiveMinimum", b.big(a[0]))
}
case cue.GreaterThanEqualOp:
b.setFilter("Schema", "minimum", b.big(a[0]))
case cue.NotEqualOp:
i := b.big(a[0])
b.setNot("allOff", ast.NewList(
b.kv("minimum", i),
b.kv("maximum", i),
))
case cue.CallOp:
name := fmt.Sprint(a[0])
switch name {
case "math.MultipleOf":
b.checkArgs(a, 1)
b.setFilter("Schema", "multipleOf", b.int(a[1]))
default:
b.unsupported(a[0])
return
}
case cue.NoOp:
// TODO: extract format from specific type.
default:
b.failf(v, "unsupported op for number %v", op)
}
}
// Multiple Regexp conjuncts are represented as allOf all other
// constraints can be combined unless in the even of discontinuous
// lengths.
// string supports the following options:
//
// - maxLength (Unicode codepoints)
// - minLength (Unicode codepoints)
// - pattern (a regexp)
//
// The regexp pattern is as follows, and is limited to be a strict subset of RE2:
// Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-3.3
//
// JSON schema requires ECMA 262 regular expressions, but
// limited to the following constructs:
// - simple character classes: [abc]
// - range character classes: [a-z]
// - complement character classes: [^abc], [^a-z]
// - simple quantifiers: +, *, ?, and lazy versions +? *? ??
// - range quantifiers: {x}, {x,y}, {x,}, {x}?, {x,y}?, {x,}?
// - begin and end anchors: ^ and $
// - simple grouping: (...)
// - alteration: |
//
// This is a subset of RE2 used by CUE.
//
// Most notably absent:
// - the '.' for any character (not sure if that is a doc bug)
// - character classes \d \D [[::]] \pN \p{Name} \PN \P{Name}
// - word boundaries
// - capturing directives.
// - flag setting
// - comments
//
// The capturing directives and comments can be removed without
// compromising the meaning of the regexp (TODO). Removing
// flag setting will be tricky. Unicode character classes,
// boundaries, etc can be compiled into simple character classes,
// although the resulting regexp will look cumbersome.
func (b *builder) string(v cue.Value) {
switch op, a := v.Expr(); op {
case cue.RegexMatchOp, cue.NotRegexMatchOp:
s, err := a[0].String()
if err != nil {
// TODO: this may be an unresolved interpolation or expression. Consider
// whether it is reasonable to treat unevaluated operands as wholes and
// generate a compound regular expression.
b.failf(v, "regexp value must be a string: %v", err)
return