-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathconvert.rs
More file actions
2397 lines (2215 loc) · 88.8 KB
/
convert.rs
File metadata and controls
2397 lines (2215 loc) · 88.8 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 2025 Oxide Computer Company
use std::collections::BTreeSet;
use crate::merge::{merge_all, try_merge_with_subschemas};
use crate::type_entry::{
EnumTagType, TypeEntry, TypeEntryDetails, TypeEntryEnum, TypeEntryNewtype, TypeEntryStruct,
Variant, VariantDetails,
};
use crate::util::{all_mutually_exclusive, ref_key, ReorderedInstanceType, StringValidator};
use log::{debug, 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, TypeSpaceImpl};
pub const STD_NUM_NONZERO_PREFIX: &str = "::std::num::NonZero";
impl TypeSpace {
pub(crate) fn convert_schema<'a>(
&mut self,
type_name: Name,
schema: &'a Schema,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
info!(
"convert_schema {:?} {}",
type_name,
serde_json::to_string_pretty(schema).unwrap()
);
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, schema, obj)
}
}
Schema::Bool(true) => self.convert_permissive(&None),
Schema::Bool(false) => self.convert_never(type_name, schema),
}
}
pub(crate) fn convert_schema_object<'a>(
&mut self,
type_name: Name,
original_schema: &'a Schema,
schema: &'a SchemaObject,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
if let Some(type_entry) = self.convert_rust_extension(schema) {
return Ok((type_entry, &schema.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) => {
let only_null = enum_values
.as_ref()
.is_some_and(|values| values.iter().all(serde_json::Value::is_null));
if only_null {
// If there are enumerated values and they're all null,
// it's just a null.
self.convert_null(metadata)
} else 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()
.filter(|&value| !value.is_null())
.cloned()
.collect()
});
let ss = Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::from(*other_type)),
enum_values,
..schema.clone()
});
// An Option type won't usually get a name--unless one is
// required (in which case we'll generated a newtype
// wrapper to give it a name). In such a case, we invent a
// new name for the inner type; otherwise, the inner type
// can just have this name.
let inner_type_name = match &type_name {
Name::Required(name) => Name::Suggested(format!("{}Inner", name)),
_ => type_name,
};
self.convert_option(inner_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, original_schema, &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: _,
string,
array: _,
object: _,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::String => self.convert_string(
type_name,
original_schema,
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,
original_schema,
metadata,
format,
string.as_ref().map(Box::as_ref),
),
// Enumerated string type
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
// One could imagine wanting to honor the format field in this
// case, perhaps to generate an impl From<T> for Uuid, say that
// allowed for fluid conversion from the enum to a type
// corresponding to the format string. But that seems uncommon
// enough to ignore for the moment.
format: _,
enum_values: Some(enum_values),
const_value: None,
subschemas: None,
number: _,
string,
array: _,
object: _,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::String => self.convert_enum_string(
type_name,
original_schema,
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: _,
array: _,
object: _,
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: _,
array: _,
object: _,
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: _,
string: _,
array: _,
object: _,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Boolean => self.convert_bool(metadata),
// Object
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: _,
string: _,
array: _,
object: validation,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Object => {
self.convert_object(type_name, original_schema, metadata, validation)
}
// Object 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, original_schema, metadata, validation),
// Array
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Single(single)),
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: _,
string: _,
array: Some(validation),
object: _,
reference: None,
extensions: _,
} if single.as_ref() == &InstanceType::Array => {
self.convert_array(type_name, metadata, validation)
}
// Array 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: Some(validation),
object: None,
reference: None,
extensions: _,
} => 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: _,
string: _,
array: None,
object: _,
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: _,
enum_values: None,
const_value: None,
subschemas: None,
number: _,
string: _,
array: _,
object: _,
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),
// Accept references that... for some reason... include the type.
// TODO this could be generalized to validate any redundant
// validation here or could be used to compute a new, more
// constrained type.
// TODO the strictest interpretation might be to ignore any fields
// that appear alongside "$ref" per
// https://json-schema.org/understanding-json-schema/structuring.html#ref
SchemaObject {
metadata,
instance_type,
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: None,
array: None,
object: None,
reference: Some(reference),
extensions: _,
} => {
let ref_schema = self.definitions.get(&ref_key(reference)).unwrap();
assert!(matches!(ref_schema, Schema::Object(SchemaObject {
instance_type: it, ..
}) if instance_type == it));
self.convert_reference(metadata, reference)
}
SchemaObject {
metadata,
instance_type: _,
format: _,
enum_values: _,
const_value: _,
subschemas: _,
number: _,
string: _,
array: _,
object: _,
reference: Some(reference),
extensions: _,
} => {
let mut def = self.definitions.get(&ref_key(reference)).unwrap();
let mut new_schema = Schema::Object(SchemaObject {
reference: None,
..schema.clone()
});
while let Schema::Object(SchemaObject { reference: r, .. }) = def {
let schema_only_ref = Schema::Object(SchemaObject {
reference: r.clone(),
..Default::default()
});
let schema_without_ref = Schema::Object(SchemaObject {
reference: None,
..def.clone().into_object()
});
new_schema = merge_all(
&[schema_without_ref, schema_only_ref, new_schema],
&self.definitions,
);
if let Some(r) = r {
def = self.definitions.get(&ref_key(r)).unwrap();
} else {
break;
}
}
let (type_entry, _) = self.convert_schema(type_name, &new_schema).unwrap();
Ok((type_entry, metadata))
}
// Enum of a single, known, non-String type (strings above).
SchemaObject {
instance_type: Some(SingleOrVec::Single(_)),
enum_values: Some(enum_values),
..
} => self.convert_typed_enum(type_name, original_schema, 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, original_schema, metadata, enum_values),
// Subschemas
SchemaObject {
metadata,
// TODO we probably shouldn't ignore this...
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, original_schema, 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, original_schema, 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, original_schema, 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, original_schema, metadata, subschema),
// Multiple subschemas may be present at the same time; attempt
// to merge and then convert.
subschemas => {
// Remove the subschemas so we can merge into the rest.
let schema_object = SchemaObject {
subschemas: None,
..schema.clone()
};
let merged_schema = try_merge_with_subschemas(
schema_object,
Some(subschemas),
&self.definitions,
);
match merged_schema {
Ok(s) => {
let (type_entry, _) =
self.convert_schema_object(type_name, original_schema, &s)?;
Ok((type_entry, &None))
}
// An error indicates that the schema is unresolvable.
Err(_) => self.convert_never(type_name, original_schema),
}
}
},
// Subschemas with other stuff.
SchemaObject {
metadata,
subschemas: subschemas @ Some(_),
..
} => {
let without_subschemas = SchemaObject {
subschemas: None,
metadata: None,
..schema.clone()
};
debug!(
"pre merged schema {}",
serde_json::to_string_pretty(schema).unwrap(),
);
match try_merge_with_subschemas(
without_subschemas,
subschemas.as_deref(),
&self.definitions,
) {
Ok(merged_schema) => {
// Preserve metadata from the outer schema.
let merged_schema = SchemaObject {
metadata: metadata.clone(),
..merged_schema
};
debug!(
"merged schema {}",
serde_json::to_string_pretty(&merged_schema).unwrap(),
);
let (type_entry, _) =
self.convert_schema_object(type_name, original_schema, &merged_schema)?;
Ok((type_entry, &None))
}
Err(_) => self.convert_never(type_name, original_schema),
}
}
// 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, original_schema, &new_schema)
.map(|(te, m)| match m {
Some(_) if m == metadata => (te, metadata),
Some(_) => panic!("unexpected metadata value"),
None => (te, &None),
})
}
// In actual, not-made-up, in-the-wild specs, I've seen the type
// field enumerate all possibilities... perhaps to emphasize their
// seriousness of the schema representing **anything**. In that
// case, we can strip it out and try again.
SchemaObject {
instance_type: Some(SingleOrVec::Vec(instance_types)),
metadata,
..
} if instance_types.contains(&InstanceType::Null)
&& instance_types.contains(&InstanceType::Boolean)
&& instance_types.contains(&InstanceType::Object)
&& instance_types.contains(&InstanceType::Array)
&& instance_types.contains(&InstanceType::Number)
&& instance_types.contains(&InstanceType::String)
&& instance_types.contains(&InstanceType::Integer) =>
{
let (type_entry, _) = self.convert_schema_object(
type_name,
original_schema,
&SchemaObject {
instance_type: None,
..schema.clone()
},
)?;
Ok((type_entry, metadata))
}
// Treat a singleton type array like a singleton type.
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Vec(instance_types)),
..
} if instance_types.len() == 1 => {
let [it] = instance_types.as_slice() else {
unreachable!()
};
let (type_entry, _) = self.convert_schema_object(
type_name,
original_schema,
&SchemaObject {
instance_type: Some(SingleOrVec::Single((*it).into())),
..schema.clone()
},
)?;
Ok((type_entry, metadata))
}
// Turn schemas with multiple types into an untagged enum labeled
// according to the given type. We associate any validation with
// the appropriate type. Note that the case of a 2-type list with
// one of them Null is already handled more specifically above (and
// rendered into an Option type).
SchemaObject {
metadata,
instance_type: Some(SingleOrVec::Vec(instance_types)),
format,
enum_values: None,
const_value: None,
subschemas: None,
number,
string,
array,
object,
reference: None,
extensions: _,
} => {
// Eliminate duplicates (they hold no significance); they
// aren't supposed to be there, but we can still handle it.
// Convert the types into a form that puts integers before numbers to ensure that
// integer get matched before numbers in untagged enum generation.
let unique_types = instance_types
.iter()
.copied()
.map(ReorderedInstanceType::from)
.collect::<BTreeSet<_>>();
// Massage the data into labeled subschemas with the following
// format:
//
// {
// "title": <instance type name>,
// "allOf": [
// {
// "type": <instance type>,
// <validation relevant to the type>
// }
// ]
// }
//
// We can then take these and construct an untagged enum. The
// outer "allOf" schema lets name the variant.
//
// Note that we *could* simply copy the full schema, trusting
// recursive calls to pull out the appropriate components...
// but why do tomorrow what we could easily to today?
let subschemas = unique_types
.into_iter()
.map(InstanceType::from)
.map(|it| {
let instance_type = Some(SingleOrVec::Single(Box::new(it)));
let (label, inner_schema) = match it {
InstanceType::Null => (
"null",
SchemaObject {
instance_type,
..Default::default()
},
),
InstanceType::Boolean => (
"boolean",
SchemaObject {
instance_type,
..Default::default()
},
),
InstanceType::Object => (
"object",
SchemaObject {
instance_type,
object: object.clone(),
..Default::default()
},
),
InstanceType::Array => (
"array",
SchemaObject {
instance_type,
array: array.clone(),
..Default::default()
},
),
InstanceType::Number => (
"number",
SchemaObject {
instance_type,
format: format.clone(),
number: number.clone(),
..Default::default()
},
),
InstanceType::String => (
"string",
SchemaObject {
instance_type,
format: format.clone(),
string: string.clone(),
..Default::default()
},
),
InstanceType::Integer => (
"integer",
SchemaObject {
instance_type,
format: format.clone(),
number: number.clone(),
..Default::default()
},
),
};
// Make the wrapping schema.
Schema::Object(SchemaObject {
metadata: Some(Box::new(Metadata {
title: Some(label.to_string()),
..Default::default()
})),
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(vec![inner_schema.into()]),
..Default::default()
})),
..Default::default()
})
})
.collect::<Vec<_>>();
let type_entry =
self.untagged_enum(type_name, original_schema, metadata, &subschemas)?;
Ok((type_entry, metadata))
}
// Unknown
SchemaObject { .. } => todo!(
"invalid (or unexpected) schema:\n{}",
serde_json::to_string_pretty(schema).unwrap()
),
}
}
fn convert_string<'a>(
&mut self,
type_name: Name,
original_schema: &'a Schema,
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 {
type_name: type_name.clone().into_option(),
reason: 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,
original_schema.clone(),
),
metadata,
))
}
},
Some("uuid") => {
self.uses_uuid = true;
Ok((
TypeEntry::new_native(
"::uuid::Uuid",
&[TypeSpaceImpl::Display, TypeSpaceImpl::FromStr],
),
metadata,
))
}
Some("date") => {
self.uses_chrono = true;
Ok((
TypeEntry::new_native(
"::chrono::naive::NaiveDate",
&[TypeSpaceImpl::Display, TypeSpaceImpl::FromStr],
),
metadata,
))
}
Some("date-time") => {
self.uses_chrono = true;
Ok((
TypeEntry::new_native(
"::chrono::DateTime<::chrono::offset::Utc>",
&[TypeSpaceImpl::Display, TypeSpaceImpl::FromStr],
),
metadata,
))
}
Some("ip") => Ok((
TypeEntry::new_native(
"::std::net::IpAddr",
&[TypeSpaceImpl::Display, TypeSpaceImpl::FromStr],
),
metadata,
)),
Some("ipv4") => Ok((
TypeEntry::new_native(
"::std::net::Ipv4Addr",
&[TypeSpaceImpl::Display, TypeSpaceImpl::FromStr],
),
metadata,
)),
Some("ipv6") => Ok((
TypeEntry::new_native(
"::std::net::Ipv6Addr",
&[TypeSpaceImpl::Display, TypeSpaceImpl::FromStr],
),
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,
original_schema: &'a Schema,
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 incorrect
// JSON schema.
let mut has_null = false;
let validator = StringValidator::new(&type_name, 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(variant_name) if validator.is_valid(variant_name) => {
Some(Ok(Variant::new(
variant_name.clone(),
None,
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 {
self.convert_never(type_name, original_schema)
}
} else {
let mut ty = TypeEntryEnum::from_metadata(
self,
type_name,
metadata,
EnumTagType::External,
variants,
false,
original_schema.clone(),
);
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.
// JSONSchema format, Rust Type, Rust NonZero Type, Rust type min, Rust type max
let formats: &[(&str, &str, &str, f64, f64)] = &[
(