How do I use attributes on fields on a custom derive macro?

Viewed 300

I'm writing my derive macro:

use proc_macro::{self, TokenStream};
#[proc_macro_derive(MyMacro, attributes(my_attr))]
pub fn my_macro(input: TokenStream) -> TokenStream {
  ...
  TokenStream::from(my_generated_code)
}

with the attributes which will be used like:

use my_crate::MyMacro;
#[derive(MyMacro)]
#[my_attr(foo)]
struct MyStruct {
  // some fields
  #[my_attr(abc)]
  a: i32,
}

But this snip leads to:

error: cannot find attribute `my_attr` in this scope
  --> src/main.rs:10:7
   |
6  |     #[my_attr(abc)]
   |       ^^^^^^^

This is insanely weird because the attribute on struct is working well. Also I tried to change struct on enum and then field annotation has worked for some reason

May it be the problem of rustc, proc_macro version? rustc version: rustc 1.61.0-nightly (c5cf08d37 2022-03-30)

Macro-crate's Cargo.toml:

[lib]
proc-macro = true

[dependencies]
syn = {version= "1.0", features = ["full", "extra-traits"]}
quote = "1.0"

I found the same problem: issue, but the solution isn't clear at all and it's solved so I can't ask for some explanations

0 Answers
Related