Is there a way to get the file where a macro_attribute is placed?

#[find_me] // ../
fn foo(){

#[proc_macro_attribute] // ../
pub fn foo(attr: TokenStream, item: TokemStream) -> TokenStream{
     // Gets the file name of each `foo` macro attribute

     // I test file!() but just returns `../`

I saw the proc_macro::Span and proc_macro2::Span APIs but the first is nightly and the second requires to pass a flag in each crate that depends of it.

You can get it at runtime by outputting ::std::file!() but not from within the proc macro. Cargo sets some environment variables that allow you to get things like the crate root, but not the current file. Note that proc-macro2 can never do anything proc-macro can't; proc-macro2 internally wraps proc-macro.

The only way are the nightly-only / unstable APIs of Span :confused:

1 Like