roblib_macro/
lib.rs

1extern crate proc_macro;
2
3use quote::quote;
4use syn::{parse_macro_input, DeriveInput};
5
6#[proc_macro_derive(Command)]
7pub fn derive_command(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
8    let inp = parse_macro_input!(item as DeriveInput);
9    let ident = &inp.ident;
10
11    let res = quote! {
12        impl From<#ident> for crate::cmd::Concrete {
13            fn from(value: #ident) -> Self {
14                crate::cmd::Concrete::#ident(value)
15            }
16        }
17        impl From<crate::cmd::Concrete> for #ident {
18            fn from(value: crate::cmd::Concrete) -> Self {
19                if let crate::cmd::Concrete::#ident(m) = value {
20                    m
21                } else {
22                    panic!("Tried to convert an unknown command to a concrete command")
23                }
24            }
25        }
26    };
27
28    // println!("{res}");
29    proc_macro::TokenStream::from(res)
30}
31
32#[proc_macro_derive(Event)]
33pub fn derive_event(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
34    let inp = parse_macro_input!(item as DeriveInput);
35    let ident = &inp.ident;
36
37    let res = quote! {
38        impl From<#ident> for crate::event::ConcreteType {
39            fn from(value: #ident) -> Self {
40                crate::event::ConcreteType::#ident(value)
41            }
42        }
43        impl From<crate::event::ConcreteType> for #ident {
44            fn from(value: crate::event::ConcreteType) -> Self {
45                if let crate::event::ConcreteType::#ident(m) = value {
46                    m
47                } else {
48                    panic!("Tried to convert an unknown command to a concrete command")
49                }
50            }
51        }
52    };
53
54    // println!("{res}");
55    proc_macro::TokenStream::from(res)
56}