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
use proc_macro2::TokenStream;
use syn;
use syn::Meta;
use crate::helpers::{extract_meta, MetaHelpers, MetaIteratorHelpers, MetaListHelpers};
fn extract_properties(meta: &[Meta]) -> Vec<(&syn::Path, &syn::Lit)> {
meta.iter()
.filter_map(|meta| meta.try_metalist())
.filter(|list| list.path.is_ident("strum"))
.flat_map(|list| list.expand_inner())
.filter_map(|meta| meta.try_metalist())
.filter(|inner_list| inner_list.path.is_ident("props"))
.flat_map(|inner_list| inner_list.expand_inner())
.filter_map(|prop| match *prop {
syn::Meta::NameValue(syn::MetaNameValue {
ref path, ref lit, ..
}) => Some((path, lit)),
_ => None,
})
.collect()
}
pub fn enum_properties_inner(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let variants = match ast.data {
syn::Data::Enum(ref v) => &v.variants,
_ => panic!("EnumProp only works on Enums"),
};
let mut arms = Vec::new();
for variant in variants {
let ident = &variant.ident;
let meta = extract_meta(&variant.attrs);
let mut string_arms = Vec::new();
let mut bool_arms = Vec::new();
let mut num_arms = Vec::new();
if meta.is_disabled() {
continue;
}
use syn::Fields::*;
let params = match variant.fields {
Unit => quote! {},
Unnamed(..) => quote! { (..) },
Named(..) => quote! { {..} },
};
for (key, value) in extract_properties(&meta) {
use syn::Lit::*;
let key = key.segments.last().unwrap().ident.to_string();
match value {
Str(ref s, ..) => {
string_arms.push(quote! { #key => ::std::option::Option::Some( #s )})
}
Bool(b) => bool_arms.push(quote! { #key => ::std::option::Option::Some( #b )}),
Int(i, ..) => num_arms.push(quote! { #key => ::std::option::Option::Some( #i )}),
_ => {}
}
}
string_arms.push(quote! { _ => ::std::option::Option::None });
bool_arms.push(quote! { _ => ::std::option::Option::None });
num_arms.push(quote! { _ => ::std::option::Option::None });
arms.push(quote! {
&#name::#ident #params => {
match prop {
#(#string_arms),*
}
}
});
}
if arms.len() < variants.len() {
arms.push(quote! { _ => ::std::option::Option::None });
}
quote! {
impl #impl_generics ::strum::EnumProperty for #name #ty_generics #where_clause {
fn get_str(&self, prop: &str) -> ::std::option::Option<&'static str> {
match self {
#(#arms),*
}
}
}
}
}