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
/*!
# A Procedural Macro for Decorators
The Decorator macro generates a decorator method for each marked field. A field can be marked with the `#[dec]` field in front.
## Example
```
#[derive(Decorator)]
struct Widget {
    #[dec]
    width: u32,
    #[dec]
    height: u32,
}
```
Generates into:
```
struct Widget {
    width: u32,
    height: u32,
}
impl Widget {
    pub fn width(self, width: u32) -> Self {
        Self {
            width,
            ..self
        }
    }
    pub fn height(self, height: u32) -> Self {
        Self {
            height,
            ..self
        }
    }
}
```
Which can be used like:
```
let w = some_widget.width(10).height(20);
assert_eq!(w, Widget {width: 10, height: 20});
```
*/

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemStruct};

/// A macro to generate a decorator method for each marked field.
/// A field can be marked with the `#[dec]` field in front.
#[proc_macro_derive(Decorator, attributes(dec))]
pub fn derive_decorator(input: TokenStream) -> TokenStream {
    let item_struct = parse_macro_input!(input as ItemStruct);

    let mut decorators: Vec<(proc_macro2::Ident, syn::Type)> = vec![];
    if let syn::Fields::Named(ref fields_named) = item_struct.fields {
        for field in fields_named.named.iter() {
            for attr in field.attrs.iter() {
                match attr.parse_meta().unwrap() {
                    syn::Meta::Path(ref path) if *path.get_ident().unwrap() == "dec" => {
                        let item = field.clone();
                        decorators.push((item.ident.unwrap(), item.ty))
                    }
                    _ => (),
                }
            }
        }
    }

    let decorators = decorators.iter().fold(quote!(), |accumulator, (name, ty)| {
        quote! {
            #accumulator
            pub fn #name(self, #name:#ty ) -> Self {
                Self {
                    #name,
                    ..self
                }
            }
        }
    });

    let name = item_struct.ident;
    let (impl_generics, ty_generics, where_clause) = item_struct.generics.split_for_impl();
    TokenStream::from(quote! {
            impl #impl_generics #name #ty_generics #where_clause  {
                #decorators
            }
    })
}