Injected Inner Attributes do not take effect on a module

⚓ Rust    📅 2025-06-30    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 37 days ago. The information described in this article may have changed.

But, injected attributes on functions do take effect.

Hi, I currently have a proc macro root_macro which I want to apply at the root of a crate, say in main.rs. This macro parses main.rs and adds an attribute proc macro fn_macro to every function via the visitor pattern provided by the syn parsing library. This is accomplished by pushing my desired attribute onto the function's vector of attributes. Then, when I compile main.rs, both macros take effect. That is, I can verify that all functions in main.rs are affected by fn_macro by running cargo expand and running the program.

Now, I want root_macro to recursively perform this operation to every module in my crate. So if there is a module in main.rs like mod x;, my root_macro currently can visit all such statements and add itself to their attribute list. I simply used the same code I did previously, by just pushing the attribute onto the module's list of attributes.

However, this does not work. When I run cargo expand, all the modules are inlined, but my fn_macro is not applied to the functions inside.

What's the difference here? How come adding attributes to functions does something, but adding attributes to modules has no effect?

Is there a way I can force modules to be inlined before my macro is expanded?

Thanks. I know custom inner attributes are unstable, I just think this should be able to work since there is no ambiguity as to which macro to apply to each module, it is all the same.

1 post - 1 participant

Read full topic

🏷️ rust_feed