Sub topic 5
Transcribers: building the expanded code
This chapter assumes you can write a one-rule macro_rules! macro and know the common fragment specifiers (expr, ident, ty). Repetitions and hygiene get their own chapters, so they appear here only briefly.
What a transcriber is
Each rule in a macro_rules! macro has two halves joined by =>. The matcher on the left describes the input. The transcriber on the right describes the code to produce. The compiler matches the invocation against the matcher, binds each $name to the tokens it captured, and then copies the transcriber with every $name replaced by its captured fragment.
Fragments stay whole
A fragment captured as expr is substituted as one complete expression, not as loose tokens. That is why precedence cannot break it.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}This prints 25. A text-substituting system such as the C preprocessor would produce 2 + 3 * 2 + 3, which is 11. Rust treats 2 + 3 as a single unit, so the result is (2 + 3) * (2 + 3).
The outer delimiters are not part of the output
The braces, parentheses, or brackets around a transcriber only mark where it starts and ends. The compiler discards them. Only the tokens inside are emitted.
This matters when the transcriber has several statements. After the outer delimiters are removed, the remaining statements are placed where the macro was called. If that place is an expression, such as the right side of a let, a bare let statement is a syntax error. Wrap the body in a second pair of braces so it becomes one block expression.
macro_rules! add_one_then_double {
($x:expr) => {{
let y = $x + 1;
y * 2
}};
}
fn main() {
let r = add_one_then_double!(4);
println!("{}", r);
}This prints 10. The inner braces are emitted, so the call expands to a block that evaluates to y * 2.
Expanding to statements
Sometimes you want the output to be statements. If the macro is called in statement position, the transcriber can produce a let that stays in scope for the rest of the function.
macro_rules! make_var {
($name:ident, $val:expr) => {
let $name = $val;
};
}
fn main() {
make_var!(answer, 42);
println!("{}", answer);
}This works because the caller supplied the identifier answer. A name the macro invented itself would not be visible here. The hygiene chapter explains why.
A fragment is pasted at every use
If $x appears twice in the transcriber, the expression is evaluated twice. This is visible when the expression has side effects.
macro_rules! sum_twice_bad {
($x:expr) => {
$x + $x
};
}
macro_rules! sum_twice {
($x:expr) => {{
let v = $x;
v + v
}};
}
fn main() {
let mut n = 0;
let mut next = || {
n += 1;
n
};
let a = sum_twice_bad!(next());
let b = sum_twice!(next());
println!("{} {}", a, b);
}This prints 3 6. The first macro calls next() twice and adds 1 and 2. The second calls it once, stores 3 in v, and adds v to itself.
Common transcriber mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `expected expression, found keyword let` | Several statements in an expression position | Use `{{ ... }}` |
| Side effect happens twice | `$x` used more than once | Bind to a local with `let` |
| `cannot find value` for a name from the macro | The macro created a binding the caller cannot see | Take the name as an `ident` argument |
| Stray semicolon warning or error | Trailing `;` inside an expression-position transcriber | Remove it, or end the block with a value |
Exercise
The macro macro_rules! m { ($a:expr) => { let t = $a; t * 2 }; } is called as let r = m!(3);. Why does this fail to compile, and what is the smallest change that fixes it?
Show answer
The outer braces only delimit the transcriber and are discarded. The call therefore expands to let t = 3; t * 2 in expression position, where a let statement is not allowed. Wrap the body in a second pair of braces, {{ let t = $a; t * 2 }}, so the expansion is a single block expression that evaluates to 6.