neli_proc_macros/
shared.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
use std::{any::type_name, collections::HashMap};

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, ToTokens};
use syn::{
    parse,
    parse::Parse,
    parse_str,
    punctuated::Punctuated,
    token::{Add, Colon2},
    Attribute, Expr, Fields, FieldsNamed, FieldsUnnamed, GenericParam, Generics, Ident, Index,
    ItemStruct, LifetimeDef, Lit, Meta, MetaNameValue, NestedMeta, Path, PathArguments,
    PathSegment, Token, TraitBound, TraitBoundModifier, Type, TypeParam, TypeParamBound, Variant,
};

/// Represents a field as either an identifier or an index.
pub enum FieldRepr {
    Index(Index),
    Ident(Ident),
}

impl ToTokens for FieldRepr {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        match self {
            FieldRepr::Index(i) => i.to_tokens(tokens),
            FieldRepr::Ident(i) => i.to_tokens(tokens),
        }
    }
}

/// Represents the field name, type, and all attributes associated
/// with this field.
pub struct FieldInfo {
    field_name: FieldRepr,
    field_type: Type,
    field_attrs: Vec<Attribute>,
}

impl FieldInfo {
    /// Convert field info to a tuple.
    fn into_tuple(self) -> (FieldRepr, Type, Vec<Attribute>) {
        (self.field_name, self.field_type, self.field_attrs)
    }

    /// Convert a vector of [`FieldInfo`]s to a tuple of vectors
    /// each containing name, type, or attributes.
    pub fn to_vecs<I>(v: I) -> (Vec<FieldRepr>, Vec<Type>, Vec<Vec<Attribute>>)
    where
        I: Iterator<Item = Self>,
    {
        v.into_iter().fold(
            (Vec::new(), Vec::new(), Vec::new()),
            |(mut names, mut types, mut attrs), info| {
                let (name, ty, attr) = info.into_tuple();
                names.push(name);
                types.push(ty);
                attrs.push(attr);
                (names, types, attrs)
            },
        )
    }
}

/// Necessary information for a given struct to generate trait
/// implementations.
pub struct StructInfo {
    struct_name: Ident,
    generics: Generics,
    generics_without_bounds: Generics,
    field_info: Vec<FieldInfo>,
    padded: bool,
}

type StructInfoTuple = (
    Ident,
    Generics,
    Generics,
    Vec<FieldRepr>,
    Vec<Type>,
    Vec<Vec<Attribute>>,
    bool,
);

impl StructInfo {
    /// Extract the necessary information from an
    /// [`ItemStruct`][syn::ItemStruct] data structure.
    pub fn from_item_struct(
        i: ItemStruct,
        trait_name: Option<&str>,
        trait_bound_path: &str,
        uses_self: bool,
    ) -> Self {
        let (mut generics, generics_without_bounds) = process_impl_generics(i.generics, trait_name);
        let trait_bounds = process_trait_bounds(&i.attrs, trait_bound_path);
        override_trait_bounds_on_generics(&mut generics, &trait_bounds);
        let field_info = match i.fields {
            Fields::Named(fields_named) => generate_named_fields(fields_named),
            Fields::Unnamed(fields_unnamed) => generate_unnamed_fields(fields_unnamed, uses_self),
            Fields::Unit => Vec::new(),
        };
        let padded = process_padding(&i.attrs);

        StructInfo {
            struct_name: i.ident,
            generics,
            generics_without_bounds,
            field_info,
            padded,
        }
    }

    /// Remove the last field from the record.
    pub fn pop_field(&mut self) {
        let _ = self.field_info.pop();
    }

    /// Convert all necessary struct information into a tuple of
    /// values.
    pub fn into_tuple(mut self) -> StructInfoTuple {
        let (field_names, field_types, field_attrs) = self.field_info();
        (
            self.struct_name,
            self.generics,
            self.generics_without_bounds,
            field_names,
            field_types,
            field_attrs,
            self.padded,
        )
    }

    /// Convert all field information into a tuple.
    fn field_info(&mut self) -> (Vec<FieldRepr>, Vec<Type>, Vec<Vec<Attribute>>) {
        FieldInfo::to_vecs(self.field_info.drain(..))
    }
}

