Sub topic 11
Recursive macros and token-tree munching
This chapter assumes you can write macro_rules! rules with matchers, fragment specifiers, and repetitions. You should also know that a transcriber is the code a rule expands to.
Macros can call themselves
A macro's expansion may contain another macro invocation, including an invocation of the same macro. The compiler expands the result again, and repeats until no macro calls remain. This is recursion in the expander, not at run time. Each step must consume part of the input, or expansion never ends.
A recursive macro needs the same two parts as a recursive function:
- A base rule that matches the smallest input.
- A recursive rule that handles one piece and passes the rest to the macro again.
Token trees
The tt fragment specifier matches one token tree. A token tree is either a single token, such as a, +, or 42, or a group in matching delimiters, such as (...), [...], or {...}, together with everything inside it. Because tt accepts almost anything, it is the usual way to split input into "the first piece" and "everything else".
Example: counting tokens
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}
fn main() {
println!("{}", count!(a b c));
}The program prints 3. The first rule is the base case, for empty input. The second rule binds the first token tree to $head and the rest to $tail. It then calls count! on the rest.
Taking the head and recursing on the tail is called token-tree munching. A macro written this way is called a "muncher".
Example: recursion over expressions
Recursion also works with other fragments. This macro finds the largest of its arguments:
macro_rules! max {
($x:expr) => { $x };
($x:expr, $($rest:expr),+) => {{
let a = $x;
let b = max!($($rest),+);
if a > b { a } else { b }
}};
}
fn main() {
println!("{}", max!(3, 9, 4));
}This prints 9. The rules are tried in order, so the single-argument rule is the base case. Each expansion has its own a and b. Hygiene keeps them from colliding with each other or with the caller's variables.
Common errors
- Recursion limit. The compiler stops at a default depth of 128 and reports
recursion limit reached while expanding. Raise it with#![recursion_limit = "256"]at the crate root. For long inputs, a non-recursive design is usually better. - Rule order. The first matching rule wins. Put specific rules, such as the empty case, before general ones. A rule that is too general can capture input meant for a later rule.
- No progress. If the recursive call passes the same tokens back, expansion loops until it hits the limit.
- Forgetting that
ttis greedy about groups.(1 + 2)is one token tree, not five. If you expect to count the inner tokens, you will get 1. - Quadratic cost. Every step re-parses the remaining tokens. With a large input, the work grows with the square of its length.
Exercise
Exercise
count!(a b c) expands step by step. What does count!(a b c) expand to after the third recursive step, before the final constant is evaluated, and what happens if you call count! with 200 tokens without changing any settings?
Show answer
After the third step the expansion is 1usize + 1usize + 1usize + 0usize, since the last call to count!() matches the base rule. With 200 tokens the macro recurses 200 times, which exceeds the default limit of 128, so compilation fails with "recursion limit reached while expanding". Add #![recursion_limit = "256"] to the crate root, or use a non-recursive approach.