简体   繁体   中英

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?

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.

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