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
use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse_macro_input, spanned::Spanned, Attribute, AttributeArgs, Data, DeriveInput, Lit, LitStr,
    NestedMeta, Type,
};

struct MacroAttrs {
    pub repr: Type,

    pub no_debug: bool,
    pub no_display: bool,
    pub no_total_eq: bool,

    pub no_clone: bool,
    pub no_copy: bool,
}

fn find_repr(attrs: &Vec<Attribute>) -> MacroAttrs {
    let mut repr: Option<Type> = None;
    let mut no_display = false;
    let mut no_debug = false;
    let mut no_total_eq = false;
    let mut no_clone = false;
    let mut no_copy = false;

    for attr in attrs {
        if let Ok(meta) = attr.parse_meta() {
            let path = meta.path();

            if path.is_ident("no_debug") {
                no_debug = true;
            } else if path.is_ident("repr") {
                if let Ok(args) = attr.parse_args::<proc_macro2::TokenStream>() {
                    let args = args.into();
                    let args = syn::parse_macro_input::parse::<AttributeArgs>(args).unwrap();

                    match args.get(0) {
                        Some(v) => match v {
                            NestedMeta::Meta(item) => {
                                if repr.is_some() {
                                    panic!("Repr is already defined");
                                }

                                let ident = item.path().get_ident().unwrap().to_string();
                                repr = Some(syn::parse_str::<syn::Type>(&ident).unwrap());
                            }
                            _ => panic!("Invalid repr"),
                        },
                        None => {
                            panic!("Repr requires an argument");
                        }
                    };
                }
            } else if path.is_ident("no_display") {
                no_display = true;
            } else if path.is_ident("no_total_eq") {
                no_total_eq = true;
            } else if path.is_ident("no_clone") {
                no_clone = true;
            } else if path.is_ident("no_copy") {
                no_copy = true;
            }
        }
    }

    MacroAttrs {
        repr: repr.expect("Repr is required"),
        no_debug,
        no_display,
        no_total_eq,
        no_clone,
        no_copy,
    }
}

/// Macro that implements bunch of traits for enums that simply
/// are aliases for integer type
///
/// example:
/// ```no_run
/// #[derive(IntegralEnum)]
/// #[repr(u8)]
/// pub enum Yuu {
///     // explicit discriminant is required
///     Hatred = 0,
///     Pain = 1,
/// }
/// ```
///
/// Macro will automatically generate such trait implementations:
/// Clone, Copy, PartialEq, Eq, Debug, Display, TryFrom
#[proc_macro_derive(IntegralEnum)]
pub fn enum_try_from(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let macro_attrs = find_repr(&input.attrs);

    let repr = &macro_attrs.repr;

    match input.data {
        Data::Enum(e) => {
            let name = input.ident;
            let old_variants = e.variants;

            let items: Vec<_> = old_variants
                .iter()
                .map(|variant| {
                    if !variant.fields.is_empty() {
                        panic!("Enum with content is not supported");
                    }

                    let ident = &variant.ident;
                    let (_, discriminant) = variant
                        .discriminant
                        .as_ref()
                        .expect("Discriminant is required");
                    let strlit = Lit::Str(LitStr::new(&ident.to_string(), variant.span()));

                    (
                        quote::quote! {
                            #discriminant => { Ok(Self::#ident) }
                        },
                        quote::quote! {
                            Self::#ident => { #strlit }
                        },
                        quote::quote! {
                            Self::#ident => { Self::#ident }
                        },
                    )
                })
                .collect();

            let convert_arms = items.iter().map(|(d, _, _)| d);
            let display_arms = items.iter().map(|(_, d, _)| d);
            let clone_arms = items.iter().map(|(_, _, d)| d);

            let (display, debug) = if macro_attrs.no_display {
                (quote::quote!(), quote::quote!())
            } else {
                let display = quote::quote! {
                    impl core::fmt::Display for #name {
                        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                            f.write_str(match self {
                                #(#display_arms),*
                            })
                        }
                    }
                };

                if macro_attrs.no_debug {
                    (display, quote::quote!())
                } else {
                    let debug = quote::quote! {
                        impl core::fmt::Debug for #name {
                            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
                                <Self as core::fmt::Display>::fmt(self, f)
                            }
                        }
                    };
                    (display, debug)
                }
            };

            let total_eq = if macro_attrs.no_total_eq {
                quote::quote!()
            } else {
                quote::quote!(impl core::cmp::Eq for #name {})
            };

            let (clone, copy) = if macro_attrs.no_clone {
                (quote::quote!(), quote::quote!())
            } else {
                let clone = quote::quote! {
                    impl core::clone::Clone for #name {
                        #[inline]
                        fn clone(&self) -> Self {
                            match self {
                                #(#clone_arms),*
                            }
                        }
                    }
                };

                if macro_attrs.no_copy {
                    let copy = quote::quote! { impl core::marker::Copy for #name {} };

                    (clone, copy)
                } else {
                    (clone, quote::quote!())
                }
            };

            quote! {
                #clone
                #copy

                impl core::cmp::PartialEq for #name {
                    fn eq(&self, other: &Self) -> bool {
                        core::mem::discriminant(self) == core::mem::discriminant(other)
                    }
                }
                #total_eq

                #display
                #debug

                impl core::convert::TryFrom<#repr> for #name {
                    type Error = ();

                    fn try_from(v: #repr) -> core::result::Result<Self, Self::Error> {
                        match v {
                            #(#convert_arms),*

                            _ => Err(())
                        }
                    }
                }
            }
            .into()
        }

        _ => panic!("Structures or unions are not supported"),
    }
}