-
Notifications
You must be signed in to change notification settings - Fork 59
/
convert.rs
1727 lines (1573 loc) · 61.9 KB
/
convert.rs
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 2022 Oxide Computer Company
use std::collections::HashSet;
use crate::type_entry::{
EnumTagType, TypeEntry, TypeEntryDetails, TypeEntryEnum, TypeEntryNewtype, TypeEntryStruct,
Variant, VariantDetails,
};
use crate::util::{all_mutually_exclusive, none_or_single, recase, Case, StringValidator};
use log::info;
use schemars::schema::{
ArrayValidation, InstanceType, Metadata, ObjectValidation, Schema, SchemaObject, SingleOrVec,
StringValidation, SubschemaValidation,
};
use crate::util::get_type_name;
use crate::{Error, Name, Result, TypeSpace};
impl TypeSpace {
pub(crate) fn convert_schema<'a>(
&mut self,
type_name: Name,
schema: &'a Schema,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
match schema {
Schema::Object(obj) => {
if let Some(type_entry) = self.cache.lookup(obj) {
Ok((type_entry, &obj.metadata))
} else {
self.convert_schema_object(type_name, obj)
}
}
Schema::Bool(true) => self.convert_permissive(&None),
// TODO Not sure what to do here... need to return something toxic?
Schema::Bool(false) => todo!(),
}
}
pub(crate) fn convert_schema_object<'a>(
&mut self,
type_name: Name,
schema: &'a SchemaObject,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
match schema {
// If we have a schema that has an instance type array that's
// exactly two elements and one of them is Null, we have the
// equivalent of an Option<T> where T is the type defined by the
// rest of the schema.
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Vec(multiple)),
enum_values,
..
} if multiple.len() == 2 && multiple.contains(&InstanceType::Null) => {
if let Some(other_type) = multiple.iter().find(|t| t != &&InstanceType::Null) {
// In the sensible case where only one of the instance
// types is null.
let enum_values = enum_values.clone().map(|values| {
values
.iter()
.cloned()
.filter(|value| !value.is_null())
.collect()
});
let ss = Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::from(*other_type)),
enum_values,
..schema.clone()
});
self.convert_option(type_name, metadata, &ss)
} else {
// .. otherwise we try again with a simpler type.
let new_schema = SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Null))),
..schema.clone()
};
self.convert_schema_object(type_name, &new_schema)
.map(|(te, m)| match m {
Some(_) if m == metadata => (te, metadata),
Some(_) => panic!("unexpected metadata value"),
None => (te, &None),
})
}
}
// Strings
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string,
array: None,
object: None,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::String => self.convert_string(
type_name,
metadata,
format,
string.as_ref().map(Box::as_ref),
),
// Strings with the type omitted, but validation present
SchemaObject {
metadata,
instance_type: None,
format,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: string @ Some(_),
array: None,
object: None,
reference: None,
extensions: _,
} => self.convert_string(
type_name,
metadata,
format,
string.as_ref().map(Box::as_ref),
),
// Enumerated string type
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format: None,
enum_values: Some(enum_values),
const_value: None,
subschemas: None,
number: None,
string,
array: None,
object: None,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::String => self.convert_enum_string(
type_name,
metadata,
enum_values,
string.as_ref().map(Box::as_ref),
),
// Integers
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format,
enum_values: None,
const_value: None,
subschemas: None,
number: validation,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Integer => {
self.convert_integer(metadata, validation, format)
}
// Numbers
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format,
enum_values: None,
const_value: None,
subschemas: None,
number: validation,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Number => {
self.convert_number(metadata, validation, format)
}
// Boolean
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format: None,
enum_values: _,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Boolean => self.convert_bool(metadata),
// Structs
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: validation,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Object => {
self.convert_object(type_name, metadata, validation)
}
// Structs with the type omitted, but validation present
SchemaObject {
metadata,
instance_type: None,
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: validation @ Some(_),
reference: None,
extensions: _,
} => self.convert_object(type_name, metadata, validation),
// Arrays
SchemaObject {
metadata,
instance_type,
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: Some(validation),
object: None,
reference: None,
extensions: _,
} if none_or_single(instance_type, &InstanceType::Array) => {
self.convert_array(type_name, metadata, validation)
}
// Arrays of anything
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Array => self.convert_array_of_any(metadata),
// The permissive schema
SchemaObject {
metadata,
instance_type: None,
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} => self.convert_permissive(metadata),
// Null
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Null => self.convert_null(metadata),
// Reference
SchemaObject {
metadata,
instance_type: None,
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: None,
reference: Some(reference),
extensions: _,
} => self.convert_reference(metadata, reference),
// Enum of a single, known type.
SchemaObject {
instance_type: Some(SingleOrVec::Single(_)),
enum_values: Some(enum_values),
..
} => self.convert_typed_enum(type_name, schema, enum_values),
// Enum of unknown type
SchemaObject {
metadata,
instance_type: None,
format: None,
enum_values: Some(enum_values),
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} => self.convert_unknown_enum(type_name, metadata, enum_values),
// Subschemas
SchemaObject {
metadata,
instance_type: _,
format: None,
enum_values: None,
const_value: None,
subschemas: Some(subschemas),
number: None,
string: None,
array: None,
object: None,
reference: None,
extensions: _,
} => match subschemas.as_ref() {
SubschemaValidation {
all_of: Some(subschemas),
any_of: None,
one_of: None,
not: None,
if_schema: None,
then_schema: None,
else_schema: None,
} => self.convert_all_of(type_name, metadata, subschemas),
SubschemaValidation {
all_of: None,
any_of: Some(subschemas),
one_of: None,
not: None,
if_schema: None,
then_schema: None,
else_schema: None,
} => self.convert_any_of(type_name, metadata, subschemas),
SubschemaValidation {
all_of: None,
any_of: None,
one_of: Some(subschemas),
not: None,
if_schema: None,
then_schema: None,
else_schema: None,
} => self.convert_one_of(type_name, metadata, subschemas),
SubschemaValidation {
all_of: None,
any_of: None,
one_of: None,
not: Some(subschema),
if_schema: None,
then_schema: None,
else_schema: None,
} => self.convert_not(type_name, metadata, subschema),
// Unknown
_ => todo!("{:#?}", subschemas),
},
// TODO let's not bother with const values at the moment. In the
// future we could create types that have a single value with a
// newtype wrapper, but it's too much of a mess for too little
// value at the moment. Instead, we act as though this const_value
// field were None.
SchemaObject {
metadata,
const_value: Some(_),
..
} => {
let new_schema = SchemaObject {
const_value: None,
..schema.clone()
};
self.convert_schema_object(type_name, &new_schema)
.map(|(te, m)| match m {
Some(_) if m == metadata => (te, metadata),
Some(_) => panic!("unexpected metadata value"),
None => (te, &None),
})
}
// Unknown
SchemaObject { .. } => todo!("invalid (or unexpected) schema:\n{:#?}", schema),
}
}
fn convert_string<'a>(
&mut self,
type_name: Name,
metadata: &'a Option<Box<Metadata>>,
format: &Option<String>,
validation: Option<&StringValidation>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
match format.as_ref().map(String::as_str) {
None => match validation {
// It should not be possible for the StringValidation to be
// Some, but all its fields to be None, but... just to be sure.
None
| Some(schemars::schema::StringValidation {
max_length: None,
min_length: None,
pattern: None,
}) => Ok((TypeEntryDetails::String.into(), metadata)),
Some(validation) => {
if let Some(pattern) = &validation.pattern {
let _ = regress::Regex::new(pattern).map_err(|e| {
Error::InvalidSchema(format!("invalid pattern '{}' {}", pattern, e))
})?;
self.uses_regress = true;
}
let string = TypeEntryDetails::String.into();
let type_id = self.assign_type(string);
Ok((
TypeEntryNewtype::from_metadata_with_string_validation(
self, type_name, metadata, type_id, validation,
),
metadata,
))
}
},
Some("uuid") => {
self.uses_uuid = true;
Ok((TypeEntry::new_builtin("uuid::Uuid", &["Display"]), metadata))
}
Some("date") => {
self.uses_chrono = true;
Ok((
TypeEntry::new_builtin("chrono::Date<chrono::offset::Utc>", &["Display"]),
metadata,
))
}
Some("date-time") => {
self.uses_chrono = true;
Ok((
TypeEntry::new_builtin("chrono::DateTime<chrono::offset::Utc>", &["Display"]),
metadata,
))
}
Some("ip") => Ok((
TypeEntry::new_builtin("std::net::IpAddr", &["Display"]),
metadata,
)),
Some("ipv4") => Ok((
TypeEntry::new_builtin("std::net::Ipv4Addr", &["Display"]),
metadata,
)),
Some("ipv6") => Ok((
TypeEntry::new_builtin("std::net::Ipv6Addr", &["Display"]),
metadata,
)),
Some(unhandled) => {
info!("treating a string format '{}' as a String", unhandled);
Ok((TypeEntryDetails::String.into(), metadata))
}
}
}
pub(crate) fn convert_enum_string<'a>(
&mut self,
type_name: Name,
metadata: &'a Option<Box<Metadata>>,
enum_values: &[serde_json::Value],
validation: Option<&StringValidation>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
// We expect all enum values to be either a string **or** a null. We
// gather them all up and then choose to either be an enum of simple
// variants, or an Option of an enum of string variants depending on if
// a null is absent or present. Note that it's actually invalid JSON
// Schema if we do see a null here. In this code path the instance
// types should exclusively be "string" making null invalid. We
// intentionally handle instance types of ["string", "null"] prior to
// this case and strip out the null in both enum values and instance
// type. Nevertheless, we do our best to interpret even somewhat janky
// JSON schema.
let mut has_null = false;
let validator = StringValidator::new(validation)?;
let variants = enum_values
.iter()
.flat_map(|value| match value {
// It would be odd to have multiple null values, but we don't
// need to worry about it.
serde_json::Value::Null => {
has_null = true;
None
}
serde_json::Value::String(value) if validator.is_valid(value) => {
let (name, rename) = recase(value, Case::Pascal);
Some(Ok(Variant {
name,
rename,
description: None,
details: VariantDetails::Simple,
}))
}
// Ignore enum variants whose strings don't match the given
// constraints. If we wanted to get fancy we could include
// these variants in the enum but exclude them from the FromStr
// conversion... but that seems like unnecessary swag.
serde_json::Value::String(_) => None,
_ => Some(Err(Error::BadValue("string".to_string(), value.clone()))),
})
.collect::<Result<Vec<Variant>>>()?;
if variants.is_empty() {
if has_null {
self.convert_null(metadata)
} else {
Err(Error::InvalidSchema("empty enum array".to_string()))
}
} else {
let mut ty = TypeEntryEnum::from_metadata(
self,
type_name,
metadata,
EnumTagType::External,
variants,
false,
);
if has_null {
ty = self.type_to_option(ty);
}
Ok((ty, metadata))
}
}
fn convert_integer<'a>(
&self,
metadata: &'a Option<Box<Metadata>>,
validation: &Option<Box<schemars::schema::NumberValidation>>,
format: &Option<String>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
let (mut min, mut max, multiple) = if let Some(validation) = validation {
let min = match (&validation.minimum, &validation.exclusive_minimum) {
(None, None) => None,
(None, Some(value)) => Some(value + 1.0),
(Some(value), None) => Some(*value),
(Some(min), Some(emin)) => Some(min.max(emin + 1.0)),
};
let max = match (&validation.maximum, &validation.exclusive_maximum) {
(None, None) => None,
(None, Some(value)) => Some(value - 1.0),
(Some(value), None) => Some(*value),
(Some(max), Some(emax)) => Some(max.min(emax - 1.0)),
};
(min, max, validation.multiple_of)
} else {
(None, None, None)
};
// Ordered from most- to least-restrictive.
let formats: &[(&str, &str, f64, f64)] = &[
("int8", "i8", i8::MIN as f64, i8::MAX as f64),
("", "std::num::NonZeroU8", 1.0, u8::MAX as f64),
("uint8", "u8", u8::MIN as f64, u8::MAX as f64),
("int16", "i16", i16::MIN as f64, i16::MAX as f64),
("", "std::num::NonZeroU16", 1.0, u16::MAX as f64),
("uint16", "u16", u16::MIN as f64, u16::MAX as f64),
("int", "i32", i32::MIN as f64, i32::MAX as f64),
("int32", "i32", i32::MIN as f64, i32::MAX as f64),
("", "std::num::NonZeroU32", 1.0, u32::MAX as f64),
("uint", "u32", u32::MIN as f64, u32::MAX as f64),
("uint32", "u32", u32::MIN as f64, u32::MAX as f64),
// TODO all these are wrong as casting to an f64 loses precision.
// However, schemars stores everything as an f64 so... meh for now.
("int64", "i64", i64::MIN as f64, i64::MAX as f64),
("", "std::num::NonZeroU64", 1.0, u64::MAX as f64),
("uint64", "u64", u64::MIN as f64, u64::MAX as f64),
];
if let Some(format) = format {
if let Some((_, ty, imin, imax)) = formats
.iter()
.find(|(int_format, _, _, _)| int_format == format)
{
// If the type matches with other constraints, we're done.
if multiple.is_none()
&& (min.is_none() || min == Some(*imin))
&& (max.is_none() || max == Some(*imax))
{
// If there's a default value and it's either not a number
// or outside of the range for this format, return an
// error.
if let Some(default) = metadata
.as_ref()
.and_then(|m| m.default.as_ref())
.and_then(|v| v.as_f64())
{
if default < *imin || default > *imax {
return Err(Error::InvalidValue);
}
}
return Ok((TypeEntry::new_integer(ty), metadata));
}
if min.is_none() {
min = Some(*imin);
}
if max.is_none() {
max = Some(*imax);
}
}
}
// We check the default value here since we have the min and max
// close at hand.
if let Some(default) = metadata.as_ref().and_then(|m| m.default.as_ref()) {
// TODO it's imprecise (in every sense of the word) to use an
// f64 here, but we're already constrained by the schemars
// representation so ... it's probably the best we can do at
// the moment.
match (default.as_f64(), min, max) {
(Some(_), None, None) => Some(()),
(Some(value), None, Some(fmax)) if value <= fmax => Some(()),
(Some(value), Some(fmin), None) if value >= fmin => Some(()),
(Some(value), Some(fmin), Some(fmax)) if value >= fmin && value <= fmax => Some(()),
_ => None,
}
.ok_or(Error::InvalidValue)?;
}
// See if the value bounds fit within a known type.
let maybe_type = match (min, max) {
(None, Some(max)) => formats.iter().find_map(|(_, ty, _, imax)| {
if imax + f64::EPSILON >= max {
Some(ty.to_string())
} else {
None
}
}),
(Some(min), None) => formats.iter().find_map(|(_, ty, imin, _)| {
if imin - f64::EPSILON <= min {
Some(ty.to_string())
} else {
None
}
}),
(Some(min), Some(max)) => formats.iter().find_map(|(_, ty, imin, imax)| {
if imax + f64::EPSILON >= max && imin - f64::EPSILON <= min {
Some(ty.to_string())
} else {
None
}
}),
(None, None) => None,
};
// TODO we should do something with `multiple`
if let Some(ty) = maybe_type {
Ok((TypeEntry::new_integer(ty), metadata))
} else {
// TODO we could construct a type that itself enforces the various
// bounds.
// TODO failing that, we should find the type that most tightly
// matches these bounds.
Ok((TypeEntry::new_integer("i64"), metadata))
}
}
// TODO deal with metadata and format
fn convert_number<'a>(
&self,
_metadata: &'a Option<Box<Metadata>>,
validation: &Option<Box<schemars::schema::NumberValidation>>,
_format: &Option<String>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
if let Some(validation) = validation {
assert!(validation.multiple_of.is_none());
assert!(validation.maximum.is_none());
assert!(validation.exclusive_maximum.is_none());
assert!(validation.minimum.is_none());
assert!(validation.exclusive_minimum.is_none());
}
Ok((TypeEntry::new_float("f64"), &None))
}
/// If we have a schema that's just the Null instance type, it represents a
/// solitary value so we model that with the unit type.
fn convert_null<'a>(
&self,
metadata: &'a Option<Box<Metadata>>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
Ok((TypeEntryDetails::Unit.into(), metadata))
}
fn convert_object<'a>(
&mut self,
type_name: Name,
metadata: &'a Option<Box<Metadata>>,
validation: &Option<Box<ObjectValidation>>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
match validation.as_ref().map(Box::as_ref) {
// Maps have an empty properties set, and a non-null schema for the
// additional_properties field.
Some(ObjectValidation {
max_properties: None,
min_properties: None,
required,
properties,
pattern_properties,
additional_properties,
property_names: None,
}) if required.is_empty()
&& properties.is_empty()
&& pattern_properties.is_empty()
&& additional_properties.as_ref().map(AsRef::as_ref)
!= Some(&Schema::Bool(false)) =>
{
self.make_map(type_name.into_option(), additional_properties)
}
None => self.make_map(type_name.into_option(), &None),
// The typical case
Some(validation) => {
let tmp_type_name = get_type_name(&type_name, metadata);
let (properties, deny_unknown_fields) =
self.struct_members(tmp_type_name, validation)?;
Ok((
TypeEntryStruct::from_metadata(
self,
type_name,
metadata,
properties,
deny_unknown_fields,
),
&None,
))
}
}
}
fn convert_reference<'a>(
&self,
metadata: &'a Option<Box<Metadata>>,
ref_name: &str,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
let key = match ref_name.rfind('/') {
Some(idx) => &ref_name[idx + 1..],
None => ref_name,
};
let type_id = self.ref_to_id.get(key).unwrap();
Ok((
TypeEntryDetails::Reference(type_id.clone()).into(),
metadata,
))
}
fn convert_all_of<'a>(
&mut self,
type_name: Name,
metadata: &'a Option<Box<Metadata>>,
subschemas: &[Schema],
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
if let Some(ty) = self.maybe_singleton_subschema(type_name.clone(), subschemas) {
return Ok((ty, metadata));
}
if let Some(ty) = self.maybe_all_of_constraints(type_name.clone(), subschemas) {
return Ok((ty, metadata));
}
if let Some(ty) = self.maybe_all_of_subclass(type_name.clone(), metadata, subschemas) {
return Ok((ty, metadata));
}
// TODO JSON schema is annoying. In particular, "allOf" means that all
// schemas must validate. So for us to construct the schema below, each
// type must actually be "open" i.e. it must permit arbitrary
// properties. If it does not, the schemas would not validate i.e. a
// value (object) could not satisfy both Schema1 and Schema2. To do
// this as accurately as possible, we would need to validate that each
// subschema was "open", pull out the "extra" item from each one, etc.
// We'll want to build a struct that looks like this:
// struct Name {
// #[serde(flatten)]
// schema1: Schema1Type,
// #[serde(flatten)]
// schema2: Schema2Type,
// ...
// }
self.flattened_union_struct(type_name, metadata, subschemas, false)
}
fn convert_any_of<'a>(
&mut self,
type_name: Name,
metadata: &'a Option<Box<Metadata>>,
subschemas: &[Schema],
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
// Rust can emit "anyOf":[{"$ref":"#/definitions/C"},{"type":"null"}
// for Option. We match this here because the mutual exclusion check
// below may fail for cases such as Option<T> where T is defined to be,
// say, (). In such a case, both variants are actually null.
if let Some(ty) = self.maybe_option(type_name.clone(), metadata, subschemas) {
return Ok((ty, metadata));
}
// Check if this could be more precisely handled as a "one-of". This
// occurs if each subschema is mutually exclusive i.e. so that exactly
// one of them can match.
if all_mutually_exclusive(subschemas, &self.definitions) {
self.convert_one_of(type_name, metadata, subschemas)
} else {
// We'll want to build a struct that looks like this:
// struct Name {
// #[serde(flatten)]
// schema1: Option<Schema1Type>,
// #[serde(flatten)]
// schema2: Option<Schema2Type>,
// ...
// }
self.flattened_union_struct(type_name, metadata, subschemas, true)
}
}
/// A "one of" may reasonably be converted into a Rust enum, but there are
/// several cases to consider:
///
/// Options expressed as enums are uncommon since { "type": [ "null",
/// "<type>"], ... } is a much simpler construction. Nevertheless, an
/// option may be expressed as a "one of" with two subschemas where one is
/// null.
///
/// Externally tagged enums are comprised of either an enumerated set of
/// string values or objects that have a single required member. The
/// variant is either the enumerated value with no data or the required
/// member with its type as the associated data. Note that this is the
/// serde default.
///
/// Internally tagged enums are comprised exclusively of objects where each
/// object has a required property in common and this required property
/// must be a string with a single fixed value. The property becomes the
/// serde tag and the value becomes the variant. Any additional properties
/// on that object become the data associated with the given variant.
///
/// Adjacently tagged enums are comprised exclusively of objects that have
/// a tag and content field in common (though the content field will only
/// be present for variants that include data). The value of the tag
/// should, as above, be a string with a single enumerated value. The value
/// of the content field, if it exists, becomes the data payload for the
/// variant.
///
/// Untagged enums intentionally omit a named tag. There are no constraints
/// on untagged enums so this is our fallback if the tagging schemes above
/// don't apply. While untagged enums are not always strictly exclusive by
/// construction, we know that *these* variants must be mutually exclusive
/// if we've ended up here. Note that untagged variants are distinguished
/// by their data, so a single variant may exist with no associated data,
/// but we'd expect that variant to be null or an empty struct. This case
/// requires us to invent variant names since that information is not
/// included in the schema data.
///
/// Note that the order of checking for tagging schemes must be carefully
/// considered. Adjacent tagging must be checked before internal tagging as
/// the former is a subset of the latter: the content field could be
/// interpreted as a struct variant with a single field:
///
/// ```ignore
/// enum MyEnum {
/// Variant1 { content: MyObj },
/// Variant2 { content: MyObj },
/// }
/// ```
///
/// Fortunately, external tagging can't be confused with internal or
/// adjacent tagging except in reductive cases such as enums with a single
/// variant.
///
/// Untagged enums apply to any set of subschemas so must be applied last.
pub(crate) fn convert_one_of<'a>(
&mut self,
type_name: Name,
metadata: &'a Option<Box<schemars::schema::Metadata>>,
subschemas: &[Schema],
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
let ty = self
.maybe_option(type_name.clone(), metadata, subschemas)
.or_else(|| self.maybe_externally_tagged_enum(type_name.clone(), metadata, subschemas))
.or_else(|| self.maybe_adjacently_tagged_enum(type_name.clone(), metadata, subschemas))
.or_else(|| self.maybe_internally_tagged_enum(type_name.clone(), metadata, subschemas))
.or_else(|| self.maybe_singleton_subschema(type_name.clone(), subschemas))
.map_or_else(|| self.untagged_enum(type_name, metadata, subschemas), Ok)?;
Ok((ty, metadata))
}
/// The "not" construction is pretty challenging to handle in the general
/// case: what is the appropriate rust structure for a type that is merely
/// the exclusion of another? This is tractable, however, in some special
/// cases that occur frequently enough in the wild to consider them.
///
/// The simplest is for the boolean schemas: true to accept everything;
/// false to accept nothing. These we can simply invert. Why someone would
/// specify a type in this fashion... hard to say.
///
/// The next we consider is that of enumerated values: if the schema
/// explicitly enumerates its valid values, we can construct a type that
/// disallows those values (just as we have a type that may only be one of
/// several specific values). We either use the specified type (e.g.
/// string) or infer the type from the enumerated values. These are
/// represented as a newtype that contains a deny list (rather than an
/// allow list as is the case for non-string enumerated values).
pub(crate) fn convert_not<'a>(
&mut self,
type_name: Name,
metadata: &'a Option<Box<schemars::schema::Metadata>>,
subschema: &'a Schema,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
match subschema {
// This is a weird construct, but simple enough to handle.
Schema::Bool(b) => {
let (type_entry, _) = self.convert_schema(type_name, &Schema::Bool(!b))?;
Ok((type_entry, metadata))
}
// An explicit type and enumerated values.
Schema::Object(
schema @ SchemaObject {
instance_type: Some(SingleOrVec::Single(_)),
enum_values: Some(enum_values),
..
},
) => {
let type_schema = SchemaObject {
enum_values: None,
..schema.clone()
};
let (type_entry, _) = self.convert_schema_object(Name::Unknown, &type_schema)?;
// Make sure all the values are valid.
// TODO this isn't strictly legal since we may not yet have
// resolved references.
enum_values
.iter()
.try_for_each(|value| type_entry.validate_value(self, value).map(|_| ()))?;
let type_id = self.assign_type(type_entry);
let newtype_entry = TypeEntryNewtype::from_metadata_with_deny_values(
self,
type_name,
metadata,
type_id,
enum_values,
);