MashPlant
MashPlant

Reputation: 81

Is is possible in Rust to invoke a macro in procedure macro code?

For example, I have a procedure macro attribute on a impl block like this, normally it handles methods:

#[my_proc_macro]
impl Foo {
  pub fn bar1() {}
  pub fn bar2() {}
}

Now the macro user may not want to write these methods, instead, he wants to invoke a macro to produce these methods, like:

#[my_proc_macro]
impl Foo {
  generate_methods!();
}

Now my_proc_macro will be fed with the tokens of macro invocation, instead the tokens of macro invocation result.

My question is: is it possible to expand generate_methods!() inside my_proc_macro, and work with the produced methods?

Upvotes: 5

Views: 599

Answers (1)

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 89016

Unfortunately, this is currently (Rust 1.44.1) impossible.

However, it's a known problem for quite some time already. The search term is "eager macro expansion". There is this open RFC which was started in February 2018:

Expose an API for procedural macros to opt in to eager expansion. This will:

  • Allow procedural and declarative macros to handle unexpanded macro calls that are passed as inputs,
  • Allow macros to access the results of macro calls that they construct themselves,
  • Enable macros to be used where the grammar currently forbids it.

So people are working on it, but I wouldn't count on getting this feature anytime soon. It's not an easy problem after all.

Upvotes: 2

Related Questions