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
use std::fmt::{self, Write};
use crate::field::Field;
use crate::fields::Fields;
use crate::formatter::Formatter;
use crate::type_def::TypeDef;
use crate::r#type::Type;
/// Defines a struct.
#[derive(Debug, Clone)]
pub struct Struct {
type_def: TypeDef,
/// Struct fields
fields: Fields,
}
impl Struct {
/// Return a structure definition with the provided name
pub fn new(name: &str) -> Self {
Self {
type_def: TypeDef::new(name),
fields: Fields::Empty,
}
}
/// Returns a reference to the type
pub const 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
}
/// Specify lint attribute to supress a warning or error.
pub fn allow(&mut self, allow: &str) -> &mut Self {
self.type_def.allow(allow);
self
}
/// Specify representation.
pub fn repr(&mut self, repr: &str) -> &mut Self {
self.type_def.repr(repr);
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 => {
writeln!(fmt, ";")?;
}
Fields::Tuple(..) => {
writeln!(fmt, ";")?;
}
_ => {}
}
Ok(())
}
}