final tweak of proc macro

This commit is contained in:
Joe Ardent 2023-06-14 15:44:54 -07:00
parent f456e07559
commit b59dfb5bf0

View file

@ -5,13 +5,13 @@ use syn::{parse_macro_input, ItemStruct};
#[proc_macro_derive(OptionalOptionalUser)] #[proc_macro_derive(OptionalOptionalUser)]
pub fn derive_optional_optional_user(input: TokenStream) -> TokenStream { pub fn derive_optional_optional_user(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ItemStruct); let input = parse_macro_input!(input as ItemStruct);
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let name = &input.ident; let name = &input.ident;
let has_user = input let has_user = input
.fields .fields
.iter() .iter()
.find(|f| { .find(|f| {
if let Some(ident) = f.ident.clone() { if let Some(ref ident) = f.ident {
ident == "user" ident == "user"
} else { } else {
false false
@ -19,19 +19,25 @@ pub fn derive_optional_optional_user(input: TokenStream) -> TokenStream {
}) })
.is_some(); .is_some();
let user_is_option_user = if has_user { let (use_any, user_is_option_user) = if has_user {
quote!( (
&&::std::any::TypeId::of::<::std::option::Option<crate::User>>() == self.user.type_id() quote!(
use ::std::any::Any;
),
quote!(
::std::any::TypeId::of::<::std::option::Option<crate::User>>()
== self.user.type_id()
),
) )
} else { } else {
quote!() (quote!(), quote!(false))
}; };
let output = quote!( let output = quote!(
impl #name { impl #impl_generics #name #ty_generics #where_clause {
fn has_optional_user(&self) -> bool { pub fn has_optional_user(&self) -> bool {
use ::std::any::Any; #use_any
#has_user #user_is_option_user #user_is_option_user
} }
} }
); );