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
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{parse_macro_input, Data, DataEnum, DeriveInput, Error, Fields};
macro_rules! derive_error {
($string: tt) => {
Error::new(Span::call_site(), $string)
.to_compile_error()
.into()
};
}
fn match_enum_to_string(name: &Ident, variants: &DataEnum) -> proc_macro2::TokenStream {
let mut match_arms = quote! {};
for variant in variants.variants.iter() {
let variant_ident = &variant.ident;
let fields_in_variant = match &variant.fields {
Fields::Unnamed(_) => quote_spanned! {variant.span() => (..) },
Fields::Unit => quote_spanned! { variant.span() => },
Fields::Named(_) => quote_spanned! {variant.span() => {..} },
};
let variant_string = variant_ident.to_string();
match_arms.extend(quote! {
#name::#variant_ident #fields_in_variant => #variant_string,
});
}
match_arms
}
#[proc_macro_derive(NamedVariant)]
pub fn derive_named_variant(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let data = &input.data;
let mut variant_checker_functions;
match data {
Data::Enum(data_enum) => {
variant_checker_functions = TokenStream2::new();
let variant_arms = match_enum_to_string(name, data_enum);
variant_checker_functions.extend(quote_spanned! { name.span() =>
const fn variant_name(&self) -> &'static str {
match self {
#variant_arms
}
}
});
}
_ => return derive_error!("NamedVariant is only implemented for enums"),
};
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let expanded = quote! {
impl #impl_generics #name #ty_generics #where_clause {
#variant_checker_functions
}
};
TokenStream::from(expanded)
}