I am relatively new to the Rust macro context and I am currently working on a project where I need to create two Rust macros basically:
-
A macro to decorate a Rust trait, for example,
[#trait_enhance]for a trait namedtrait_name. -
A macro to decorate a Rust struct, for example,
[#trait_enhance(<trait_name>)].
In the first case, the decorated trait may contain illegal Rust syntax inside the trait block, which I want the trait to translate into legal Rust syntax finally. In the second case, the decorated struct has no illegal Rust syntax, but what it derived needs to refer to the final legal code of trait <trait_name>.
I am currently unsure about the overall structure of my project (i.e., how many crates are needed, and what specific crates are required). My basic question is: can I achieve my goals within a single proc-macro crate, similar to the enum_dispatch crate?
More specifically, I have two key concerns:
-
The order of the two macros matters, as the first macro must be unwrapped before the second. However, I am aware that there are ways to work around this, as demonstrated by the
enum_dispatchcrate. The main issue is whether a proc-macro can accept input with illegal Rust syntax. If not, I presume I would need to implement the first macro in a separate declarative macro crate (since I understand that a declarative macro cannot be exported from a procedural macro crate). -
If another declarative macro crate is needed, can I then define another procedural macro within a normal crate (where "normal" means the crate is not configured as
[lib] proc-macro=trueandproc-macro2="1.0"can be used) and use it in the definition of the declarative macro defined in the same crate?
(For these issues, I've asked chatGpt multiple times, but the answers are sometimes contradictory, so I'm not sure what to do. I would be very grateful if you could give me some advice.)