/// Convert a list of identifiers into a path where the path segments
/// are added in the order that they appear in the list.
fn path_from_idents(idents: &[&str]) -> Path {
    Path {
        leading_colon: None,
        segments: idents
            .iter()
            .map(|ident| PathSegment {
                ident: Ident::new(ident, Span::call_site()),
                arguments: PathArguments::None,
            })
            .collect::<Punctuated<PathSegment, Colon2>>(),
    }
}

/// Process all type parameters in the type parameter definition for
/// an `impl` block. Optionally add a trait bound for all type parameters
/// if `required_trait` is `Some(_)`.
///
/// The first return value in the tuple is the list of type parameters
/// with trait bounds added. The second argument is a list of type
/// parameters without trait bounds to be passed into the type parameter
/// list for a struct.
///
/// # Example:
/// ## impl block
///
/// ```no_compile
/// trait MyTrait {}
///
/// impl<T, P> MyStruct<T, P> {
///     fn nothing() {}
/// }
/// ```
///
/// ## Method call
/// `neli_proc_macros::process_impl_generics(generics, Some("MyTrait"))`
///
/// ## Result
/// ```no_compile
/// (<T: MyTrait, P: MyTrait>, <T, P>)
/// ```
///
/// or rather:
///
/// ```no_compile
/// impl<T: MyTrait, P: MyTrait> MyStruct<T, P> {
///     fn nothing() {}
/// }
/// ```
pub fn process_impl_generics(
    mut generics: Generics,
    required_trait: Option<&str>,
) -> (Generics, Generics) {
    if let Some(rt) = required_trait {
        for gen in generics.params.iter_mut() {
            if let GenericParam::Type(param) = gen {
                param.colon_token = Some(Token![:](Span::call_site()));
                param.bounds.push(TypeParamBound::Trait(TraitBound {
                    paren_token: None,
                    modifier: TraitBoundModifier::None,
                    lifetimes: None,
                    path: path_from_idents(&["neli", rt]),
                }));
                param.eq_token = None;
                param.default = None;
            }
        }
    }

    let mut generics_without_bounds: Generics = generics.clone();
    for gen in generics_without_bounds.params.iter_mut() {
        if let GenericParam::Type(param) = gen {
            param.colon_token = None;
            param.bounds.clear();
            param.eq_token = None;
            param.default = None;
        }
    }

    (generics, generics_without_bounds)
}

/// Remove attributes that should not be carried over to an `impl`
/// definition and only belong in the data structure like documentation
/// attributes.
pub fn remove_bad_attrs(attrs: Vec<Attribute>) -> Vec<Attribute> {
    attrs
        .into_iter()
        .filter(|attr| {
            if let Ok(meta) = attr.parse_meta() {
                match meta {
                    Meta::NameValue(MetaNameValue { path, .. }) => {
                        !(path == parse_str::<Path>("doc").expect("doc should be valid path"))
                    }
                    _ => true,
                }
            } else {
                panic!("Could not parse provided attribute {}", attr.tokens,)
            }
        })
        .collect()
}

/// Generate a pattern and associated expression for each variant
/// in an enum.
fn generate_pat_and_expr<N, U>(
    enum_name: Ident,
    var_name: Ident,
    fields: Fields,
    generate_named_pat_and_expr: &N,
    generate_unnamed_pat_and_expr: &U,
    unit: &TokenStream2,
) -> TokenStream2
where
    N: Fn(Ident, Ident, FieldsNamed) -> TokenStream2,
    U: Fn(Ident, Ident, FieldsUnnamed) -> TokenStream2,
{
    match fields {
        Fields::Named(fields) => generate_named_pat_and_expr(enum_name, var_name, fields),
        Fields::Unnamed(fields) => generate_unnamed_pat_and_expr(enum_name, var_name, fields),
        Fields::Unit => quote! {
            #enum_name::#var_name => #unit,
        },
    }
}

/// Convert an enum variant into an arm of a match statement.
fn generate_arm<N, U>(
    attrs: Vec<Attribute>,
    enum_name: Ident,
    var_name: Ident,
    fields: Fields,
    generate_named_pat_and_expr: &N,
    generate_unnamed_pat_and_expr: &U,
    unit: &TokenStream2,
) -> TokenStream2
where
    N: Fn(Ident, Ident, FieldsNamed) -> TokenStream2,
    U: Fn(Ident, Ident, FieldsUnnamed) -> TokenStream2,
{
    let attrs = remove_bad_attrs(attrs)
        .into_iter()
        .map(|attr| {
            attr.parse_meta()
                .unwrap_or_else(|_| panic!("Failed to parse attribute {}", attr.tokens))
        })
        .collect::<Vec<_>>();
    let arm = generate_pat_and_expr(
        enum_name,
        var_name,
        fields,
        generate_named_pat_and_expr,
        generate_unnamed_pat_and_expr,
        unit,
    );
    quote! {
        #(
            #attrs
        )*
        #arm
    }
}

