The 3 Macro Problem

I'm trying to create a macro system and I suspect that it might not be possible with the current implementation of procedural macros, but I figured I'd check.

My desired system has three macros:

  1. A child! macro that does some useful work
  2. A def! macro that generates the child! macro depending on the inputs to def!
  3. A call! macro that calls the child! macro, passing some of the parameters that were passed to call!

The goal is that def! and call! will be the interface that I expose to my library's clients, and child! will just be an implementation detail that the client doesn't have to care (or, ideally, know) about. Ideally, a client crate could have multiple (def!, call!) pairs (the exact name of child! depends on the inputs to def! and call!).

My current approach is to define def! and call! as procedural macros in my library crate my_lib and have child! be a macro_rules! macro that is generated by def!. A client library will call def! in one file (which will cause child! to be defined) and then call call! in a separate file (which will invoke child!).

In code:

pub fn def(a: TokenStream, b: TokenStream) -> TokenStream {
  parse a and b
  return quote!(macro_rules! child_whose_name_depends_on_b {
    () => {behavior that depends on b}

pub fn call(a: TokenStream, b: TokenStream) -> TokenStream {
  parse a and b
 return quote!(child_whose_name_depends_on_b! {})


use my_lib::def;
trait MyTrait {...}


use my_lib::call;
use crate::file_one::MyTrait;
struct MyStruct;
impl MyTrait for MyStruct {...}

The problem I'm seeing right now is that child! is not reliably defined. For the example above, the specific error I'm seeing is

error: cannot find macro `child_whose_name_depends_on_b` in this scope
  --> client_crate/

Is there just something wrong with my implementation or is there a fundamental problem with this approach? Having read some posts about sharing state between procedural macros, I suspect that my problem might be that I can't rely on def! being expanded before call!.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.