Sub topic 13
Internal Rules and Helper Arms
This chapter assumes you can write multi-arm macro_rules! macros, use $(...) repetitions, and read a recursive macro that consumes token trees (tt). Here you will learn how to hide a macro's helper logic inside the same macro. You will also learn where those helper arms must go and what breaks when you put them in the wrong place.
What an internal rule is
A macro_rules! macro is a list of arms, and the compiler tries them from top to bottom. Larger macros often need arms that only the macro itself should call, such as an accumulator step or a formatting helper. These are called internal rules.
Rust has no private keyword for macro arms. By convention, an internal rule starts with a marker token that callers would never write, usually @ followed by a name:
(@acc $n:expr;) => { /* ... */ };@ cannot start any Rust expression, type, or pattern. A caller is therefore very unlikely to produce it by accident, and the public arms can tell it apart from real input.
Internal rules give you three things:
- One macro name in the public API instead of a helper macro that users could import.
- Helper logic that lives next to the code that uses it.
- Accumulator state that stays out of the public syntax.
Worked example: counting with an accumulator
An earlier chapter showed a recursive count! that expanded to 1 + 1 + 1 + 0. This version carries a running total in an internal rule:
macro_rules! count {
(@acc $n:expr;) => { $n };
(@acc $n:expr; $head:tt $($tail:tt)*) => {
count!(@acc $n + 1usize; $($tail)*)
};
($($t:tt)*) => { count!(@acc 0usize; $($t)*) };
}
fn main() {
println!("{}", count!(a b c));
println!("{}", count!());
}This prints 3 and then 0.
The macro has three arms:
- The first arm is the base case. When no tokens remain after
@acc $n;, it returns the total. - The second arm peels one token tree off the front and adds one to the total.
- The third arm is the only public entry. It accepts any tokens and starts the accumulator at
0usize.
An expr fragment is forwarded as one opaque expression. In $n + 1usize, the earlier $n stays grouped, so precedence is never a problem.
Why arm order matters
The compiler tries arms in order, and the public arm in count! accepts anything. Suppose you put it first:
macro_rules! broken_count {
($($t:tt)*) => { broken_count!(@acc 0usize; $($t)*) };
(@acc $n:expr;) => { $n };
}The call broken_count!(@acc 0usize;) made by the first arm matches the first arm again, because @, acc, and the rest are all token trees. The expansion loops until the compiler reports recursion limit reached while expanding.
The rule is: put internal arms first and the public catch-all arms last.
There is a second, quieter reason. If a public arm uses a fragment like $e:expr and sits before the internal arm, the compiler must try to parse @acc ... as an expression. A failed parse of a fragment such as expr, ty, or pat is a hard error. The compiler does not fall through to the next arm. You get an error like expected expression, found '@', and your internal arm is never tried.
The only fragments that never fail this way are tt, ident, lifetime, and literal-style matches on single tokens. Fragments that run the full parser are the dangerous ones.
Worked example: an accumulator that builds output
Internal rules also work for building output in pieces. This macro collects key = value; pairs into a vector. The partial output sits inside brackets and is passed along as raw token trees:
macro_rules! config {
(@acc [$($out:tt)*]) => {
vec![$($out)*]
};
(@acc [$($out:tt)*] $k:ident = $v:expr; $($rest:tt)*) => {
config!(@acc [$($out)* (stringify!($k), $v.to_string()),] $($rest)*)
};
($($t:tt)*) => { config!(@acc [] $($t)*) };
}
fn main() {
let c = config!(host = "localhost"; port = 8080;);
println!("{:?}", c);
}This prints [("host", "localhost"), ("port", "8080")].
Each step moves one key = value; group into the bracketed accumulator and passes the remaining input on. When nothing remains, the base arm wraps the accumulated tokens in vec![...]. This is sometimes called push-down accumulation. You use it when a macro cannot emit its result until it has seen all of its input.
Two details are worth noting:
- The
$v:exprfragment is followed by;. This is one of the tokens allowed afterexpr, so the follow-set rules are satisfied. - Once captured by
$($out:tt)*, anexprfragment is a single opaque token tree. It is not re-parsed or split apart on later calls.
Internal rules in an exported macro
When a macro is exported with #[macro_export], the recursive calls must also work for users who import it by path, such as use my_crate::config;. A bare config!(...) inside the expansion would fail unless the user also had config in scope under that name. Use $crate:: so the call resolves from the defining crate:
#[macro_export]
macro_rules! config {
(@acc [$($out:tt)*]) => {
::std::vec![$($out)*]
};
(@acc [$($out:tt)*] $k:ident = $v:expr; $($rest:tt)*) => {
$crate::config!(@acc [$($out)* (stringify!($k), $v.to_string()),] $($rest)*)
};
($($t:tt)*) => { $crate::config!(@acc [] $($t)*) };
}
#[cfg(test)]
mod tests {
#[test]
fn builds_pairs() {
let c = crate::config!(a = 1; b = 2;);
assert_eq!(c, vec![("a", "1".to_string()), ("b", "2".to_string())]);
}
}Put this in src/lib.rs and run cargo test. The test calls the macro by its path, which exercises the $crate::config! recursion.
Internal rules versus a separate helper macro
Sometimes the helper is better as its own macro. This is common when several public macros share it. The table compares the two approaches.
| Aspect | `@name` arm in the same macro | Separate `#[doc(hidden)]` helper macro |
|---|---|---|
| Public names added | None | One more exported macro |
| Callers can invoke it | Yes, but only by writing `@name` | Yes, by name |
| Sharing between macros | Not possible | Possible |
| Recursive call syntax | `$crate::config!(@name ...)` | `$crate::__helper!(...)` |
| Arm order concerns | Yes, internal arms first | No |
For a helper used by one macro, the @name approach is simpler. For a helper shared by several macros, use a separate exported macro with a name like __helper and mark it #[doc(hidden)]. Neither approach is enforced privacy. A caller can still invoke the helper, and the compiler treats it as public API for semver purposes if it is exported.
Recursion limits and expansion cost
Every internal-rule step is a macro call, and the compiler caps nested expansion depth at 128 by default. A tt muncher that eats one token per step fails on long input with recursion limit reached while expanding. You can raise the limit in the crate that invokes the macro:
#![recursion_limit = "512"]The attribute goes at the crate root of the crate where the expansion happens, which may be the user's crate and not the macro's crate. Libraries therefore cannot fix the limit for their callers. Consider consuming several tokens per step if you expect long input.
Common mistakes
- Wrong arm order. A catch-all arm above
@arms causes either infinite recursion or a hard fragment parse error. - Forgetting
$crate::in an exported macro. Local tests pass because the macro is in scope, and downstream users getcannot find macro. - Reusing one marker for different jobs. Give each helper a distinct name, such as
@accand@finish, so the arms do not overlap. - Writing a marker that looks like real input. A marker made of ordinary identifiers can collide with caller syntax. Start with
@so that collisions are unlikely. - Reading the error at the wrong level. A failed internal call is reported as
no rules expected the tokenfor the inner call. Look at the expansion, not the original invocation (the next chapter on debugging covers this).
Exercise
The macro below is meant to sum its arguments, but cargo build reports recursion limit reached while expanding sum. What is wrong, and how do you fix it?
macro_rules! sum {
($($t:tt)) => { sum!(@go 0; $($t)) };
(@go $acc:expr;) => { $acc };
(@go $acc:expr; $x:expr $(, $rest:expr)) => {
sum!(@go $acc + $x; $($rest),)
};
}
Show answer
The public catch-all arm ($($t:tt)*) comes first, so it also matches the internal call sum!(@go 0; ...). It rewrites that call into sum!(@go 0; @go 0; ...) and keeps nesting until the recursion limit is hit. Move the two @go arms above the public arm. The macro then expands sum!(1, 2, 3) correctly through the internal arms. Because the public arm now sits last, only calls that do not start with @go reach it.