Sub topic 2
Transcribers: building the expanded code
Assume you know Rust expressions, let bindings, vectors, and how to run a Cargo project. A transcriber is the part of a macro_rules! rule that produces Rust code after the matcher accepts the input.
Captured variables begin with $. Literal tokens in the transcriber are copied directly. A repetition in the matcher must have a corresponding repetition in the transcriber.
macro_rules! list {
($($item:expr),* $(,)?) => {{
let mut values = Vec::new();
$(values.push($item);)*
values
}};
}
fn main() {
let numbers = list![10, 20, 30,];
println!("{numbers:?}");
}The first repetition captures zero or more expressions separated by commas. The second repetition emits one values.push(...) statement for each captured expression. The optional $(,)? accepts one trailing comma.
A repetition must preserve the structure of its captures. If a transcriber uses two captures from the same repetition, both expand the same number of times. A separator placed outside the repetition is emitted once; a separator placed inside it separates repeated output.
| Pattern | Meaning |
|---|---|
| `$( $x:expr ),*` | Zero or more expressions separated by commas |
| `$( $x:expr ),+` | One or more expressions separated by commas |
| `$(,)?` | An optional comma |
Follow-set rules
Rust restricts which tokens may follow some fragment types. This prevents an expression from being parsed differently depending on later input. For example, an expr fragment cannot generally be followed immediately by another expression fragment. A comma, semicolon, or closing delimiter makes the boundary clear.
Prefer ($left:expr, $right:expr) over an ambiguous pattern such as ($left:expr $right:expr). If no rule accepts the next token, the compiler reports that no rules expected it.
Hygiene
Macro hygiene keeps names introduced by a macro separate from similarly named caller variables. In list!, the macro's values binding does not capture or overwrite a caller's values. However, $item refers to the expression supplied by the caller, so its names resolve in the caller's context.
Exercise
Why does list![a, b] need a repetition in the transcriber?
Show answer
The matcher captures multiple expressions, so the transcriber must repeat values.push($item); once for each captured expression.