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
use std::collections::{BTreeMap, BTreeSet};
use log::info;
use output::OutputSpace;
use proc_macro2::TokenStream;
use quote::quote;
use rustfmt_wrapper::rustfmt;
use schemars::schema::{Metadata, Schema};
use thiserror::Error;
use type_entry::{TypeEntry, TypeEntryDetails, TypeEntryNewtype, VariantDetails, WrappedValue};
#[cfg(test)]
mod test_util;
mod convert;
mod defaults;
mod enums;
mod output;
mod structs;
mod type_entry;
mod util;
mod value;
#[derive(Error, Debug)]
pub enum Error {
#[error("unexpected value type")]
BadValue(String, serde_json::Value),
#[error("invalid TypeId")]
InvalidTypeId,
#[error("value does not conform to the given schema")]
InvalidValue,
#[error("schema invalid: {0}")]
InvalidSchema(String),
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Type<'a> {
type_space: &'a TypeSpace,
type_entry: &'a TypeEntry,
}
pub enum TypeDetails<'a> {
Enum(TypeEnum<'a>),
Struct(TypeStruct<'a>),
Newtype(TypeNewtype<'a>),
Option(TypeId),
Array(TypeId),
Map(TypeId),
Set(TypeId),
Box(TypeId),
Tuple(Box<dyn Iterator<Item = TypeId> + 'a>),
Builtin(&'a str),
Unit,
String,
}
pub struct TypeEnum<'a> {
details: &'a type_entry::TypeEntryEnum,
}
pub enum TypeEnumVariant<'a> {
Simple,
Tuple(Vec<TypeId>),
Struct(Vec<(&'a str, TypeId)>),
}
pub struct TypeStruct<'a> {
details: &'a type_entry::TypeEntryStruct,
}
pub struct TypeNewtype<'a> {
details: &'a type_entry::TypeEntryNewtype,
}
#[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Clone)]
pub struct TypeId(u64);
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Name {
Required(String),
Suggested(String),
Unknown,
}
impl Name {
pub fn into_option(self) -> Option<String> {
match self {
Name::Required(s) | Name::Suggested(s) => Some(s),
Name::Unknown => None,
}
}
pub fn append(&self, s: &str) -> Self {
match self {
Name::Required(prefix) | Name::Suggested(prefix) => {
Self::Suggested(format!("{}_{}", prefix, s))
}
Name::Unknown => Name::Unknown,
}
}
}
#[derive(Debug)]
pub struct TypeSpace {
next_id: u64,
definitions: BTreeMap<String, Schema>,
id_to_entry: BTreeMap<TypeId, TypeEntry>,
type_to_id: BTreeMap<TypeEntryDetails, TypeId>,
name_to_id: BTreeMap<String, TypeId>,
ref_to_id: BTreeMap<String, TypeId>,
uses_chrono: bool,
uses_uuid: bool,
uses_serde_json: bool,
uses_regress: bool,
settings: TypeSpaceSettings,
defaults: BTreeSet<DefaultImpl>,
}
impl Default for TypeSpace {
fn default() -> Self {
Self {
next_id: 1,
definitions: Default::default(),
id_to_entry: Default::default(),
type_to_id: Default::default(),
name_to_id: Default::default(),
ref_to_id: Default::default(),
uses_chrono: Default::default(),
uses_uuid: Default::default(),
uses_serde_json: Default::default(),
uses_regress: Default::default(),
settings: Default::default(),
defaults: Default::default(),
}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum DefaultImpl {
Boolean,
I64,
U64,
}
#[derive(Debug, Default, Clone)]
pub struct TypeSpaceSettings {
type_mod: Option<String>,
extra_derives: Vec<String>,
struct_builder: bool,
}
impl TypeSpaceSettings {
pub fn with_type_mod<S: AsRef<str>>(&mut self, type_mod: S) -> &mut Self {
self.type_mod = Some(type_mod.as_ref().to_string());
self
}
pub fn with_derive(&mut self, derive: String) -> &mut Self {
self.extra_derives.push(derive);
self
}
pub fn with_struct_builder(&mut self, struct_builder: bool) -> &mut Self {
self.struct_builder = struct_builder;
self
}
}
impl TypeSpace {
pub fn new(settings: &TypeSpaceSettings) -> Self {
Self {
settings: settings.clone(),
..Default::default()
}
}
pub fn add_ref_types<I, S>(&mut self, type_defs: I) -> Result<()>
where
I: IntoIterator<Item = (S, Schema)>,
S: AsRef<str>,
{
let definitions = type_defs
.into_iter()
.map(|(name, schema)| (name.as_ref().to_string(), schema))
.collect::<Vec<(String, Schema)>>();
let base_id = self.next_id;
let def_len = definitions.len() as u64;
self.next_id += def_len;
for (index, (ref_name, schema)) in definitions.iter().enumerate() {
self.ref_to_id
.insert(ref_name.to_string(), TypeId(base_id + index as u64));
self.definitions.insert(ref_name.clone(), schema.clone());
}
for (index, (ref_name, schema)) in definitions.into_iter().enumerate() {
let type_name = match ref_name.rfind('/') {
Some(idx) => &ref_name[idx..],
None => &ref_name,
};
info!(
"converting type: {} with schema {}",
type_name,
serde_json::to_string(&schema).unwrap()
);
let (mut type_entry, metadata) =
self.convert_schema(Name::Required(type_name.to_string()), &schema)?;
let default = metadata
.as_ref()
.and_then(|m| m.default.as_ref())
.cloned()
.map(WrappedValue::new);
let type_entry = match &mut type_entry.details {
TypeEntryDetails::Enum(details) => {
details.default = default;
type_entry
}
TypeEntryDetails::Struct(details) => {
details.default = default;
type_entry
}
TypeEntryDetails::Newtype(details) => {
details.default = default;
type_entry
}
TypeEntryDetails::Reference(type_id) => TypeEntryNewtype::from_metadata(
Name::Required(type_name.to_string()),
metadata,
type_id.clone(),
)
.into(),
_ => TypeEntryNewtype::from_metadata(
Name::Required(type_name.to_string()),
metadata,
self.assign_type(type_entry),
)
.into(),
};
let entry_name = type_entry.name().unwrap().clone();
let type_id = TypeId(base_id + index as u64);
self.name_to_id.insert(entry_name, type_id.clone());
self.id_to_entry.insert(type_id, type_entry);
}
for index in 0..def_len {
let type_id = TypeId(base_id + index);
let mut type_entry = self.id_to_entry.get(&type_id).unwrap().clone();
type_entry.check_defaults(self)?;
let mut box_id = None;
self.break_trivial_cyclic_refs(&type_id, &mut type_entry, &mut box_id);
self.id_to_entry.insert(type_id, type_entry);
}
Ok(())
}
fn check_for_cyclic_ref(
&mut self,
parent_type_id: &TypeId,
child_type_id: &mut TypeId,
box_id: &mut Option<TypeId>,
) {
if *child_type_id == *parent_type_id {
*child_type_id = box_id
.get_or_insert_with(|| self.id_to_box(parent_type_id))
.clone();
} else {
let mut child_type_entry = self.id_to_entry.get_mut(child_type_id).unwrap().clone();
if let TypeEntryDetails::Option(option_type_id) = &mut child_type_entry.details {
if *option_type_id == *parent_type_id {
*option_type_id = box_id
.get_or_insert_with(|| self.id_to_box(parent_type_id))
.clone();
}
}
let _ = self
.id_to_entry
.insert(child_type_id.clone(), child_type_entry);
}
}
fn break_trivial_cyclic_refs(
&mut self,
parent_type_id: &TypeId,
type_entry: &mut TypeEntry,
box_id: &mut Option<TypeId>,
) {
match &mut type_entry.details {
TypeEntryDetails::Struct(s) => {
for prop in &mut s.properties {
self.check_for_cyclic_ref(parent_type_id, &mut prop.type_id, box_id);
}
}
TypeEntryDetails::Enum(type_entry_enum) => {
for variant in &mut type_entry_enum.variants {
match &mut variant.details {
VariantDetails::Simple => {}
VariantDetails::Tuple(vec_type_id) => {
for tuple_type_id in vec_type_id {
self.check_for_cyclic_ref(parent_type_id, tuple_type_id, box_id);
}
}
VariantDetails::Struct(vec_struct_property) => {
for struct_property in vec_struct_property {
let vec_type_id = &mut struct_property.type_id;
self.check_for_cyclic_ref(parent_type_id, vec_type_id, box_id);
}
}
}
}
}
TypeEntryDetails::Newtype(new_type_entry) => {
self.check_for_cyclic_ref(parent_type_id, &mut new_type_entry.type_id, box_id);
}
TypeEntryDetails::Array(_) => {}
TypeEntryDetails::Set(_) => {}
TypeEntryDetails::Map(_) => {}
_ => {}
}
}
pub fn add_type(&mut self, schema: &Schema) -> Result<TypeId> {
self.add_type_with_name(schema, None)
}
pub fn add_type_with_name(
&mut self,
schema: &Schema,
name_hint: Option<String>,
) -> Result<TypeId> {
let name = match name_hint {
Some(s) => Name::Suggested(s),
None => Name::Unknown,
};
let (mut type_entry, metadata) = self.convert_schema(name, schema)?;
if let Some(metadata) = metadata {
match &mut type_entry.details {
TypeEntryDetails::Enum(details) => {
details.default = metadata.default.clone().map(WrappedValue::new)
}
TypeEntryDetails::Struct(details) => {
details.default = metadata.default.clone().map(WrappedValue::new)
}
TypeEntryDetails::Newtype(details) => {
details.default = metadata.default.clone().map(WrappedValue::new)
}
_ => (),
}
type_entry.check_defaults(self)?;
}
Ok(self.assign_type(type_entry))
}
pub fn get_type(&self, type_id: &TypeId) -> Result<Type> {
let type_entry = self.id_to_entry.get(type_id).ok_or(Error::InvalidTypeId)?;
Ok(Type {
type_space: self,
type_entry,
})
}
pub fn uses_chrono(&self) -> bool {
self.uses_chrono
}
pub fn uses_regress(&self) -> bool {
self.uses_regress
}
pub fn uses_serde_json(&self) -> bool {
self.uses_serde_json
}
pub fn uses_uuid(&self) -> bool {
self.uses_uuid
}
pub fn iter_types(&self) -> impl Iterator<Item = Type> {
self.id_to_entry.values().map(move |type_entry| Type {
type_space: self,
type_entry,
})
}
pub fn common_code(&self) -> TokenStream {
if self.defaults.is_empty() {
quote! {}
} else {
let fns = self.defaults.iter().map(TokenStream::from);
quote! {
mod defaults {
#(#fns)*
}
}
}
}
pub fn to_stream(&self) -> TokenStream {
let mut output = OutputSpace::default();
self.id_to_entry
.values()
.for_each(|type_entry| type_entry.output(self, &mut output));
self.defaults
.iter()
.for_each(|x| output.add_item(output::OutputSpaceMod::Defaults, "", x.into()));
output.into_stream()
}
fn assign(&mut self) -> TypeId {
let id = TypeId(self.next_id);
self.next_id += 1;
id
}
fn assign_type(&mut self, ty: TypeEntry) -> TypeId {
if let TypeEntryDetails::Reference(type_id) = ty.details {
type_id
} else if let Some(name) = ty.name() {
if let Some(type_id) = self.name_to_id.get(name) {
let existing_ty = self.id_to_entry.get(type_id).unwrap();
assert_eq!(existing_ty, &ty);
type_id.clone()
} else {
let type_id = self.assign();
self.name_to_id.insert(name.clone(), type_id.clone());
self.id_to_entry.insert(type_id.clone(), ty);
type_id
}
} else if let Some(type_id) = self.type_to_id.get(&ty.details) {
type_id.clone()
} else {
let type_id = self.assign();
self.type_to_id.insert(ty.details.clone(), type_id.clone());
self.id_to_entry.insert(type_id.clone(), ty);
type_id
}
}
fn id_for_schema<'a>(
&mut self,
type_name: Name,
schema: &'a Schema,
) -> Result<(TypeId, &'a Option<Box<Metadata>>)> {
let (ty, metadata) = self.convert_schema(type_name, schema)?;
let type_id = self.assign_type(ty);
Ok((type_id, metadata))
}
fn id_to_option(&mut self, id: &TypeId) -> TypeId {
self.assign_type(TypeEntryDetails::Option(id.clone()).into())
}
fn type_to_option(&mut self, ty: TypeEntry) -> TypeEntry {
TypeEntryDetails::Option(self.assign_type(ty)).into()
}
fn id_to_box(&mut self, id: &TypeId) -> TypeId {
self.assign_type(TypeEntryDetails::Box(id.clone()).into())
}
}
impl ToString for TypeSpace {
fn to_string(&self) -> String {
rustfmt(self.to_stream().to_string()).unwrap()
}
}
impl<'a> Type<'a> {
pub fn name(&self) -> String {
let Type {
type_space,
type_entry,
} = self;
type_entry.type_name(type_space)
}
pub fn ident(&self) -> TokenStream {
let Type {
type_space,
type_entry,
} = self;
assert!(type_space.settings.type_mod.is_some());
type_entry.type_ident(type_space, &type_space.settings.type_mod)
}
pub fn parameter_ident(&self) -> TokenStream {
let Type {
type_space,
type_entry,
} = self;
type_entry.type_parameter_ident(type_space, None)
}
pub fn parameter_ident_with_lifetime(&self, lifetime: &str) -> TokenStream {
let Type {
type_space,
type_entry,
} = self;
type_entry.type_parameter_ident(type_space, Some(lifetime))
}
pub fn describe(&self) -> String {
self.type_entry.describe()
}
pub fn details(&self) -> TypeDetails {
match &self.type_entry.details {
TypeEntryDetails::Enum(details) => TypeDetails::Enum(TypeEnum { details }),
TypeEntryDetails::Struct(details) => TypeDetails::Struct(TypeStruct { details }),
TypeEntryDetails::Newtype(details) => TypeDetails::Newtype(TypeNewtype { details }),
TypeEntryDetails::Option(type_id) => TypeDetails::Option(type_id.clone()),
TypeEntryDetails::Array(type_id) => TypeDetails::Array(type_id.clone()),
TypeEntryDetails::Map(type_id) => TypeDetails::Map(type_id.clone()),
TypeEntryDetails::Set(type_id) => TypeDetails::Set(type_id.clone()),
TypeEntryDetails::Box(type_id) => TypeDetails::Box(type_id.clone()),
TypeEntryDetails::Tuple(types) => TypeDetails::Tuple(Box::new(types.iter().cloned())),
TypeEntryDetails::Unit => TypeDetails::Unit,
TypeEntryDetails::BuiltIn(name)
| TypeEntryDetails::Integer(name)
| TypeEntryDetails::Float(name) => TypeDetails::Builtin(name.as_str()),
TypeEntryDetails::Boolean => TypeDetails::Builtin("bool"),
TypeEntryDetails::String => TypeDetails::String,
TypeEntryDetails::Reference(_) => unreachable!(),
}
}
}
impl<'a> TypeEnum<'a> {
pub fn variants(&'a self) -> impl Iterator<Item = (&'a str, TypeEnumVariant<'a>)> {
self.details.variants.iter().map(move |variant| {
let v = match &variant.details {
type_entry::VariantDetails::Simple => TypeEnumVariant::Simple,
type_entry::VariantDetails::Tuple(types) => TypeEnumVariant::Tuple(types.clone()),
type_entry::VariantDetails::Struct(properties) => TypeEnumVariant::Struct(
properties
.iter()
.map(|prop| (prop.name.as_str(), prop.type_id.clone()))
.collect(),
),
};
(variant.name.as_str(), v)
})
}
}
impl<'a> TypeStruct<'a> {
pub fn properties(&'a self) -> impl Iterator<Item = (&'a str, TypeId)> {
self.details
.properties
.iter()
.map(move |prop| (prop.name.as_str(), prop.type_id.clone()))
}
}
impl<'a> TypeNewtype<'a> {
pub fn subtype(&self) -> TypeId {
self.details.type_id.clone()
}
}
#[cfg(test)]
mod tests {
use schema::Schema;
use schemars::{schema_for, JsonSchema};
use serde::Serialize;
use serde_json::json;
use std::collections::HashSet;
use crate::{
output::OutputSpace,
test_util::validate_output,
type_entry::{TypeEntryEnum, VariantDetails},
Name, TypeEntryDetails, TypeSpace,
};
#[allow(dead_code)]
#[derive(Serialize, JsonSchema)]
struct Blah {
blah: String,
}
#[allow(dead_code)]
#[derive(Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
enum E {
A,
B,
C(Blah),
D {
dd: String,
},
}
#[allow(dead_code)]
#[derive(JsonSchema)]
#[serde(rename_all = "camelCase")]
struct Foo {
#[serde(default)]
bar: Option<String>,
baz_baz: i32,
e: E,
}
#[test]
fn test_simple() {
let schema = schema_for!(Foo);
println!("{:#?}", schema);
let mut type_space = TypeSpace::default();
type_space.add_ref_types(schema.definitions).unwrap();
let (ty, _) = type_space
.convert_schema_object(Name::Unknown, &schema.schema)
.unwrap();
println!("{:#?}", ty);
let mut output = OutputSpace::default();
ty.output(&type_space, &mut output);
println!("{}", output.into_stream());
for ty in type_space.id_to_entry.values() {
println!("{:#?}", ty);
let mut output = OutputSpace::default();
ty.output(&type_space, &mut output);
println!("{}", output.into_stream());
}
}
#[test]
fn test_convert_enum_string() {
#[allow(dead_code)]
#[derive(JsonSchema)]
#[serde(rename_all = "camelCase")]
enum SimpleEnum {
DotCom,
Grizz,
Kenneth,
}
let schema = schema_for!(SimpleEnum);
println!("{:#?}", schema);
let mut type_space = TypeSpace::default();
type_space.add_ref_types(schema.definitions).unwrap();
let (ty, _) = type_space
.convert_schema_object(Name::Unknown, &schema.schema)
.unwrap();
match ty.details {
TypeEntryDetails::Enum(TypeEntryEnum { variants, .. }) => {
for variant in &variants {
assert_eq!(variant.details, VariantDetails::Simple);
}
let var_names = variants
.iter()
.map(|variant| variant.name.clone())
.collect::<HashSet<_>>();
assert_eq!(
var_names,
["DotCom", "Grizz", "Kenneth",]
.iter()
.map(ToString::to_string)
.collect::<HashSet<_>>()
);
}
_ => {
let mut output = OutputSpace::default();
ty.output(&type_space, &mut output);
println!("{}", output.into_stream());
panic!();
}
}
}
#[test]
fn test_string_enum_with_null() {
let enum_values = vec![
json!("Shadrach"),
json!("Meshach"),
json!("Abednego"),
json!(null),
];
let mut type_space = TypeSpace::default();
let (te, _) = type_space
.convert_enum_string(Name::Required("OnTheGo".to_string()), &None, &enum_values)
.unwrap();
if let TypeEntryDetails::Option(id) = &te.details {
let ote = type_space.id_to_entry.get(id).unwrap();
if let TypeEntryDetails::Enum(TypeEntryEnum { variants, .. }) = &ote.details {
let variants = variants
.iter()
.map(|v| match v.details {
VariantDetails::Simple => v.name.clone(),
_ => panic!("unexpected variant type"),
})
.collect::<HashSet<_>>();
assert_eq!(
variants,
enum_values
.iter()
.flat_map(|j| j.as_str().map(ToString::to_string))
.collect::<HashSet<_>>()
);
} else {
panic!("not the sub-type we expected {:#?}", te)
}
} else {
panic!("not the type we expected {:#?}", te)
}
}
#[test]
fn test_alias() {
#[derive(JsonSchema, Schema)]
struct Stuff(Vec<String>);
#[allow(dead_code)]
#[derive(JsonSchema, Schema)]
struct Things {
a: String,
b: Stuff,
}
validate_output::<Things>();
}
}