Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call one procedural macro from another?

Tags:

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?

like image 208
synek317 Avatar asked Mar 06 '18 22:03

synek317


1 Answers

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.

like image 181
synek317 Avatar answered Sep 20 '22 13:09

synek317