-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathmerge.rs
More file actions
1868 lines (1706 loc) · 64.6 KB
/
merge.rs
File metadata and controls
1868 lines (1706 loc) · 64.6 KB
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 2024 Oxide Computer Company
use std::{
collections::{BTreeMap, BTreeSet},
iter::repeat,
};
use log::debug;
use schemars::schema::{
ArrayValidation, InstanceType, NumberValidation, ObjectValidation, Schema, SchemaObject,
SingleOrVec, StringValidation, SubschemaValidation,
};
use crate::{util::ref_key, validate::schema_value_validate, RefKey};
/// Merge all schemas in array of schemas. If the result is unsatisfiable, this
/// returns `Schema::Bool(false)`.
pub(crate) fn merge_all(schemas: &[Schema], defs: &BTreeMap<RefKey, Schema>) -> Schema {
try_merge_all(schemas, defs).unwrap_or(Schema::Bool(false))
}
fn try_merge_all(schemas: &[Schema], defs: &BTreeMap<RefKey, Schema>) -> Result<Schema, ()> {
debug!(
"merge all {}",
serde_json::to_string_pretty(schemas).unwrap(),
);
let merged_schema = match schemas {
[] => panic!("we should not be trying to merge an empty array of schemas"),
[only] => only.clone(),
[first, second, rest @ ..] => {
let mut out = try_merge_schema(first, second, defs)?;
for schema in rest {
out = try_merge_schema(&out, schema, defs)?;
}
out
}
};
Ok(merged_schema)
}
/// Given two additionalItems schemas that might be None--which is equivalent
/// to Schema::Bool(true)--this returns the appropriate value. This is only
/// called in a situation where additionalItems are relevant, so we prefer
/// `true` to the (equivalent) absence of the schema. In other words, this will
/// never return None.
fn merge_additional_items(
a: Option<&Schema>,
b: Option<&Schema>,
defs: &BTreeMap<RefKey, Schema>,
) -> Option<Schema> {
match (a, b) {
(None, None) => Some(Schema::Bool(true)),
_ => merge_additional_properties(a, b, defs),
}
}
/// Given two additionalProperties schemas that might be None--which is
/// equivalent to Schema::Bool(true)--this returns the appropriate value. We
/// prefer None to `true` for objects since the named properties are th main
/// event.
fn merge_additional_properties(
a: Option<&Schema>,
b: Option<&Schema>,
defs: &BTreeMap<RefKey, Schema>,
) -> Option<Schema> {
match (a, b) {
(None, other) | (other, None) => other.cloned(),
(Some(aa), Some(bb)) => Some(try_merge_schema(aa, bb, defs).unwrap_or(Schema::Bool(false))),
}
}
fn merge_schema(a: &Schema, b: &Schema, defs: &BTreeMap<RefKey, Schema>) -> Schema {
try_merge_schema(a, b, defs).unwrap_or(Schema::Bool(false))
}
/// Merge two schemas returning the resulting schema. If the two schemas are
/// incompatible (i.e. if there is no data that can satisfy them both
/// simultaneously) then this returns Err.
fn try_merge_schema(a: &Schema, b: &Schema, defs: &BTreeMap<RefKey, Schema>) -> Result<Schema, ()> {
match (a, b) {
(Schema::Bool(false), _) | (_, Schema::Bool(false)) => Err(()),
(Schema::Bool(true), other) | (other, Schema::Bool(true)) => Ok(other.clone()),
// If we have two references to the same schema, that's easy!
(
Schema::Object(SchemaObject {
reference: Some(a_ref_name),
..
}),
Schema::Object(SchemaObject {
reference: Some(b_ref_name),
..
}),
) if a_ref_name == b_ref_name => Ok(Schema::Object(SchemaObject {
reference: Some(a_ref_name.clone()),
..Default::default()
})),
// Resolve references here before we start to merge the objects.
//
// TODO: need to mitigate circular references so we don't go into a
// spin loop. We can do this by wrapping defs in a structure that
// remembers what we've already looked up; if we hit a cycle we can
// consider the proper handling, but it might be to ignore it--a
// circular allOf chain is a bit hard to reason about.
(
ref_schema @ Schema::Object(SchemaObject {
reference: Some(ref_name),
..
}),
other,
)
| (
other,
ref_schema @ Schema::Object(SchemaObject {
reference: Some(ref_name),
..
}),
) => {
let key = ref_key(ref_name);
let resolved = defs
.get(&key)
.unwrap_or_else(|| panic!("unresolved reference: {}", ref_name));
let merged_schema = try_merge_schema(resolved, other, defs)?;
// If we merge a referenced schema with another schema **and**
// the resulting schema is equivalent to the referenced schema
// (i.e. the other schema is identical or less permissive) then we
// just return the reference schema rather than its contents.
if merged_schema.roughly(resolved) {
Ok(ref_schema.clone())
} else {
Ok(merged_schema)
}
}
(Schema::Object(aa), Schema::Object(bb)) => Ok(merge_schema_object(aa, bb, defs)?.into()),
}
}
fn merge_schema_object(
a: &SchemaObject,
b: &SchemaObject,
defs: &BTreeMap<RefKey, Schema>,
) -> Result<SchemaObject, ()> {
debug!(
"merging {}\n{}",
serde_json::to_string_pretty(a).unwrap(),
serde_json::to_string_pretty(b).unwrap(),
);
assert!(a.reference.is_none());
assert!(b.reference.is_none());
let instance_type = merge_so_instance_type(a.instance_type.as_ref(), b.instance_type.as_ref())?;
let format = merge_so_format(a.format.as_ref(), b.format.as_ref())?;
let number = merge_so_number(a.number.as_deref(), b.number.as_deref())?;
let string = merge_so_string(a.string.as_deref(), b.string.as_deref())?;
let array = merge_so_array(a.array.as_deref(), b.array.as_deref(), defs)?;
let object = merge_so_object(a.object.as_deref(), b.object.as_deref(), defs)?;
let enum_values = merge_so_enum_values(
a.enum_values.as_ref(),
a.const_value.as_ref(),
b.enum_values.as_ref(),
b.const_value.as_ref(),
)?;
// We could clean up this schema to eliminate data irrelevant to the
// instance type, but logic in the conversion path should already handle
// that.
let mut merged_schema = SchemaObject {
metadata: None,
instance_type,
format,
enum_values,
const_value: None,
subschemas: None,
number,
string,
array,
object,
reference: None,
extensions: Default::default(),
};
// TODO if the merged schema is Default::default() then we should probably
// take some shortcut here...
// If we have subschemas for either schema then we merge the body of the
// two schemas and then do the appropriate merge with subschemas (i.e.
// potentially twice). This is effectively an `allOf` between the merged
// "body" schema and the component subschemas.
merged_schema = try_merge_with_subschemas(merged_schema, a.subschemas.as_deref(), defs)?;
merged_schema = try_merge_with_subschemas(merged_schema, b.subschemas.as_deref(), defs)?;
assert_ne!(merged_schema, Schema::Bool(false).into_object());
// Now that we've finalized the schemas, we take a pass through the
// enumerated values (if there are any) to weed out any that might be
// invalid.
if let Some(enum_values) = merged_schema.enum_values.take() {
let wrapped_schema = Schema::Object(merged_schema);
let enum_values = Some(
enum_values
.into_iter()
.filter(|value| schema_value_validate(&wrapped_schema, value, defs).is_ok())
.collect(),
);
let Schema::Object(new_merged_schema) = wrapped_schema else {
unreachable!()
};
merged_schema = new_merged_schema;
merged_schema.enum_values = enum_values;
}
debug!(
"merged {}\n{}\n|\nv\n{}",
serde_json::to_string_pretty(a).unwrap(),
serde_json::to_string_pretty(b).unwrap(),
serde_json::to_string_pretty(&merged_schema).unwrap(),
);
Ok(merged_schema)
}
fn merge_so_enum_values(
a_enum: Option<&Vec<serde_json::Value>>,
a_const: Option<&serde_json::Value>,
b_enum: Option<&Vec<serde_json::Value>>,
b_const: Option<&serde_json::Value>,
) -> Result<Option<Vec<serde_json::Value>>, ()> {
let aa = match (a_enum, a_const) {
(None, None) => None,
(Some(enum_values), None) => Some(enum_values.clone()),
(None, Some(value)) => Some(vec![value.clone()]),
(Some(_), Some(_)) => unimplemented!(),
};
let bb = match (b_enum, b_const) {
(None, None) => None,
(Some(enum_values), None) => Some(enum_values.clone()),
(None, Some(value)) => Some(vec![value.clone()]),
(Some(_), Some(_)) => unimplemented!(),
};
match (aa, bb) {
(None, None) => Ok(None),
(None, Some(values)) | (Some(values), None) => Ok(Some(values)),
(Some(aa), Some(bb)) => {
let values = aa
.into_iter()
.filter(|value| bb.contains(value))
.collect::<Vec<_>>();
if values.is_empty() {
Err(())
} else {
Ok(Some(values))
}
}
}
}
/// Merge the schema with a subschema validation object. It's important that
/// the return value reduces the complexity of the problem so avoid infinite
/// recursion.
pub(crate) fn try_merge_with_subschemas(
mut schema_object: SchemaObject,
maybe_subschemas: Option<&SubschemaValidation>,
defs: &BTreeMap<RefKey, Schema>,
) -> Result<SchemaObject, ()> {
let Some(SubschemaValidation {
all_of,
any_of,
one_of,
not,
if_schema,
then_schema,
else_schema,
}) = maybe_subschemas
else {
return Ok(schema_object);
};
if if_schema.is_some() || then_schema.is_some() || else_schema.is_some() {
println!(
"{}",
serde_json::to_string_pretty(&maybe_subschemas).unwrap()
);
unimplemented!("if/then/else schemas are not supported");
}
if let Some(all_of) = all_of {
let merged_schema = all_of
.iter()
.try_fold(schema_object.into(), |schema, other| {
try_merge_schema(&schema, other, defs)
})?;
assert_ne!(merged_schema, Schema::Bool(false));
schema_object = merged_schema.into_object();
}
if let Some(not) = not {
schema_object = try_merge_schema_not(schema_object, not.as_ref(), defs)?;
}
// TODO: we should be able to handle a combined one_of and any_of... but
// I don't want to do that now because that would be a very strange
// construction.
assert!(any_of.is_none() || one_of.is_none());
if let Some(any_of) = any_of {
let merged_subschemas = try_merge_with_each_subschema(&schema_object, any_of, defs);
match merged_subschemas.len() {
0 => return Err(()),
1 => schema_object = merged_subschemas.into_iter().next().unwrap().into_object(),
_ => {
schema_object = SchemaObject {
metadata: schema_object.metadata,
subschemas: Some(Box::new(SubschemaValidation {
any_of: Some(merged_subschemas),
..Default::default()
})),
..Default::default()
}
}
}
}
if let Some(one_of) = one_of {
// Check if the base schema already has a oneOf - if so, we need to
// compute the Cartesian product of the two oneOfs
let base_one_of = schema_object
.subschemas
.as_ref()
.and_then(|ss| ss.one_of.as_ref());
let merged_subschemas = if let Some(base_variants) = base_one_of {
// Cartesian product: for each base variant and each new variant,
// merge them together
try_merge_oneof_cartesian_product(base_variants, one_of, defs)
} else {
try_merge_with_each_subschema(&schema_object, one_of, defs)
};
match merged_subschemas.len() {
0 => return Err(()),
1 => schema_object = merged_subschemas.into_iter().next().unwrap().into_object(),
_ => {
schema_object = SchemaObject {
metadata: schema_object.metadata,
subschemas: Some(Box::new(SubschemaValidation {
one_of: Some(merged_subschemas),
..Default::default()
})),
..Default::default()
}
}
}
}
Ok(schema_object)
}
fn try_merge_with_each_subschema(
schema_object: &SchemaObject,
subschemas: &[Schema],
defs: &BTreeMap<RefKey, Schema>,
) -> Vec<Schema> {
let schema = Schema::Object(schema_object.clone());
// First we do a pairwise merge the schemas; if the result is invalid /
// unresolvable / never / whatever, we exclude it from the list. If it is
// valid, *then* we do the join to preserve information (though we probably
// only need to to *that* if at least one schema contains a ref). This
// could probably be an opportunity for memoization, but this is an
// infrequent construction so... whatever for now.
let joined_schemas = subschemas
.iter()
.enumerate()
.filter_map(|(ii, other)| {
// Skip if the merged schema is unsatisfiable.
let merged_schema = try_merge_schema(&schema, other, defs).ok()?;
// If the merged schema is equivalent to one or other of the
// individual schemas, use that.
// TODO is this right? Should we be "subtracting" out other schemas as below?
if merged_schema.roughly(&schema) {
Some(schema.clone())
} else if merged_schema.roughly(other) {
Some(other.clone())
} else {
let not_others = subschemas
.iter()
.enumerate()
.filter(|(jj, _)| *jj != ii)
.map(|(_, not_schema)| {
Schema::Object(SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
not: Some(Box::new(not_schema.clone())),
..Default::default()
})),
..Default::default()
})
});
let joined_schema = [schema.clone(), other.clone()]
.into_iter()
.chain(not_others)
.collect::<Vec<_>>();
Some(
SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(joined_schema),
..Default::default()
})),
..Default::default()
}
.into(),
)
}
})
.collect::<Vec<_>>();
joined_schemas
}
/// Compute the Cartesian product of two oneOf schemas. For each combination
/// of a variant from the first oneOf and a variant from the second oneOf,
/// merge them together. This is used when we have `allOf: [oneOf[A,B], oneOf[C,D]]`
/// which should produce `oneOf[A∩C, A∩D, B∩C, B∩D]`.
fn try_merge_oneof_cartesian_product(
base_variants: &[Schema],
new_variants: &[Schema],
defs: &BTreeMap<RefKey, Schema>,
) -> Vec<Schema> {
let mut result = Vec::new();
for base_variant in base_variants {
for new_variant in new_variants {
// Try to merge each pair of variants
if let Ok(merged) = try_merge_schema(base_variant, new_variant, defs) {
// Only include if the merge produced a satisfiable schema
if merged != Schema::Bool(false)
&& !result.iter().any(|existing| existing.roughly(&merged))
{
result.push(merged);
}
}
}
}
result
}
fn merge_schema_not(
schema: &Schema,
not_schema: &Schema,
defs: &BTreeMap<RefKey, Schema>,
) -> Schema {
match (schema, not_schema) {
(_, Schema::Bool(true)) | (Schema::Bool(false), _) => Schema::Bool(false),
(any, Schema::Bool(false)) => any.clone(),
// TODO I don't know how to subtract something from nothing...
(Schema::Bool(true), Schema::Object(_)) => todo!(),
(Schema::Object(schema_object), any_not) => {
match try_merge_schema_not(schema_object.clone(), any_not, defs) {
Ok(schema_obj) => Schema::Object(schema_obj),
Err(_) => Schema::Bool(false),
}
}
}
}
/// "Subtract" the "not" schema from the schema object.
///
/// TODO Exactly where and how we handle not constructions is... tricky! As we
/// find and support more and more useful uses of not we will likely move some
/// of this into the conversion methods.
fn try_merge_schema_not(
schema_object: SchemaObject,
not_schema: &Schema,
defs: &BTreeMap<RefKey, Schema>,
) -> Result<SchemaObject, ()> {
debug!(
"try_merge_schema_not {}\n not:{}",
serde_json::to_string_pretty(&schema_object).unwrap(),
serde_json::to_string_pretty(not_schema).unwrap(),
);
match not_schema {
// Subtracting everything leaves nothing...
Schema::Bool(true) => Err(()),
// ... whereas subtracting nothing leaves everything.
Schema::Bool(false) => Ok(schema_object),
// Do the real work.
Schema::Object(not_object) => try_merge_schema_object_not(schema_object, not_object, defs),
}
}
fn try_merge_with_subschemas_not(
schema_object: SchemaObject,
not_subschemas: &SubschemaValidation,
defs: &BTreeMap<RefKey, Schema>,
) -> Result<SchemaObject, ()> {
debug!("try_merge_with_subschemas_not");
match not_subschemas {
SubschemaValidation {
all_of: None,
any_of: Some(any_of),
one_of: None,
not: None,
if_schema: None,
then_schema: None,
else_schema: None,
} => {
// A not of anyOf is equivalent to an allOf of not... and the
// latter is easier to merge with other schemas by subtraction.
let all_of = any_of
.iter()
.map(|ss| {
Schema::Object(SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
not: Some(Box::new(ss.clone())),
..Default::default()
})),
..Default::default()
})
})
.collect::<Vec<_>>();
let new_other = SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(all_of),
..Default::default()
})),
..Default::default()
};
merge_schema_object(&schema_object, &new_other, defs)
}
SubschemaValidation {
all_of: None,
any_of: None,
one_of: None,
not: Some(not),
if_schema: None,
then_schema: None,
else_schema: None,
} => {
debug!("not not");
Ok(try_merge_schema(&schema_object.into(), not.as_ref(), defs)?.into_object())
}
// TODO this is a kludge
SubschemaValidation {
all_of: None,
any_of: None,
one_of: Some(_),
not: None,
if_schema: None,
then_schema: None,
else_schema: None,
} => Ok(schema_object),
SubschemaValidation {
all_of: None,
any_of: None,
one_of: None,
not: None,
if_schema: None,
then_schema: None,
else_schema: None,
} => Ok(schema_object),
SubschemaValidation {
all_of: Some(all_of),
any_of: None,
one_of: None,
not: None,
if_schema: None,
then_schema: None,
else_schema: None,
} => match try_merge_all(all_of, defs) {
Ok(merged_not_schema) => try_merge_schema_not(schema_object, &merged_not_schema, defs),
Err(_) => Ok(schema_object),
},
_ => todo!(
"{}\nnot: {}",
serde_json::to_string_pretty(&schema_object).unwrap(),
serde_json::to_string_pretty(¬_subschemas).unwrap(),
),
}
}
fn try_merge_schema_object_not(
mut schema_object: SchemaObject,
not_object: &SchemaObject,
defs: &BTreeMap<RefKey, Schema>,
) -> Result<SchemaObject, ()> {
// Examine enum values
match (&mut schema_object.enum_values, ¬_object.enum_values) {
// Nothing to do.
(_, None) => {}
// TODO not sure quite what to do, so we'll ignore for now.
(None, Some(_)) => {}
(Some(values), Some(not_values)) => {
values.retain(|value| !not_values.contains(value));
if values.is_empty() {
return Err(());
}
}
}
match (&mut schema_object.object, ¬_object.object) {
// Nothing to do.
(_, None) => {}
// TODO Not sure how to enforce the inverse here...
(None, Some(_)) => {}
// In the interesting case, we need to "subtract" object attributes.
(Some(obj), Some(not_obj)) => {
for (prop_name, prop_schema) in &mut obj.properties {
if let Some(not_prop_schema) = not_obj.properties.get(prop_name) {
// For properties in both, we merge those schemas. Note
// that if such a merging is unsatisfiable *and* the
// property is required, we'll take the appropriate action
// later.
*prop_schema = merge_schema_not(prop_schema, not_prop_schema, defs);
}
}
for prop_name in not_obj.properties.keys() {
if !obj.properties.contains_key(prop_name) {
// There's a property in the "not" that isn't in the
// object. Most precisely we would say "this property may
// have any value as long as it doesn't match this schema".
// That's a little tricky right now, so instead we'll say
// "you may not have a property with this name".
let _ = obj
.properties
.insert(prop_name.clone(), Schema::Bool(false));
}
}
for not_required in ¬_obj.required {
if !not_obj.properties.contains_key(not_required) {
// No value is permissible
let _ = obj
.properties
.insert(not_required.clone(), Schema::Bool(false));
}
}
// If any of the previous steps resulted in a required property
// being invalid, we note that here and identify the full schema as
// invalid.
for required in &obj.required {
if let Some(Schema::Bool(false)) = obj.properties.get(required) {
return Err(());
}
}
}
}
if let Some(not_subschemas) = ¬_object.subschemas {
schema_object = try_merge_with_subschemas_not(schema_object, not_subschemas, defs)?;
}
Ok(schema_object)
}
/// Merge instance types which could be None (meaning type is valid), a
/// singleton type, or an array of types. An error result indicates that the
/// types were non-overlappin and therefore incompatible.
fn merge_so_instance_type(
a: Option<&SingleOrVec<InstanceType>>,
b: Option<&SingleOrVec<InstanceType>>,
) -> Result<Option<SingleOrVec<InstanceType>>, ()> {
match (a, b) {
(None, None) => Ok(None),
(None, other @ Some(_)) | (other @ Some(_), None) => Ok(other.cloned()),
// If each has a single type, it must match.
(Some(SingleOrVec::Single(aa)), Some(SingleOrVec::Single(bb))) => {
if aa == bb {
Ok(Some(SingleOrVec::Single(aa.clone())))
} else {
Err(())
}
}
// If one has a single type and the other is an array, the type must
// appear in the array (and that's the resulting type).
(Some(SingleOrVec::Vec(types)), Some(SingleOrVec::Single(it)))
| (Some(SingleOrVec::Single(it)), Some(SingleOrVec::Vec(types))) => {
if types.contains(it) {
Ok(Some(SingleOrVec::Single(it.clone())))
} else {
Err(())
}
}
// If both are arrays, we take the intersection; if the intersection is
// empty, we return an error.
(Some(SingleOrVec::Vec(aa)), Some(SingleOrVec::Vec(bb))) => {
let types = aa
.iter()
.collect::<BTreeSet<_>>()
.intersection(&bb.iter().collect::<BTreeSet<_>>())
.cloned()
.cloned()
.collect::<Vec<_>>();
match types.len() {
// No intersection
0 => Err(()),
1 => Ok(Some(types.into_iter().next().unwrap().into())),
_ => Ok(Some(types.into())),
}
}
}
}
/// By and large, formats are pretty free-form and aren't really compatible
/// with each other. That is to say, if you have two formats at the same time
/// that's probably unsatisfiable. There are a few notable exceptions to this:
///
/// o integer widths -- take the narrowest
/// o "ip" vs. "ipv4" / "ipv6" -- take the more specific ip flavor
///
/// TODO incorporate the instance type / types here to limit what formats we
/// consider.
/// TODO We might need to handle this in a very type-specific way in order to
/// properly handle cases such as
/// "int8" and "uint8" -> { min: 0, max: 127, format: None }
fn merge_so_format(a: Option<&String>, b: Option<&String>) -> Result<Option<String>, ()> {
match (a.map(String::as_str), b.map(String::as_str)) {
(None, other) | (other, None) => Ok(other.map(String::from)),
(Some("ip"), result @ Some("ipv4"))
| (Some("ip"), result @ Some("ipv6"))
| (result @ Some("ipv4"), Some("ip"))
| (result @ Some("ipv6"), Some("ip")) => Ok(result.map(String::from)),
// Fine if they're both the same
(Some(aa), Some(bb)) if aa == bb => Ok(Some(aa.into())),
// ... they're not the same...
(Some(_), Some(_)) => Err(()),
}
}
fn merge_so_number(
a: Option<&NumberValidation>,
b: Option<&NumberValidation>,
) -> Result<Option<Box<NumberValidation>>, ()> {
match (a, b) {
(None, other) | (other, None) => Ok(other.cloned().map(Box::new)),
(Some(a), Some(b)) if a == b => Ok(Some(Box::new(a.clone()))),
(Some(_), Some(_)) => {
unimplemented!("this is fairly fussy and I don't want to do it")
}
}
}
fn merge_so_string(
a: Option<&StringValidation>,
b: Option<&StringValidation>,
) -> Result<Option<Box<StringValidation>>, ()> {
match (a, b) {
(None, other) | (other, None) => Ok(other.cloned().map(Box::new)),
(Some(a), Some(b)) if a == b => Ok(Some(Box::new(a.clone()))),
(Some(_), Some(_)) => {
unimplemented!("this is fairly fussy and I don't want to do it")
}
}
}
fn merge_so_array(
a: Option<&ArrayValidation>,
b: Option<&ArrayValidation>,
defs: &BTreeMap<RefKey, Schema>,
) -> Result<Option<Box<ArrayValidation>>, ()> {
match (a, b) {
(None, other) | (other, None) => Ok(other.cloned().map(Box::new)),
(Some(aa), Some(bb)) => {
let max_items = choose_value(aa.max_items, bb.max_items, Ord::min);
let min_items = choose_value(aa.min_items, bb.min_items, Ord::max);
let unique_items =
choose_value(aa.unique_items, bb.unique_items, std::ops::BitOr::bitor);
// We can only contain one thing; we can't resolve the need to
// contain two different things.
let contains = match (aa.contains.as_deref(), bb.contains.as_deref()) {
(None, other) | (other, None) => other.cloned().map(Box::new),
// We could probably do a more complex "equivalency" check e.g.
// that would follow references.
(Some(aa_contains), Some(bb_contains)) if aa_contains == bb_contains => {
Some(Box::new(aa_contains.clone()))
}
(Some(_), Some(_)) => return Err(()),
};
// If min > max the schema is unsatisfiable.
if let (Some(min), Some(max)) = (min_items, max_items) {
if min > max {
return Err(());
}
}
// The items and additional_items fields need to be considered
// together, and the results of merging can affect the max.
//
// - If items is a singleton, additional_items is ignored and all
// items in the array must obey the items schema.
//
// - If items is an array of size N, the Ith < N item must conform
// to the Ith schema. Subsequent items must conform to
// additional_items (so can be whatever if it is None =
// Schema::Bool(true))
//
// - If items is None (i.e. absent) additional_items is ignored and
// any value is permitted in any position of the array.
//
// Note that if there is a maximum array length specified and the
// items schema array is at least that long, additional_items is
// irrelevant so we omit it. This case appears several times below.
let (items, additional_items, max_items) = match (
(&aa.items, &aa.additional_items),
(&bb.items, &bb.additional_items),
) {
// Both items are none; items and additional_items are None.
((None, _), (None, _)) => (None, None, max_items),
// A None and a single-item; we can use the single item and
// additional_items are irrelevant.
((None, _), (Some(SingleOrVec::Single(item)), _))
| ((Some(SingleOrVec::Single(item)), _), (None, _)) => {
(Some(SingleOrVec::Single(item.clone())), None, max_items)
}
// A None and a array of schemas; we can take the array,
// modifying it only in consideration of the maximum length (if
// it is specified).
((None, _), (Some(SingleOrVec::Vec(items)), additional_items))
| ((Some(SingleOrVec::Vec(items)), additional_items), (None, _)) => {
match (max_items, items.len()) {
(Some(max), len) if len >= max as usize => (
Some(SingleOrVec::Vec(
items.iter().take(max as usize).cloned().collect(),
)),
None,
max_items,
),
_ => (
Some(SingleOrVec::Vec(items.clone())),
additional_items.clone(),
max_items,
),
}
}
// Two single schemas, just merge them; additional_items would
// be irrelevant.
(
(Some(SingleOrVec::Single(aa_single)), _),
(Some(SingleOrVec::Single(bb_single)), _),
) => (
Some(SingleOrVec::Single(Box::new(try_merge_schema(
aa_single, bb_single, defs,
)?))),
None,
max_items,
),
// A single item and an array of schemas. We merge the
// singleton with the array and additional_items as needed.
(
(Some(SingleOrVec::Single(single)), _),
(Some(SingleOrVec::Vec(items)), additional_items),
)
| (
(Some(SingleOrVec::Vec(items)), additional_items),
(Some(SingleOrVec::Single(single)), _),
) => {
let (items, allow_additional_items) = merge_items_array(
items.iter().zip(repeat(single.as_ref())),
min_items,
max_items,
defs,
)?;
if allow_additional_items {
let additional_items = additional_items.as_deref().map_or_else(
|| Ok(single.as_ref().clone()),
|additional_schema| try_merge_schema(additional_schema, single, defs),
)?;
(
Some(SingleOrVec::Vec(items)),
Some(Box::new(additional_items)),
max_items,
)
} else {
let len = items.len() as u32;
(Some(SingleOrVec::Vec(items)), None, Some(len))
}
}
// We need to pairwise merge schemas--as many as the longer
// of the two items arrays, limited by the max size of the
// array if one is specified. To do this we create
// iterators over the items followed by a repetition of the
// additional_items schema. We zip these together, merge, and
// limit them as appropriate.
(
(Some(SingleOrVec::Vec(aa_items)), aa_additional_items),
(Some(SingleOrVec::Vec(bb_items)), bb_additional_items),
) => {
let items_len = aa_items.len().max(bb_items.len());
// Note that one of these .chain(repeat(..)) statements is
// always irrelevant because we will always .take(..) the
// shorter of the two (and may consume even fewer). We just
// chain them both for simplicity and don't sweat it.
let aa_items_iter = aa_items.iter().chain(repeat(
aa_additional_items
.as_deref()
.unwrap_or(&Schema::Bool(true)),
));
let bb_items_iter = bb_items.iter().chain(repeat(
bb_additional_items
.as_deref()
.unwrap_or(&Schema::Bool(true)),
));
let items_iter = aa_items_iter.zip(bb_items_iter).take(items_len);
let (items, allow_additional_items) =
merge_items_array(items_iter, min_items, max_items, defs)?;
if allow_additional_items {
let additional_items = merge_additional_items(
aa_additional_items.as_deref(),
bb_additional_items.as_deref(),
defs,
);
(
Some(SingleOrVec::Vec(items)),
additional_items.map(Box::new),
max_items,
)
} else {
let len = items.len() as u32;
(Some(SingleOrVec::Vec(items)), None, Some(len))
}
}
};
Ok(Some(Box::new(ArrayValidation {
items,
additional_items,
max_items,
min_items,
unique_items,
contains,
})))
}
}
}
fn merge_items_array<'a>(
items_iter: impl Iterator<Item = (&'a Schema, &'a Schema)>,
min_items: Option<u32>,
max_items: Option<u32>,
defs: &BTreeMap<RefKey, Schema>,
) -> Result<(Vec<Schema>, bool), ()> {
let mut items = Vec::new();
for (a, b) in items_iter {
match try_merge_schema(a, b, defs) {
Ok(schema) => {
items.push(schema);
if let Some(max) = max_items {
if items.len() == max as usize {
return Ok((items, false));
}
}
}
Err(_) => {
let len = items.len() as u32;
if len < min_items.unwrap_or(1) {
return Err(());
}
return Ok((items, false));
}
}
}