/// Generate all arms of a match statement.
pub fn generate_arms<N, U>(
    enum_name: Ident,
    variants: Vec<Variant>,
    generate_named_pat_and_expr: N,
    generate_unnamed_pat_and_expr: U,
    unit: TokenStream2,
) -> Vec<TokenStream2>
where
    N: Fn(Ident, Ident, FieldsNamed) -> TokenStream2,
    U: Fn(Ident, Ident, FieldsUnnamed) -> TokenStream2,
{
    variants
        .into_iter()
        .map(|var| {
            let variant_name = var.ident;
            generate_arm(
                var.attrs,
                enum_name.clone(),
                variant_name,
                var.fields,
                &generate_named_pat_and_expr,
                &generate_unnamed_pat_and_expr,
                &unit,
            )
        })
        .collect()
}

/// Generate a list of named fields in accordance with the struct.
pub fn generate_named_fields(fields: FieldsNamed) -> Vec<FieldInfo> {
    fields
        .named
        .into_iter()
        .fold(Vec::new(), |mut info, field| {
            info.push(FieldInfo {
                field_name: FieldRepr::Ident(field.ident.expect("Must be named")),
                field_type: field.ty,
                field_attrs: field.attrs,
            });
            info
        })
}

/// Generate unnamed fields as either indicies to be accessed using
/// `self` or placeholder variable names for match-style patterns.
pub fn generate_unnamed_fields(fields: FieldsUnnamed, uses_self: bool) -> Vec<FieldInfo> {
    fields
        .unnamed
        .into_iter()
        .enumerate()
        .fold(Vec::new(), |mut fields, (index, field)| {
            fields.push(FieldInfo {
                field_name: if uses_self {
                    FieldRepr::Index(Index {
                        index: index as u32,
                        span: Span::call_site(),
                    })
                } else {
                    FieldRepr::Ident(Ident::new(
                        &String::from((b'a' + index as u8) as char),
                        Span::call_site(),
                    ))
                },
                field_type: field.ty,
                field_attrs: field.attrs,
            });
            fields
        })
}

/// Returns [`true`] if the given attribute is present in the list.
fn attr_present(attrs: &[Attribute], attr_name: &str) -> bool {
    for attr in attrs {
        let meta = attr
            .parse_meta()
            .unwrap_or_else(|_| panic!("Failed to parse attribute {}", attr.tokens));
        if let Meta::List(list) = meta {
            if list.path == parse_str::<Path>("neli").expect("neli is valid path") {
                for nested in list.nested {
                    if let NestedMeta::Meta(Meta::Path(path)) = nested {
                        if path
                            == parse_str::<Path>(attr_name)
                                .unwrap_or_else(|_| panic!("{} should be valid path", attr_name))
                        {
                            return true;
                        }
                    }
                }
            }
        }
    }
    false
}

/// Process attributes to find all attributes with the name `attr_name`.
/// Return a [`Vec`] of [`Option`] types with the associated literal parsed
/// into type parameter `T`. `T` must allow parsing from a string to be
/// used with this method.
fn process_attr<T>(attrs: &[Attribute], attr_name: &str) -> Vec<Option<T>>
where
    T: Parse,
{
    let mut output = Vec::new();
    for attr in attrs {
        let meta = attr
            .parse_meta()
            .unwrap_or_else(|_| panic!("Failed to parse attribute {}", attr.tokens));
        if let Meta::List(list) = meta {
            if list.path == parse_str::<Path>("neli").expect("neli is valid path") {
                for nested in list.nested {
                    if let NestedMeta::Meta(Meta::NameValue(MetaNameValue {
                        path,
                        lit: Lit::Str(lit),
                        ..
                    })) = nested
                    {
                        if path
                            == parse_str::<Path>(attr_name)
                                .unwrap_or_else(|_| panic!("{} should be valid path", attr_name))
                        {
                            output.push(Some(parse_str::<T>(&lit.value()).unwrap_or_else(|_| {
                                panic!(
                                    "{} should be valid tokens of type {}",
                                    &lit.value(),
                                    type_name::<T>()
                                )
                            })));
                        }
                    } else if let NestedMeta::Meta(Meta::Path(path)) = nested {
                        if path
                            == parse_str::<Path>(attr_name)
                                .unwrap_or_else(|_| panic!("{} should be valid path", attr_name))
                        {
                            output.push(None);
                        }
                    }
                }
            }
        }
    }
    output
}

