derive_enum_all_values/
lib.rs

1extern crate proc_macro;
2extern crate syn;
3#[macro_use]
4extern crate quote;
5
6use proc_macro::TokenStream;
7
8#[proc_macro_derive(AllValues)]
9pub fn derive_all_variants(input: TokenStream) -> TokenStream {
10    let syn_item: syn::DeriveInput = syn::parse(input).unwrap();
11    let variants = match syn_item.data {
12        syn::Data::Enum(enum_item) => enum_item.variants.into_iter().map(|v| v.ident),
13        _ => panic!("AllValues only works on enums"),
14    };
15
16    let enum_name = syn_item.ident;
17    let expanded = quote! {
18        impl #enum_name {
19            /// Returns a slice containing all variants (values) of the enum.
20            /// Returned as a const, so can be used in compile time.
21            pub const fn all_values() -> &'static[#enum_name] {
22                &[ #(#enum_name::#variants),* ]
23            }
24        }
25    };
26
27    expanded.into()
28}