forked from bincode-org/virtue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen_enum.rs
236 lines (210 loc) · 6.37 KB
/
gen_enum.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
use super::{Impl, ImplFor, Parent, StreamBuilder, StringOrIdent};
use crate::parse::Visibility;
use crate::prelude::{Delimiter, Ident, Span};
use crate::Result;
/// Builder to generate an `enum <Name> { <value> { ... }, ... }`
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Fooz");
/// {
/// let mut enumgen = generator.generate_enum("Foo");
/// enumgen
/// .add_value("ZST")
/// .make_zst();
/// enumgen
/// .add_value("Named")
/// .add_field("bar", "u16")
/// .add_field("baz", "String");
/// enumgen
/// .add_value("Unnamed")
/// .add_field("", "u16")
/// .add_field("baz", "String")
/// .make_tuple();
/// }
/// # generator.assert_eq("enum Foo { ZST , Named { bar : u16 , baz : String , } , Unnamed (u16 , String ,) , }");
/// # Ok::<_, virtue::Error>(())
/// ```
///
/// Generates:
/// ```
/// enum Foo {
/// ZST,
/// Named {
/// bar: u16,
/// baz: String,
/// },
/// Unnamed(u16, String),
/// };
/// ```
pub struct GenEnum<'a, P: Parent> {
parent: &'a mut P,
name: Ident,
visibility: Visibility,
values: Vec<EnumValue>,
additional: Vec<StreamBuilder>,
}
impl<'a, P: Parent> GenEnum<'a, P> {
pub(crate) fn new(parent: &'a mut P, name: impl Into<String>) -> Self {
Self {
parent,
name: Ident::new(name.into().as_str(), Span::call_site()),
visibility: Visibility::Default,
values: Vec::new(),
additional: Vec::new(),
}
}
/// Make the enum `pub`. By default the struct will have no visibility modifier and will only be visible in the current scope.
pub fn make_pub(&mut self) -> &mut Self {
self.visibility = Visibility::Pub;
self
}
/// Add an enum value
///
/// Returns a builder for the value that's similar to GenStruct
pub fn add_value(&mut self, name: impl Into<String>) -> &mut EnumValue {
self.values.push(EnumValue::new(name));
self.values.last_mut().unwrap()
}
/// Add an `impl <name> for <enum>`
pub fn impl_for(&mut self, name: impl Into<StringOrIdent>) -> ImplFor<Self> {
ImplFor::new(self, name.into(), None)
}
/// Generate an `impl <name>` implementation. See [`Impl`] for more information.
pub fn r#impl(&mut self) -> Impl<Self> {
Impl::with_parent_name(self)
}
/// Generate an `impl <name>` implementation. See [`Impl`] for more information.
///
/// Alias for [`impl`] which doesn't need a `r#` prefix.
///
/// [`impl`]: #method.impl
pub fn generate_impl(&mut self) -> Impl<Self> {
Impl::with_parent_name(self)
}
}
impl<'a, P: Parent> Parent for GenEnum<'a, P> {
fn append(&mut self, builder: StreamBuilder) {
self.additional.push(builder);
}
fn name(&self) -> &Ident {
&self.name
}
fn generics(&self) -> Option<&crate::parse::Generics> {
None
}
fn generic_constraints(&self) -> Option<&crate::parse::GenericConstraints> {
None
}
}
impl<'a, P: Parent> Drop for GenEnum<'a, P> {
fn drop(&mut self) {
let mut builder = StreamBuilder::new();
if self.visibility == Visibility::Pub {
builder.ident_str("pub");
}
builder
.ident_str("enum")
.ident(self.name.clone())
.group(Delimiter::Brace, |b| {
for value in &self.values {
build_value(b, value)?;
}
Ok(())
})
.expect("Could not build enum");
for additional in std::mem::take(&mut self.additional) {
builder.append(additional);
}
self.parent.append(builder);
}
}
fn build_value(builder: &mut StreamBuilder, value: &EnumValue) -> Result {
builder.ident(value.name.clone());
match value.value_type {
ValueType::Named => builder.group(Delimiter::Brace, |b| {
for field in &value.fields {
if field.vis == Visibility::Pub {
b.ident_str("pub");
}
b.ident_str(&field.name)
.punct(':')
.push_parsed(&field.ty)?
.punct(',');
}
Ok(())
})?,
ValueType::Unnamed => builder.group(Delimiter::Parenthesis, |b| {
for field in &value.fields {
if field.vis == Visibility::Pub {
b.ident_str("pub");
}
b.push_parsed(&field.ty)?.punct(',');
}
Ok(())
})?,
ValueType::Zst => builder,
};
builder.punct(',');
Ok(())
}
pub struct EnumValue {
name: Ident,
fields: Vec<EnumField>,
value_type: ValueType,
}
impl EnumValue {
fn new(name: impl Into<String>) -> Self {
Self {
name: Ident::new(name.into().as_str(), Span::call_site()),
fields: Vec::new(),
value_type: ValueType::Named,
}
}
/// Make the struct a zero-sized type (no fields)
///
/// Any fields will be ignored
pub fn make_zst(&mut self) -> &mut Self {
self.value_type = ValueType::Zst;
self
}
/// Make the struct fields unnamed
///
/// The names of any field will be ignored
pub fn make_tuple(&mut self) -> &mut Self {
self.value_type = ValueType::Unnamed;
self
}
/// Add a *private* field to the struct. For adding a public field, see `add_pub_field`
///
/// Names are ignored when the Struct's fields are unnamed
pub fn add_field(&mut self, name: impl Into<String>, ty: impl Into<String>) -> &mut Self {
self.fields.push(EnumField {
name: name.into(),
vis: Visibility::Default,
ty: ty.into(),
});
self
}
/// Add a *public* field to the struct. For adding a public field, see `add_field`
///
/// Names are ignored when the Struct's fields are unnamed
pub fn add_pub_field(&mut self, name: impl Into<String>, ty: impl Into<String>) -> &mut Self {
self.fields.push(EnumField {
name: name.into(),
vis: Visibility::Pub,
ty: ty.into(),
});
self
}
}
struct EnumField {
name: String,
vis: Visibility,
ty: String,
}
enum ValueType {
Named,
Unnamed,
Zst,
}