pub fn process_trait_bounds(attrs: &[Attribute], trait_bound_path: &str) -> Vec<TypeParam> {
    process_attr(attrs, trait_bound_path)
        .into_iter()
        .flatten()
        .collect()
}

/// Handles the attribute `#[neli(padding)]`.
pub fn process_padding(attrs: &[Attribute]) -> bool {
    attr_present(attrs, "padding")
}

/// Handles the attribute `#[neli(input)]` or `#[neli(input = "...")]`
/// when deriving [`FromBytes`][neli::FromBytes] implementations.
///
/// Returns:
/// * [`None`] if the attribute is not present
/// * [`Some(None)`] if the attribute is present and has no
/// associated expression
/// * [`Some(Some(_))`] if the attribute is present and
/// has an associated expression
pub fn process_input(attrs: &[Attribute]) -> Option<Option<Expr>> {
    let mut exprs = process_attr(attrs, "input");
    if exprs.len() > 1 {
        panic!("Only one input expression allowed for attribute #[neli(input = \"...\")]");
    } else {
        exprs.pop()
    }
}

/// Handles the attribute `#[neli(size = "...")]`
/// when deriving [`FromBytes`][neli::FromBytes] implementations.
///
/// Returns:
/// * [`None`] if the attribute is not present
/// associated expression
/// * [`Some(_)`] if the attribute is present and has an associated expression
pub fn process_size(attrs: &[Attribute]) -> Option<Expr> {
    let mut exprs = process_attr(attrs, "size");
    if exprs.len() > 1 {
        panic!("Only one input expression allowed for attribute #[neli(size = \"...\")]");
    } else {
        exprs
            .pop()
            .map(|opt| opt.expect("#[neli(size = \"...\")] must have associated expression"))
    }
}

/// If the first type parameter of a list of type parameters is a lifetime,
/// extract it for use in other parts of the procedural macro code.
///
/// # Example
/// `impl<'a, I, P>` would return `'a`.
pub fn process_lifetime(generics: &mut Generics) -> LifetimeDef {
    if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
        lt.clone()
    } else {
        let mut punc = Punctuated::new();
        let lt = parse::<LifetimeDef>(TokenStream::from(quote! {
            'lifetime
        }))
        .expect("'lifetime should be valid lifetime");
        punc.push(GenericParam::Lifetime(lt.clone()));
        punc.push_punct(Token![,](Span::call_site()));
        punc.extend(generics.params.iter().cloned());
        generics.params = punc;
        lt
    }
}

/// Allow overriding the trait bounds specified by the method
/// [`process_impl_generics`][process_impl_generics].
///
/// # Example
/// ```no_compile
/// use std::marker::PhantomData;
///
/// struct MyStruct<I, A>(PhantomData<I>, PhantomData<A>);
///
/// trait MyTrait {}
/// trait AnotherTrait {}
///
/// // Input
///
/// impl<I: MyTrait, A: MyTrait> MyStruct<I, A> {
///     fn nothing() {}
/// }
///
/// // Result
///
/// impl<I: AnotherTrait, A: MyTrait> MyStruct<I, A> {
///     fn nothing() {}
/// }
/// ```
fn override_trait_bounds_on_generics(generics: &mut Generics, trait_bound_overrides: &[TypeParam]) {
    let mut overrides = trait_bound_overrides.iter().cloned().fold(
        HashMap::<Ident, Punctuated<TypeParamBound, Add>>::new(),
        |mut map, param| {
            if let Some(bounds) = map.get_mut(&param.ident) {
                bounds.extend(param.bounds);
            } else {
                map.insert(param.ident, param.bounds);
            }
            map
        },
    );

    for generic in generics.params.iter_mut() {
        if let GenericParam::Type(ref mut ty) = generic {
            let ident = &ty.ident;
            if let Some(ors) = overrides.remove(ident) {
                ty.colon_token = Some(Token![:](Span::call_site()));
                ty.bounds = ors;
                ty.eq_token = None;
                ty.default = None;
            }
        }
    }
}