How to get the fully qualified name of a function in a proc-macro?

I'm writing a procedural macro where I extract the attribute argument:

#[my_macro("something")]
pub fn my_func() {}

I get and store the "something" string, but I also want to get the fully qualified path of the decorated function (i.e., "crate::mod_1::mod_2::file::my_func"). How can I access this information from within the proc-macro?

Here are some options: macros - Equivalent of __func__ or __FUNCTION__ in Rust? - Stack Overflow

1 Like

While the solutions do provide the fully qualified path, the problem is that executing them from inside the procedural macro function returns the path of the proc-macro function instead of the targeted/decorated function.

You can't. Macros get only whatever is passed to them, not anything external. They don't know how and where the current module is included.

1 Like

Unlike a lot of questions about “how can I get information from inside a macro”, though, it would be possible for Rust to offer this. Macro expansion executes simultaneously with name resolution and module loading (otherwise you wouldn’t be able to use macros), so it would be feasible for the proc-macro API to offer the path of the module containing the macro call (which could then be concatenated with the fn name from the input tokens).

4 Likes

Yep. input_fn.sig.ident returns the function name. input_fn could technically also return the fully qualified path. As it stands, it seems to be impossible to get the fully qualified path as this information is not passed anywhere.