liveBook · Manning

Macro recursion

As explained in Write Powerful Rust Macros

Macro recursion is the expansion behavior in which a macro invocation expands to another invocation of the same macro.

Macro recursion occurs when a macro invocation expands into another invocation of the same macro. In Rust declarative macros, expansion recursion differs from function recursion: expressions such as `$val - 1` are not evaluated while the macro expands, so a seemingly valid terminal condition may never be reached. section 2.2.3

Recursive delegation

A `generate_get_value!` macro can delegate its one-argument form to a more general two-argument form: `generate_get_value!($struct_type)` expands to `generate_get_value!($struct_type, String)`. This reuses one implementation for both default and explicit return types. section 2.2.3

Listing 2.11 A recursive fumble
macro_rules! count {
    ($val: expr) => {
        if $val == 1 {
            1
        } else {
            count!($val - 1)
        }
    }
}

The `count!` example demonstrates a recursive fumble: expansion repeatedly appends `- 1` to the expression instead of evaluating it, eventually producing a compile-time recursion-limit error. section 2.2.3

How Write Powerful Rust Macros covers it

How deep it goes
Explains recursive expansion through working macro arms and a compile-time failure, but defers unknown-argument recursion to another example.
Examples
Demonstrates recursive `generate_get_value!` delegation and a failing `count!` macro that expands indefinitely.
What you can do after
Apply it via `macro_rules!` to route simpler invocations into generalized implementations while recognizing expansion-time recursion failures.
How it connects
Connects declarative macros with newtypes, generated methods, functions, and compile-time recursion limits.

Also explained in

Compare how 2 books explain macro recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.