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
extern crate proc_macro;
extern crate syn;

#[macro_use]
extern crate quote;

use proc_macro::TokenStream;
use syn::DeriveInput;

#[proc_macro_derive(VariantName)]
pub fn variant_name(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree
    let input: DeriveInput = syn::parse(input).unwrap();

    let name = &input.ident;

    // Build the output, possibly using quasi-quotation
    let expanded = match input.data {
        syn::Data::Struct(_) => {
            quote! {
                impl VariantName for #name {
                    fn variant_name(&self) -> &'static str {
                        stringify!(#name)
                    }
                    fn variant_names() -> &'static [&'static str] {
                        &[stringify!(#name)]
                    }
                }
            }
        }
        syn::Data::Enum(enu) => {
            let branches = enu.variants.iter().map(|v| {
                let ident = &v.ident;
                let match_identifier = match v.fields {
                    syn::Fields::Named(_) => {
                        quote! {
                            #ident{ .. }
                        }
                    }
                    syn::Fields::Unnamed(_) => {
                        quote! {
                            #ident( .. )
                        }
                    }
                    syn::Fields::Unit => {
                        quote! {
                            #ident
                        }
                    }
                };
                quote! {
                    &#name::#match_identifier => stringify!(#ident)
                }
            });
            let names = enu.variants.iter().map(|v| v.ident);
            quote! {
                impl VariantName for #name {
                    fn variant_name(&self) -> &'static str {
                        match self {
                            #(#branches),*
                        }
                    }
                    fn variant_names() -> &'static [&'static str] {
                        &[#(stringify!(#names)),*]
                    }
                }
            }
        }
        syn::Data::Union(_) => panic!("VariantName can only be derived for Enum or Struct!"),
    };

    // Hand the output tokens back to the compiler
    expanded.into()
}