Define macro logic with proc_macro2 instead of proc_macro

This commit is contained in:
Kodi Craft 2024-06-20 15:26:17 +02:00
parent db036064e7
commit e6e9610d1f
Signed by: kodi
GPG Key ID: 69D9EED60B242822

View File

@ -17,18 +17,22 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::{format_ident, quote}; use quote::{format_ident, quote};
use syn::{parse_macro_input, spanned::Spanned, DeriveInput, Field, Ident}; use syn::{parse2, spanned::Spanned, DeriveInput, Field, Ident};
#[proc_macro_derive(Protocol)] #[proc_macro_derive(Protocol)]
pub fn derive_protocol(input: TokenStream) -> TokenStream { pub fn derive_protocol_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput); let expanded = derive_protocol(input.into());
TokenStream::from(expanded)
}
fn derive_protocol(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let input = parse2::<DeriveInput>(input).unwrap();
// Must be on an enum // Must be on an enum
let enum_ = match &input.data { let enum_ = match &input.data {
syn::Data::Enum(e) => e, syn::Data::Enum(e) => e,
_ => { _ => {
return syn::Error::new(input.span(), "Protocol can only be derived on enums") return syn::Error::new(input.span(), "Protocol can only be derived on enums")
.to_compile_error() .to_compile_error()
.into()
} }
}; };
let name = &input.ident; let name = &input.ident;
@ -60,8 +64,7 @@ pub fn derive_protocol(input: TokenStream) -> TokenStream {
variant.span(), variant.span(),
"Every variant on a protocol must have exactly 2 fields", "Every variant on a protocol must have exactly 2 fields",
) )
.to_compile_error() .to_compile_error();
.into();
} }
let var_name = ident_to_snake_case(&variant.ident); let var_name = ident_to_snake_case(&variant.ident);
@ -230,7 +233,7 @@ pub fn derive_protocol(input: TokenStream) -> TokenStream {
#server_trait #server_trait
#client_struct #client_struct
}; };
expanded.into() expanded
} }
fn ident_to_snake_case(ident: &Ident) -> Ident { fn ident_to_snake_case(ident: &Ident) -> Ident {