Generating macros using macros


#1

I need to generate an exported macro using an outer macro, where the inner, exported macro uses Kleene operators. So something like this:

#[macro_export]
macro_rules! foo {
    () => {
        #[macro_export]
        macro_rules! bar {
            ( $(things:expr)* ) => {
                // code
            };
        }
    };
}

Is there any way that rustc will allow me to do this? If I try the example verbatim rustc errors out with:

Standard Error

   Compiling playground v0.0.1 (file:///playground)
error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
 --> src/main.rs:6:16
  |
6 |             ( $(things:expr)* ) => {
  |                ^^^^^^^^^^^^^

error: aborting due to previous error

error: Could not compile `playground`.

To learn more, run the command again with --verbose.


#2

#3

It is possible to have a macro that generates a macro that contains $(...)* if the first one is implemented as a procedural macro.

The mashup! macro is one example of this: the user-facing public mashup! macro is a macro_rules macro, which calls a procedural macro through proc-macro-hack, which expands to a macro_rules macro that contains plenty of $(...)*.


#4

I see. Is there a way then to use proc macros on stable (last time I checked there wasn’t)?
Because depending nightly rustc is what I’d like to avoid.


#5

Yes, proc-macro-hack works with any stable Rust compiler 1.15+.