forked from carllerche/codegen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
1683 lines (1376 loc) · 39.7 KB
/
lib.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
//! Provides a builder API for generating Rust code.
//!
//! The general strategy for using the crate is as follows:
//!
//! 1. Create a `Scope` instance.
//! 2. Use the builder API to add elements to the scope.
//! 3. Call `Scope::to_string()` to get the generated code.
//!
//! For example:
//!
//! ```rust
//! use codegen::Scope;
//!
//! let mut scope = Scope::new();
//!
//! scope.new_struct("Foo")
//! .derive("Debug")
//! .field("one", "usize")
//! .field("two", "String");
//!
//! println!("{}", scope.to_string());
//! ```
#![deny(warnings, missing_debug_implementations, missing_docs)]
extern crate ordermap;
use ordermap::OrderMap;
use std::fmt::{self, Write};
/// Defines a scope.
///
/// A scope contains modules, types, etc...
#[derive(Debug, Clone)]
pub struct Scope {
/// Scope documentation
docs: Option<Docs>,
/// Imports
imports: OrderMap<String, OrderMap<String, Import>>,
/// Contents of the documentation,
items: Vec<Item>,
}
#[derive(Debug, Clone)]
enum Item {
Module(Module),
Struct(Struct),
Trait(Trait),
Enum(Enum),
Impl(Impl),
Raw(String),
}
/// Defines a module.
#[derive(Debug, Clone)]
pub struct Module {
/// Module name
name: String,
/// Visibility
vis: Option<String>,
/// Module documentation
docs: Option<Docs>,
/// Contents of the module
scope: Scope,
}
/// Defines an enumeration.
#[derive(Debug, Clone)]
pub struct Enum {
type_def: TypeDef,
variants: Vec<Variant>,
}
/// Defines a struct.
#[derive(Debug, Clone)]
pub struct Struct {
type_def: TypeDef,
/// Struct fields
fields: Fields,
}
/// Define a trait.
#[derive(Debug, Clone)]
pub struct Trait {
type_def: TypeDef,
parents: Vec<Type>,
associated_tys: Vec<AssociatedType>,
fns: Vec<Function>,
}
/// Defines a type.
#[derive(Debug, Clone)]
pub struct Type {
name: String,
generics: Vec<Type>,
}
/// Defines a type definition.
#[derive(Debug, Clone)]
struct TypeDef {
ty: Type,
vis: Option<String>,
docs: Option<Docs>,
derive: Vec<String>,
bounds: Vec<Bound>,
}
/// Defines an enum variant.
#[derive(Debug, Clone)]
pub struct Variant {
name: String,
fields: Fields,
}
/// Defines a set of fields.
#[derive(Debug, Clone)]
enum Fields {
Empty,
Tuple(Vec<Type>),
Named(Vec<Field>),
}
/// Defines a struct field.
#[derive(Debug, Clone)]
pub struct Field {
/// Field name
name: String,
/// Field type
ty: Type,
/// Field documentation
documentation: String,
/// Field annotation
annotation: String,
}
/// Defines an associated type.
#[derive(Debug, Clone)]
pub struct AssociatedType(Bound);
#[derive(Debug, Clone)]
struct Bound {
name: String,
bound: Vec<Type>,
}
/// Defines an impl block.
#[derive(Debug, Clone)]
pub struct Impl {
/// The struct being implemented
target: Type,
/// Impl level generics
generics: Vec<String>,
/// If implementing a trait
impl_trait: Option<Type>,
/// Associated types
assoc_tys: Vec<Field>,
/// Bounds
bounds: Vec<Bound>,
fns: Vec<Function>,
}
/// Defines an import (`use` statement).
#[derive(Debug, Clone)]
pub struct Import {
line: String,
vis: Option<String>,
}
/// Defines a function.
#[derive(Debug, Clone)]
pub struct Function {
/// Name of the function
name: String,
/// Function documentation
docs: Option<Docs>,
/// Function visibility
vis: Option<String>,
/// Function generics
generics: Vec<String>,
/// If the function takes `&self` or `&mut self`
arg_self: Option<String>,
/// Function arguments
args: Vec<Field>,
/// Return type
ret: Option<Type>,
/// Where bounds
bounds: Vec<Bound>,
/// Body contents
body: Option<Vec<Body>>,
}
/// Defines a code block. This is used to define a function body.
#[derive(Debug, Clone)]
pub struct Block {
before: Option<String>,
after: Option<String>,
body: Vec<Body>,
}
#[derive(Debug, Clone)]
enum Body {
String(String),
Block(Block),
}
#[derive(Debug, Clone)]
struct Docs {
docs: String,
}
/// Configures how a scope is formatted.
#[derive(Debug)]
pub struct Formatter<'a> {
/// Write destination
dst: &'a mut String,
/// Number of spaces to start a new line with
spaces: usize,
/// Number of spaces per indentiation
indent: usize,
}
const DEFAULT_INDENT: usize = 4;
// ===== impl Scope =====
impl Scope {
/// Returns a new scope
pub fn new() -> Self {
Scope {
docs: None,
imports: OrderMap::new(),
items: vec![],
}
}
/// Import a type into the scope.
///
/// This results in a new `use` statement bein added to the beginning of the
/// scope.
pub fn import(&mut self, path: &str, ty: &str) -> &mut Import {
self.imports.entry(path.to_string())
.or_insert(OrderMap::new())
.entry(ty.to_string())
.or_insert_with(|| Import::new(path, ty))
}
/// Push a new module definition, returning a mutable reference to it.
pub fn new_module(&mut self, name: &str) -> &mut Module {
self.push_module(Module::new(name));
match *self.items.last_mut().unwrap() {
Item::Module(ref mut v) => v,
_ => unreachable!(),
}
}
/// Push a module definition.
pub fn push_module(&mut self, item: Module) -> &mut Self {
self.items.push(Item::Module(item));
self
}
/// Push a new struct definition, returning a mutable reference to it.
pub fn new_struct(&mut self, name: &str) -> &mut Struct {
self.push_struct(Struct::new(name));
match *self.items.last_mut().unwrap() {
Item::Struct(ref mut v) => v,
_ => unreachable!(),
}
}
/// Push a struct definition
pub fn push_struct(&mut self, item: Struct) -> &mut Self {
self.items.push(Item::Struct(item));
self
}
/// Push a new trait definition, returning a mutable reference to it.
pub fn new_trait(&mut self, name: &str) -> &mut Trait {
self.push_trait(Trait::new(name));
match *self.items.last_mut().unwrap() {
Item::Trait(ref mut v) => v,
_ => unreachable!(),
}
}
/// Push a trait definition
pub fn push_trait(&mut self, item: Trait) -> &mut Self {
self.items.push(Item::Trait(item));
self
}
/// Push a new struct definition, returning a mutable reference to it.
pub fn new_enum(&mut self, name: &str) -> &mut Enum {
self.push_enum(Enum::new(name));
match *self.items.last_mut().unwrap() {
Item::Enum(ref mut v) => v,
_ => unreachable!(),
}
}
/// Push a structure definition
pub fn push_enum(&mut self, item: Enum) -> &mut Self {
self.items.push(Item::Enum(item));
self
}
/// Push a new `impl` block, returning a mutable reference to it.
pub fn new_impl(&mut self, target: &str) -> &mut Impl {
self.push_impl(Impl::new(target));
match *self.items.last_mut().unwrap() {
Item::Impl(ref mut v) => v,
_ => unreachable!(),
}
}
/// Push an `impl` block.
pub fn push_impl(&mut self, item: Impl) -> &mut Self {
self.items.push(Item::Impl(item));
self
}
/// Push a raw string to the scope.
///
/// This string will be included verbatim in the formatted string.
pub fn raw(&mut self, val: &str) -> &mut Self {
self.items.push(Item::Raw(val.to_string()));
self
}
/// Return a string representation of the scope.
pub fn to_string(&self) -> String {
let mut ret = String::new();
self.fmt(&mut Formatter::new(&mut ret)).unwrap();
// Remove the trailing newline
if ret.as_bytes().last() == Some(&b'\n') {
ret.pop();
}
ret
}
/// Formats the scope using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
self.fmt_imports(fmt)?;
if !self.imports.is_empty() {
write!(fmt, "\n")?;
}
for (i, item) in self.items.iter().enumerate() {
if i != 0 {
write!(fmt, "\n")?;
}
match *item {
Item::Module(ref v) => v.fmt(fmt)?,
Item::Struct(ref v) => v.fmt(fmt)?,
Item::Trait(ref v) => v.fmt(fmt)?,
Item::Enum(ref v) => v.fmt(fmt)?,
Item::Impl(ref v) => v.fmt(fmt)?,
Item::Raw(ref v) => {
write!(fmt, "{}\n", v)?;
}
}
}
Ok(())
}
fn fmt_imports(&self, fmt: &mut Formatter) -> fmt::Result {
// First, collect all visibilities
let mut visibilities = vec![];
for (_, imports) in &self.imports {
for (_, import) in imports {
if !visibilities.contains(&import.vis) {
visibilities.push(import.vis.clone());
}
}
}
let mut tys = vec![];
// Loop over all visibilities and format the associated imports
for vis in &visibilities {
for (path, imports) in &self.imports {
tys.clear();
for (ty, import) in imports {
if *vis == import.vis {
tys.push(ty);
}
}
if !tys.is_empty() {
if let Some(ref vis) = *vis {
write!(fmt, "{} ", vis)?;
}
write!(fmt, "use {}::", path)?;
if tys.len() > 1 {
write!(fmt, "{{")?;
for (i, ty) in tys.iter().enumerate() {
if i != 0 { write!(fmt, ", ")?; }
write!(fmt, "{}", ty)?;
}
write!(fmt, "}};\n")?;
} else if tys.len() == 1 {
write!(fmt, "{};\n", tys[0])?;
}
}
}
}
Ok(())
}
}
// ===== impl Module =====
impl Module {
/// Return a new, blank module
pub fn new(name: &str) -> Self {
Module {
name: name.to_string(),
vis: None,
docs: None,
scope: Scope::new(),
}
}
/// Returns a mutable reference to the module's scope.
pub fn scope(&mut self) -> &mut Scope {
&mut self.scope
}
/// Set the module visibility.
pub fn vis(&mut self, vis: &str) -> &mut Self {
self.vis = Some(vis.to_string());
self
}
/// Import a type into the module's scope.
///
/// This results in a new `use` statement bein added to the beginning of the
/// module.
pub fn import(&mut self, path: &str, ty: &str) -> &mut Self {
self.scope.import(path, ty);
self
}
/// Push a new module definition, returning a mutable reference to it.
pub fn new_module(&mut self, name: &str) -> &mut Module {
self.scope.new_module(name)
}
/// Push a module definition
pub fn push_module(&mut self, item: Module) -> &mut Self {
self.scope.push_module(item);
self
}
/// Push a new struct definition, returning a mutable reference to it.
pub fn new_struct(&mut self, name: &str) -> &mut Struct {
self.scope.new_struct(name)
}
/// Push a structure definition
pub fn push_struct(&mut self, item: Struct) -> &mut Self {
self.scope.push_struct(item);
self
}
/// Push a new enum definition, returning a mutable reference to it.
pub fn new_enum(&mut self, name: &str) -> &mut Enum {
self.scope.new_enum(name)
}
/// Push an enum definition
pub fn push_enum(&mut self, item: Enum) -> &mut Self {
self.scope.push_enum(item);
self
}
/// Push a new `impl` block, returning a mutable reference to it.
pub fn new_impl(&mut self, target: &str) -> &mut Impl {
self.scope.new_impl(target)
}
/// Push an `impl` block.
pub fn push_impl(&mut self, item: Impl) -> &mut Self {
self.scope.push_impl(item);
self
}
/// Formats the module using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
if let Some(ref vis) = self.vis {
write!(fmt, "{} ", vis)?;
}
write!(fmt, "mod {}", self.name)?;
fmt.block(|fmt| {
self.scope.fmt(fmt)
})
}
}
// ===== impl Struct =====
impl Struct {
/// Return a structure definition with the provided name
pub fn new(name: &str) -> Self {
Struct {
type_def: TypeDef::new(name),
fields: Fields::Empty,
}
}
/// Returns a reference to the type
pub fn ty(&self) -> &Type {
&self.type_def.ty
}
/// Set the structure visibility.
pub fn vis(&mut self, vis: &str) -> &mut Self {
self.type_def.vis(vis);
self
}
/// Add a generic to the struct.
pub fn generic(&mut self, name: &str) -> &mut Self {
self.type_def.ty.generic(name);
self
}
/// Add a `where` bound to the struct.
pub fn bound<T>(&mut self, name: &str, ty: T) -> &mut Self
where T: Into<Type>,
{
self.type_def.bound(name, ty);
self
}
/// Set the structure documentation.
pub fn doc(&mut self, docs: &str) -> &mut Self {
self.type_def.doc(docs);
self
}
/// Add a new type that the struct should derive.
pub fn derive(&mut self, name: &str) -> &mut Self {
self.type_def.derive(name);
self
}
/// Push a named field to the struct.
///
/// A struct can either set named fields with this function or tuple fields
/// with `push_tuple_field`, but not both.
pub fn push_field(&mut self, field: Field) -> &mut Self
{
self.fields.push_named(field);
self
}
/// Add a named field to the struct.
///
/// A struct can either set named fields with this function or tuple fields
/// with `tuple_field`, but not both.
pub fn field<T>(&mut self, name: &str, ty: T) -> &mut Self
where T: Into<Type>,
{
self.fields.named(name, ty);
self
}
/// Add a tuple field to the struct.
///
/// A struct can either set tuple fields with this function or named fields
/// with `field`, but not both.
pub fn tuple_field<T>(&mut self, ty: T) -> &mut Self
where T: Into<Type>,
{
self.fields.tuple(ty);
self
}
/// Formats the struct using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
self.type_def.fmt_head("struct", &[], fmt)?;
self.fields.fmt(fmt)?;
match self.fields {
Fields::Empty => {
write!(fmt, ";\n")?;
}
Fields::Tuple(..) => {
write!(fmt, ";\n")?;
}
_ => {}
}
Ok(())
}
}
// ===== impl Trait =====
impl Trait {
/// Return a trait definition with the provided name
pub fn new(name: &str) -> Self {
Trait {
type_def: TypeDef::new(name),
parents: vec![],
associated_tys: vec![],
fns: vec![],
}
}
/// Returns a reference to the type
pub fn ty(&self) -> &Type {
&self.type_def.ty
}
/// Set the trait visibility.
pub fn vis(&mut self, vis: &str) -> &mut Self {
self.type_def.vis(vis);
self
}
/// Add a generic to the trait
pub fn generic(&mut self, name: &str) -> &mut Self {
self.type_def.ty.generic(name);
self
}
/// Add a `where` bound to the trait.
pub fn bound<T>(&mut self, name: &str, ty: T) -> &mut Self
where T: Into<Type>,
{
self.type_def.bound(name, ty);
self
}
/// Add a parent trait.
pub fn parent<T>(&mut self, ty: T) -> &mut Self
where T: Into<Type>,
{
self.parents.push(ty.into());
self
}
/// Set the trait documentation.
pub fn doc(&mut self, docs: &str) -> &mut Self {
self.type_def.doc(docs);
self
}
/// Add an associated type. Returns a mutable reference to the new
/// associated type for futher configuration.
pub fn associated_type(&mut self, name: &str) -> &mut AssociatedType {
self.associated_tys.push(AssociatedType(Bound {
name: name.to_string(),
bound: vec![],
}));
self.associated_tys.last_mut().unwrap()
}
/// Push a new function definition, returning a mutable reference to it.
pub fn new_fn(&mut self, name: &str) -> &mut Function {
let mut func = Function::new(name);
func.body = None;
self.push_fn(func);
self.fns.last_mut().unwrap()
}
/// Push a function definition.
pub fn push_fn(&mut self, item: Function) -> &mut Self {
self.fns.push(item);
self
}
/// Formats the scope using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
self.type_def.fmt_head("trait", &self.parents, fmt)?;
fmt.block(|fmt| {
let assoc = &self.associated_tys;
// format associated types
if !assoc.is_empty() {
for ty in assoc {
let ty = &ty.0;
write!(fmt, "type {}", ty.name)?;
if !ty.bound.is_empty() {
write!(fmt, ": ")?;
fmt_bound_rhs(&ty.bound, fmt)?;
}
write!(fmt, ";\n")?;
}
}
for (i, func) in self.fns.iter().enumerate() {
if i != 0 || !assoc.is_empty() { write!(fmt, "\n")?; }
func.fmt(true, fmt)?;
}
Ok(())
})
}
}
// ===== impl Enum =====
impl Enum {
/// Return a enum definition with the provided name.
pub fn new(name: &str) -> Self {
Enum {
type_def: TypeDef::new(name),
variants: vec![],
}
}
/// Returns a reference to the type.
pub fn ty(&self) -> &Type {
&self.type_def.ty
}
/// Set the enum visibility.
pub fn vis(&mut self, vis: &str) -> &mut Self {
self.type_def.vis(vis);
self
}
/// Add a generic to the enum.
pub fn generic(&mut self, name: &str) -> &mut Self {
self.type_def.ty.generic(name);
self
}
/// Add a `where` bound to the enum.
pub fn bound<T>(&mut self, name: &str, ty: T) -> &mut Self
where T: Into<Type>,
{
self.type_def.bound(name, ty);
self
}
/// Set the enum documentation.
pub fn doc(&mut self, docs: &str) -> &mut Self {
self.type_def.doc(docs);
self
}
/// Add a new type that the struct should derive.
pub fn derive(&mut self, name: &str) -> &mut Self {
self.type_def.derive(name);
self
}
/// Push a variant to the enum, returning a mutable reference to it.
pub fn new_variant(&mut self, name: &str) -> &mut Variant {
self.push_variant(Variant::new(name));
self.variants.last_mut().unwrap()
}
/// Push a variant to the enum.
pub fn push_variant(&mut self, item: Variant) -> &mut Self {
self.variants.push(item);
self
}
/// Formats the enum using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
self.type_def.fmt_head("enum", &[], fmt)?;
fmt.block(|fmt| {
for variant in &self.variants {
variant.fmt(fmt)?;
}
Ok(())
})
}
}
// ===== impl Variant =====
impl Variant {
/// Return a new enum variant with the given name.
pub fn new(name: &str) -> Self {
Variant {
name: name.to_string(),
fields: Fields::Empty,
}
}
/// Add a named field to the variant.
pub fn named<T>(&mut self, name: &str, ty: T) -> &mut Self
where T: Into<Type>,
{
self.fields.named(name, ty);
self
}
/// Add a tuple field to the variant.
pub fn tuple(&mut self, ty: &str) -> &mut Self {
self.fields.tuple(ty);
self
}
/// Formats the variant using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
write!(fmt, "{}", self.name)?;
self.fields.fmt(fmt)?;
write!(fmt, ",\n")?;
Ok(())
}
}
// ===== impl Type =====
impl Type {
/// Return a new type with the given name.
pub fn new(name: &str) -> Self {
Type {
name: name.to_string(),
generics: vec![],
}
}
/// Add a generic to the type.
pub fn generic<T>(&mut self, ty: T) -> &mut Self
where T: Into<Type>,
{
// Make sure that the name doesn't already include generics
assert!(!self.name.contains("<"), "type name already includes generics");
self.generics.push(ty.into());
self
}
/// Rewrite the `Type` with the provided path
///
/// TODO: Is this needed?
pub fn path(&self, path: &str) -> Type {
// TODO: This isn't really correct
assert!(!self.name.contains("::"));
let mut name = path.to_string();
name.push_str("::");
name.push_str(&self.name);
Type {
name,
generics: self.generics.clone(),
}
}
/// Formats the struct using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
write!(fmt, "{}", self.name)?;
Type::fmt_slice(&self.generics, fmt)
}
fn fmt_slice(generics: &[Type], fmt: &mut Formatter) -> fmt::Result {
if !generics.is_empty() {
write!(fmt, "<")?;
for (i, ty) in generics.iter().enumerate() {
if i != 0 { write!(fmt, ", ")? }
ty.fmt(fmt)?;
}
write!(fmt, ">")?;
}
Ok(())
}
}
impl<'a> From<&'a str> for Type {
fn from(src: &'a str) -> Self {
Type::new(src)
}
}
impl From<String> for Type {
fn from(src: String) -> Self {
Type {
name: src,
generics: vec![],
}
}
}
impl<'a> From<&'a String> for Type {
fn from(src: &'a String) -> Self {
Type::new(src)
}
}
impl<'a> From<&'a Type> for Type {
fn from(src: &'a Type) -> Self {
src.clone()
}
}
// ===== impl TypeDef =====
impl TypeDef {
/// Return a structure definition with the provided name
fn new(name: &str) -> Self {
TypeDef {
ty: Type::new(name),
vis: None,
docs: None,
derive: vec![],
bounds: vec![],
}
}
fn vis(&mut self, vis: &str) {
self.vis = Some(vis.to_string());
}
fn bound<T>(&mut self, name: &str, ty: T)
where T: Into<Type>,
{
self.bounds.push(Bound {
name: name.to_string(),
bound: vec![ty.into()],
});
}
fn doc(&mut self, docs: &str) {
self.docs = Some(Docs::new(docs));
}
fn derive(&mut self, name: &str) {
self.derive.push(name.to_string());
}
fn fmt_head(&self,
keyword: &str,
parents: &[Type],
fmt: &mut Formatter) -> fmt::Result
{
if let Some(ref docs) = self.docs {
docs.fmt(fmt)?;
}
self.fmt_derive(fmt)?;
if let Some(ref vis) = self.vis {
write!(fmt, "{} ", vis)?;
}