Sub topic 11
Recursive macros and token-tree munching
This chapter assumes you can write a macro_rules! macro with several arms, use fragment specifiers such as expr, ident, and tt, and write repetitions with $(...). You should also know that a macro arm is chosen by matching the invocation against each matcher in order.
Why macros recurse
A macro_rules! transcriber can contain an invocation of any macro, including the macro being expanded. The compiler expands that inner call in turn. This lets a macro handle input that a single repetition cannot describe, such as input where each item changes how the rest is read.
Recursion needs two kinds of arms:
- A base case that matches the smallest input and does not call the macro again.
- A recursive case that handles one piece of input and passes the rest to a new invocation.
The compiler stops expanding when it reaches the base case. If no base case is ever reached, the compiler hits a recursion limit and reports an error.
Token trees
The tt fragment specifier matches a single token tree. A token tree is one of two things:
- A single token that is not a delimiter, such as
a,+,42, or"text". - A matched pair of delimiters
(),[], or{}together with everything inside, nested to any depth.
So a, +, and (1, 2, [3]) are each one token tree. The input a + (b * c) is three token trees: a, +, and (b * c).
Because tt accepts almost anything, it is the most flexible fragment. It is also the only fragment that lets you look at input piece by piece without the parser committing to a grammar rule first. Other fragments, such as expr, parse the input as a Rust construct and fail if it does not fit.
A first recursive macro
This macro counts its arguments by removing one token tree per step.
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}
fn main() {
println!("{}", count!(a b c));
}This prints 3. The expansion proceeds like this:
count!(a b c)matches the second arm with$headasaand$tailasb c. It expands to1usize + count!(b c).count!(b c)expands to1usize + count!(c).count!(c)expands to1usize + count!().count!()matches the first arm and expands to0usize.
The final code is 1usize + (1usize + (1usize + 0usize)) in effect, which the compiler evaluates as 3.
Arm order matters here. The empty arm comes first so the empty input never reaches the second arm. In this case the second arm would not match empty input anyway, because $head:tt needs at least one token tree.
Token-tree munching
Token-tree munching, also called tt munching, is the technique of taking input one token tree at a time. The macro matches a small piece at the front of the input, handles it, and calls itself with the remainder. The count! macro above is the simplest example.
A more useful pattern is a macro that reads a small language. This example accepts a list of name => value pairs and generates println! calls, with a custom keyword in front of each one.
macro_rules! show {
() => {};
(int $name:ident = $val:expr; $($rest:tt)*) => {
println!("int {} = {}", stringify!($name), $val);
show!($($rest)*);
};
(text $name:ident = $val:expr; $($rest:tt)*) => {
println!("text {} = {:?}", stringify!($name), $val);
show!($($rest)*);
};
}
fn main() {
show! {
int age = 30;
text city = "Oslo";
int count = 2 + 3;
}
}This prints:
int age = 30
text city = "Oslo"
int count = 5Each arm starts with a literal keyword (int or text), so the compiler can pick the right arm by looking at the first token. The arm consumes one statement and passes $($rest)* back. The base case () => {}; expands to nothing and ends the recursion.
The trailing $($rest:tt)* is the standard way to capture "everything else." Because tt matches any token tree, this repetition always succeeds and never causes an ambiguity error.
Why not use a repetition instead?
A plain repetition such as $($kind:ident $name:ident = $val:expr;)* works when every item has the same shape. Munching is the better fit when:
- Different items have different shapes, as with
intandtextabove. - Each step must decide something based on earlier items, such as a running count or an accumulated value.
- The output must be built in an order that a flat repetition cannot express.
If the input is uniform, use a repetition. It expands faster and is easier to read.
Accumulators
A macro cannot hold mutable state between invocations. When a step needs to remember something, you pass it forward as an extra argument. This is the accumulator pattern.
This macro reverses a list of expressions into a tuple-like array. Each step moves one item from the input into the accumulator, so the accumulator ends up in reverse order.
macro_rules! reverse_vec {
// Done: no input left, build the vector from the accumulator.
(@acc [$($out:expr),*]) => {
vec![$($out),*]
};
// Move the first remaining item to the front of the accumulator.
(@acc [$($out:expr),*] $head:expr $(, $tail:expr)*) => {
reverse_vec!(@acc [$head $(, $out)*] $($tail),*)
};
// Entry point.
($($x:expr),* $(,)?) => {
reverse_vec!(@acc [] $($x),*)
};
}
fn main() {
let v = reverse_vec![1, 2, 3];
println!("{:?}", v);
}This prints [3, 2, 1].
Two details are worth noting:
- The arms that start with
@accare internal helper arms. The@acctoken cannot be typed by accident as a normal argument, so the public arm at the bottom is never confused with them. The next chapters cover this pattern in more detail. - The entry arm is placed last. The helper arms must come first, because an input beginning with
@accwould otherwise be tried against$($x:expr),*and produce a parse error instead of falling through to the next arm.
The second point is a real gotcha. Once the compiler starts parsing a fragment such as expr, it cannot back out to try another arm. If the parse fails, that is a hard error. Putting the most specific arms first avoids this.
The recursion limit
The compiler limits macro expansion depth. The default is 128 nested expansions. When a macro exceeds it, you see an error like this:
error: recursion limit reached while expanding `count!`
= help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crateYou can raise the limit with a crate-level attribute:
#![recursion_limit = "256"]Raising the limit is a workaround, not a fix. A munching macro expands once per token tree, so a long input hits the limit quickly. Compile time also grows, and some munchers grow quadratically because every step re-parses the whole remaining input.
Ways to reduce depth:
- Consume several token trees per step. For example, add an arm that matches
$a:tt $b:tt $c:tt $d:tt $($rest:tt)*and handles four at once. - Use a repetition for the uniform part of the input and recurse only where the shape changes.
- Move large counting or indexing work to a
const fnor an array length expression.
For counting specifically, a substitution trick avoids recursion entirely:
macro_rules! replace_expr {
($_t:tt $sub:expr) => { $sub };
}
macro_rules! count_flat {
($($x:tt)*) => { 0usize $(+ replace_expr!($x 1usize))* };
}
fn main() {
println!("{}", count_flat!(a b c d e));
}This prints 5. Each token tree is replaced by 1usize, and the results are added in one flat expression. There is no recursion, so the depth limit does not apply.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `recursion limit reached` | Input too long, or the base case never matches | Check the base case, consume more tokens per step, or raise `recursion_limit` |
| `no rules expected the token` | The remaining input does not match any arm | Add an arm for the missing shape, or check that the recursive call passes `$($rest)*` and not `$rest` |
| `local ambiguity when calling macro` | Two ways to match the same tokens | Make the arms start with distinct literal tokens |
| `expected expression, found ...` | An `expr` arm came before a more specific arm | Reorder so specific arms are first |
| Output missing a statement | A transcriber ended with an expression and no semicolon | Add `;` after each generated statement |
The second row catches many beginners. Forgetting the * repetition around the tail turns the rest of the input into a single captured token tree, and the recursive call receives something the arms do not expect.
Choosing recursion or repetition
- Use a single repetition when every input item has the same shape and the output is a simple map over items.
- Use recursion with
ttwhen the input has several shapes, a small grammar, or state that carries from one item to the next. - Use an accumulator when the output must be built in a different order from the input, or when you need to collect items before producing a result.
- Move to a procedural macro when the recursion is deep, the grammar is complex, or the error messages need to be better than the compiler gives for failed arm matches.
Exercise
Write a macro sum! that adds any number of expressions using recursion, with sum!() evaluating to 0. Then explain what sum!(1, 2, 3) expands to, and why sum!(1, 2, 3,) with a trailing comma would fail with your first version.
Show answer
One version:
macro_rules! sum {
() => { 0 };
($head:expr $(, $tail:expr) $(,)?) => { $head + sum!($($tail),) };
}
sum!(1, 2, 3) expands to 1 + sum!(2, 3), then 1 + (2 + sum!(3)), then 1 + (2 + (3 + sum!())), and sum!() is 0, so the result is 6. Without the $(,)? at the end of the second arm, the trailing comma in sum!(1, 2, 3,) leaves a comma that no arm accepts, so the compiler reports "no rules expected the token ,". Adding $(,)? lets the arm accept one optional trailing comma. The recursive call passes only $($tail),*, which has no trailing comma, so deeper calls are fine.
Exercise
In the show! macro, what happens if you swap the order so that the () => {}; arm comes last, and does it change the behavior? What happens if you remove it entirely and call show! with an empty list?
Show answer
Moving () => {}; to the end does not change behavior, because the other arms need a leading int or text token and never match empty input, so only the empty arm matches the empty call. If you remove the arm entirely, the final recursive call show!() has no matching arm, and the compiler reports "unexpected end of macro invocation" or "no rules expected the token". The base case is what lets the last statement end the recursion cleanly.