Problem getting derive macro attribute

This is how I'm trying to get myattr attribute inside macro, but it's not working.
named.named.iter() is an empty iterator.

#[myattr = "something"]
#[derive(MyMacro)]
pub struct MyStruct {}
#[proc_macro_derive(MyMacro, attributes(myattr))]
pub fn my_drive(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);

    let struct_: syn::DataStruct = match ast.clone().data {
        syn::Data::Struct(data) => data,
        _ => panic!("Usage of #[Modbus] on a non-struct type"),
    };

    match &struct_.fields {
        syn::Fields::Named(named) => for field in named.named.iter() {
            let name = field.ident.as_ref().unwrap();
            let number = field.attrs.iter().filter_map(|attr| {
                match attr.parse_meta() {
                    Result::Ok(syn::Meta::NameValue(attr)) if attr.path.is_ident("myattr") => {
                        println!("found it!");
                        Some(attr.lit)
                    },
                    _ => None,
                }
            }).nth(0);
            
        }
        _ => unimplemented!()
    }

    (quote! {}).into()
}

Attributes are applied in order, so derive only sees ones which are below it, not above. This should work:

#[derive(MyMacro)]
#[myattr = "something"]
pub struct MyStruct {}

Unfortunately it doesn't. Actually I had tried this before but it doesn't seem to be the actual problem.

ast.attrs contains the attributes of the type definition. field.attrs contains the attributes of a specific field.

1 Like

Great! Thank you.

You might also be interested in trying to parse attributes more elegantly, with less boilerplate, using darling.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.