4

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • Can't reproduce locally. – Chayim Friedman Apr 04 '22 at 22:02
  • Have exactly the same problem right now. Will either solve it and post solution here or make reproducible sample – Michael Ilyin May 21 '22 at 17:54
  • 2
    This happens when syntax tree of source structure MyStruct is copied into resulting token stream (maybe with some modification like changing name, replacing some types, etc). The attributes "my_attr" are also copied into generated structure, which is not under "#[derive(MyMacro)] anymore. So the #[my_attr] attributes are not valid *in scope of generated structure* – Michael Ilyin May 22 '22 at 13:50

0 Answers0