简体   繁体   中英

How can I call one procedural macro from another?

I would like to compose two procedural macros - one is mine and the second comes from another crate.

I want to call the procedural macro like a normal function. The function marked as #[proc_macro_derive] is public, but I cannot call it from my macro: the compiler cannot find the function. I think that procedural macro functions are used only during code generation and are not present in the final code during compilation.

I could generate code that has #[derive(...)] and the compiler will call that second macro, but this approach requires the end user to depend on the second macro crate even though they are not using it directly.

Is there any way I could call a procedural macro like a normal function which takes tokens and returns tokens?

I've found a workaround for simplest case, where the second procedural macro must be called after the first one:

  1. Create a separate crate that is not a procedural macro crate
  2. Include both procedural macros as dependencies in Cargo.toml and in lib.rs add #[macro_use] extern crate ... for both crates.
  3. Let the first macro generate code with #[derive(SecondProcMacro)]

This way, the user only has to add one dependency: the crate that includes both procedural macros.

I still have no idea what to do if I would like to postprocess the output of the other procedural macro.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM