Call macro inside macro repetition

Well, I'm trying to achieve nothing more that stated in the title:

I've seen examples of how a macro called inside another macro, but in repetition for some reason in doesn't expand, is it possible to achieve that?

The problem you're running into is that a macro expansion needs to produce valid rust code, and only then will any macros in the emitted code be expanded. As written, outer! expands to this, which is ungrammatical from Rust's point of view:

enum Test {
    A inner!(ok),
    B inner!(ok)
}
3 Likes

Thank you for the response.
How can I achieve modularity for this case? Like having a body for a variant and process it with another macro to have valid rust code only after this stage?

To do this kind of thing, you need what's known as a tt-muncher macro: It builds all of the text for the enum body first, and then wraps it in the enum as the final step. A good reference for this kind of advanced macro programming is The Little Book of Rust Macros.

macro_rules! inner {
    ( $name:ident {$($body:tt)*} ($variant:ident) $($tail:tt)* ) => {
        inner!{
            $name // Enum name
            {
                $($body)*  // Previously-built variants
                $variant,  // What this variant should look like
            }
            $($tail)* // Unprocessed variants
        }
    };
    
    // When there are no more variants, emit the enum definition
    ( $name:ident {$($body:tt)*} ) => {
        enum $name { $($body)* }
    };
}

macro_rules! outer {
    ( $($variants:ident),* ) => {
        inner!{ Test {} $(($variants))* }
    }
}

(Playground)

2 Likes

Thanks,
I believe other questions would be offtopic, and the main takeaway is to keep valid syntax on each step

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.