Sub topic 13
Internal rules and helper arms
This chapter assumes you can write multi-arm macro_rules! macros, use tt and expr fragments, and have seen recursive macros. If recursion is new to you, read the chapter on recursive macros first.
The problem: helpers have no private namespace
A recursive macro often needs extra state, such as an accumulator. A macro has no separate helper functions, so the usual trick is to add more arms to the same macro. These extra arms are called internal rules. By convention, each one starts with a marker token that callers never write, usually @name.
The @ token is not special syntax. It is an ordinary token that nobody uses in normal input, so it works as a tag.
A worked example
This macro counts token trees. The public arm takes the user's input. The @step arms carry the running total.
macro_rules! count_tts {
(@step $acc:expr;) => {
$acc
};
(@step $acc:expr; $head:tt $($tail:tt)*) => {
count_tts!(@step $acc + 1usize; $($tail)*)
};
($($t:tt)*) => {
count_tts!(@step 0usize; $($t)*)
};
}
fn main() {
println!("{}", count_tts!(a b c));
}This prints 3. The expansion goes through these steps:
Why the order of arms matters
The compiler tries arms from top to bottom and uses the first one that matches. The public arm ($($t:tt)*) matches any input at all, including @step 0usize; a b c. If it came first, the recursive call would match it again, and the macro would recurse until it hit the recursion limit.
Put internal rules first, with the most specific patterns at the top. Put the catch-all public arm last.
Passing state between arms
Internal rules usually pass state in the matcher. These are common patterns:
- An accumulator, as in
$acc:expr, that grows with each step. - A list of tokens collected so far, as in
[$($done:tt)*]. Square brackets keep it separate from the remaining input. - A mode tag, such as
@parseor@emit, that selects the phase of a multi-step macro.
Fragments such as expr become opaque after parsing. In the example, $acc + 1usize is passed on as one expr, so it is not reparsed with a different precedence. If you need to inspect tokens in a later step, accumulate them as tt instead.
Exported macros need `$crate`
When you mark a macro #[macro_export], users may import it by path, for example use mycrate::count_tts;. In that case a bare count_tts!(...) inside the transcriber may not resolve at the call site. Write the recursive call with a path:
#[macro_export]
macro_rules! count_tts {
(@step $acc:expr;) => { $acc };
(@step $acc:expr; $head:tt $($tail:tt)*) => {
$crate::count_tts!(@step $acc + 1usize; $($tail)*)
};
($($t:tt)*) => {
$crate::count_tts!(@step 0usize; $($t)*)
};
}The @step rules stay reachable because they belong to the same exported macro. Callers can technically write @step themselves, so this is a convention and not real privacy.
A separate hidden macro as an alternative
If the helper logic is large, you can move it into its own macro and hide it from documentation:
#[doc(hidden)]
#[macro_export]
macro_rules! __count_impl {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + $crate::__count_impl!($($tail)*) };
}This keeps each macro short. The cost is that __count_impl is now exported from your crate, so you cannot freely rename or remove it later.
| Approach | Strength | Cost |
|---|---|---|
| `@` arms in one macro | One name in the public API | Arm order matters, and the macro grows long |
| Separate hidden macro | Easier to read and test on its own | Extra exported name |
Exercise
In count_tts!, you move the public arm ($($t:tt)*) to the top of the macro. What happens when you call count_tts!(a b c), and why?
Show answer
The public arm matches first and expands to count_tts!(@step 0usize; a b c). That call also matches the public arm, because @, step, and the rest are all token trees. It expands again to a longer call, and the macro keeps recursing until the compiler reports that the recursion limit was reached. Internal @ rules must come before the catch-all arm.