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
use std::collections::{BTreeMap, BTreeSet};
use std::iter;
use anyhow::{bail, Result};
use itertools::Itertools;
use quote::ToTokens;
pub struct Ir {
pub items: BTreeMap<String, Item>,
pub generics: BTreeMap<String, BTreeSet<String>>,
}
#[derive(Debug)]
pub enum Item {
Struct(Struct),
Enum(Enum),
Abstract,
}
impl Item {
pub fn fields<'a>(&'a self) -> Box<dyn Iterator<Item = &Field> + 'a> {
match self {
Item::Struct(s) => Box::new(s.fields.iter()),
Item::Enum(e) => Box::new(e.variants.iter().flat_map(|v| &v.fields)),
Item::Abstract => Box::new(iter::empty()),
}
}
pub fn generics(&self) -> &[ItemGeneric] {
match self {
Item::Struct(s) => &s.generics,
Item::Enum(e) => &e.generics,
Item::Abstract => &[],
}
}
}
#[derive(Debug)]
pub struct Struct {
pub fields: Vec<Field>,
pub generics: Vec<ItemGeneric>,
}
#[derive(Debug)]
pub struct Enum {
pub variants: Vec<Variant>,
pub generics: Vec<ItemGeneric>,
}
#[derive(Debug)]
pub struct Variant {
pub name: String,
pub fields: Vec<Field>,
}
#[derive(Debug)]
pub struct Field {
pub name: Option<String>,
pub ty: Type,
}
#[derive(Debug)]
pub struct ItemGeneric {
pub name: String,
pub bounds: Vec<String>,
}
#[derive(Debug)]
pub enum Type {
Primitive,
Abstract(String),
Option(Box<Type>),
Vec(Box<Type>),
Box(Box<Type>),
Local(String),
}
pub(crate) fn analyze(syn_items: &[syn::DeriveInput]) -> Result<Ir> {
let mut items = BTreeMap::new();
for syn_item in syn_items {
let name = syn_item.ident.to_string();
let generics = analyze_generics(&syn_item.generics)?;
let item = match &syn_item.data {
syn::Data::Struct(s) => Item::Struct(Struct {
fields: analyze_fields(&s.fields)?,
generics,
}),
syn::Data::Enum(e) => {
let mut variants = vec![];
for v in &e.variants {
variants.push(Variant {
name: v.ident.to_string(),
fields: analyze_fields(&v.fields)?,
});
}
Item::Enum(Enum { variants, generics })
}
syn::Data::Union(_) => bail!("Unable to analyze union: {}", syn_item.ident),
};
for field in item.fields() {
if let Type::Abstract(ty) = &field.ty {
items.insert(ty.clone(), Item::Abstract);
}
}
items.insert(name, item);
}
let mut generics = BTreeMap::<_, BTreeSet<String>>::new();
for item in items.values() {
for ig in item.generics() {
generics
.entry(ig.name.clone())
.or_default()
.extend(ig.bounds.clone());
}
}
for item in items.values() {
validate_fields(&items, item.fields())?
}
Ok(Ir { items, generics })
}
fn validate_fields<'a, I>(items: &BTreeMap<String, Item>, fields: I) -> Result<()>
where
I: IntoIterator<Item = &'a Field>,
{
for f in fields {
match &f.ty {
Type::Local(s) if !items.contains_key(s) => {
bail!(
"Unable to analyze non built-in type that is not defined in input: {}",
s
);
}
_ => (),
}
}
Ok(())
}
fn analyze_fields(fields: &syn::Fields) -> Result<Vec<Field>> {
fields
.iter()
.map(|f| {
Ok(Field {
name: f.ident.as_ref().map(|id| id.to_string()),
ty: analyze_type(&f.ty)?,
})
})
.collect()
}
fn analyze_generics(generics: &syn::Generics) -> Result<Vec<ItemGeneric>> {
let mut out = vec![];
for g in generics.params.iter() {
match g {
syn::GenericParam::Type(syn::TypeParam { ident, bounds, .. }) => {
let name = ident.to_string();
let bounds = analyze_generic_bounds(bounds)?;
if name.ends_with('2') {
bail!("Generic parameters whose name ends in '2' conflict with folder's naming scheme: {}", name);
}
out.push(ItemGeneric { name, bounds });
}
_ => {
bail!(
"Unable to analyze non-type generic parameter: {}",
g.to_token_stream()
)
}
}
}
Ok(out)
}
fn analyze_generic_bounds<'a, I>(bounds: I) -> Result<Vec<String>>
where
I: IntoIterator<Item = &'a syn::TypeParamBound>,
{
let mut out = vec![];
for b in bounds {
match b {
syn::TypeParamBound::Trait(t) if t.path.segments.len() != 1 => {
bail!(
"Unable to analyze trait bound with more than one path segment: {}",
b.to_token_stream()
)
}
syn::TypeParamBound::Trait(t) => out.push(t.path.segments[0].ident.to_string()),
_ => bail!("Unable to analyze non-trait bound: {}", b.to_token_stream()),
}
}
Ok(out)
}
fn analyze_type(ty: &syn::Type) -> Result<Type> {
match ty {
syn::Type::Path(syn::TypePath { qself: None, path }) => {
match path.segments.len() {
2 => {
let name = path.segments.iter().map(|s| s.ident.to_string()).join("::");
Ok(Type::Abstract(name))
}
1 => {
let segment = path.segments.last().unwrap();
let segment_name = segment.ident.to_string();
let container = |construct_ty: fn(Box<Type>) -> Type| {
match &segment.arguments {
syn::PathArguments::AngleBracketed(args) if args.args.len() == 1 => {
match args.args.last().unwrap() {
syn::GenericArgument::Type(ty) => {
let inner = Box::new(analyze_type(ty)?);
Ok(construct_ty(inner))
}
_ => bail!("Container type argument is not a basic (i.e., non-lifetime, non-constraint) type argument: {}", ty.into_token_stream()),
}
}
syn::PathArguments::AngleBracketed(_) => bail!(
"Container type does not have exactly one type argument: {}",
ty.into_token_stream()
),
syn::PathArguments::Parenthesized(_) => bail!(
"Container type has unexpected parenthesized type arguments: {}",
ty.into_token_stream()
),
syn::PathArguments::None => bail!(
"Container type is missing type argument: {}",
ty.into_token_stream()
),
}
};
match &*segment_name {
"bool" | "usize" | "u64" | "char" | "String" | "PathBuf"
| "DateTimeField" => match segment.arguments {
syn::PathArguments::None => Ok(Type::Primitive),
_ => bail!(
"Primitive type had unexpected arguments: {}",
ty.into_token_stream()
),
},
"Vec" => container(Type::Vec),
"Option" => container(Type::Option),
"Box" => container(Type::Box),
_ => Ok(Type::Local(segment_name)),
}
}
_ => {
bail!(
"Unable to analyze type path with more than two components: '{}'",
path.into_token_stream()
)
}
}
}
_ => bail!(
"Unable to analyze non-struct, non-enum type: {}",
ty.into_token_stream()
),
}
}