deriving_via_impl/
lib.rs

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
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use quote::{format_ident, quote, ToTokens};

#[proc_macro_derive(Invoke)]
pub fn into_extract(input: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(input as syn::ItemEnum);

    let ident = &input.ident;
    let match_arms = input.variants.iter().map(|variant| {
        let module = variant
            .ident
            .to_token_stream()
            .to_string()
            .to_case(Case::Snake);
        let module = format_ident!("{}", module);
        quote! {
            #variant =>  #module :: extract
        }
    });

    let gen = quote! {
        impl #ident {
            fn invoke(self, input: &syn::DeriveInput, via: Option<syn::Type>) -> TokenStream {
                use #ident :: *;
                (match self {
                    #(#match_arms),*
                })(input, via)
            }
        }
    };

    gen.into()
}