
Understand it
macro_rules! consumes token trees with balanced delimiters. Fragment specifiers such as expr and ty let the parser validate shapes before expansion, producing safer patterns than string substitution.
Rust tokenizes macro input into structured pieces. Identifiers, punctuation, and literals are tokens; balanced parentheses, brackets, and braces form delimited groups that can contain more tokens. A macro does not receive raw characters to split by hand. In a function-like invocation such as show!({a, b}), the name show selects the macro, while the input stream inside the invocation contains a brace group with a, a comma, and b. Keeping that boundary clear prevents confusion when reading a procedural macro parser.
A macro_rules! pattern can ask the compiler to parse a fragment as an expression, type, identifier, or other supported shape. A pattern like ($value:expr) rejects input that is not an expression before the transcriber runs. Repetition syntax can accept comma-separated lists, but test empty input, a single item, and a trailing comma explicitly. For the example, expand twice!(2 + 3) by hand and notice that the temporary evaluates the expression once before adding it to itself. That matters if the expression has side effects. Treat macros as syntax APIs: define accepted forms, produce readable errors, and avoid making a clever pattern harder to understand than an ordinary function.
Delimiter groups matter for error reporting too: a missing closing brace changes the token tree before your macro matcher sees it. Distinguish lexical or parse errors from a pattern that simply did not match. Keep an example for every arm in documentation, especially if one arm accepts an optional comma or nested group; syntax APIs deserve the same testing care as functions.
Read the code
macro_rules! twice {
($value:expr) => {{
let once = $value;
once + once
}};
}:expr captures a whole expression, and the let evaluates it once before it is used twice.
Practice starter
macro_rules! twice {
($value:expr) => {{
let once = $value;
once + once
}};
}
fn main() {
println!("{}", twice!(2 + 3));
println!("{}", twice!(struct));
}Try it
Predict which call the compiler rejects, and say whether the transcriber ever runs for it. Then change :expr to :tt and predict what happens to 2 + 3.
What success looks like: You can say which input :expr and :tt each accept, and why 2 + 3 is one fragment for the first but three token trees for the second.
Check your understanding
What does :expr require?
Reveal the answer
- A Rust expression
- Any text
- A type only
:expr asks the parser for a whole expression, so 2 + 3 matches as one fragment and struct is rejected before the transcriber runs.
Go deeper
Common misconception: “A macro works on raw text, so it can split its input however it likes.”
macro_rules! consumes token trees with balanced delimiters, and fragments such as expr ask the parser for a checked shape.
- Match the fragment:
twice!(2 + 3)gives$valuethe whole expression2 + 3as oneexprfragment. - Expand with a temporary: The transcriber writes
let once = 2 + 3;, so the expression runs once, even if it has side effects. - Read the result:
once + onceis the value of the block, so the call yields 10. The double braces make the expansion one block expression.
Transfer challenge: Add an arm ($first:expr, $second:expr) that returns $first + $second, then call twice!(1, 2) and twice!(1). Predict the arm each call picks and why twice!(1,) fails.
Connections
- Macro Hygiene: Resolve generated names without accidental capture
- Proc-Macro Boundaries: Separate host-time generation from target code
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Token Trees (courseId "systems", lessonId "token-trees") Link: https://crabrix.com/learn/systems/token-trees/ Goal: macro_rules! consumes token trees with balanced delimiters. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/token-trees) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.