Sub topic 5
Transcribers: building the expanded code
This chapter assumes you can write a one-rule macro_rules! macro and know the basic fragment specifiers (expr, ident, ty, tt). It covers the right-hand side of a rule, the transcriber, and how the compiler turns it into code.
What a transcriber is
Every rule in a macro_rules! macro has two halves separated by =>. The matcher on the left describes the input. The transcriber on the right describes the code the compiler substitutes for the invocation.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}Here ($x:expr) is the matcher and { $x * $x } is the transcriber. The program prints 25.
The transcriber is not a function body. It is a template of tokens. The compiler copies the tokens, replaces each $x with whatever was captured, and parses the result as code at the place where the macro was called.
The outer delimiters are not part of the output
The transcriber is wrapped in a pair of delimiters, { }, ( ), or [ ]. Rust does not care which you pick, and the compiler discards them. Most code uses braces.
This causes a common mistake. If the expansion must contain several statements and end in a value, you need a real block, which means a second pair of braces inside the first.
macro_rules! sum_pair {
($a:expr, $b:expr) => {{
let a = $a;
let b = $b;
a + b
}};
}
fn main() {
let total = sum_pair!(10, 20);
println!("{}", total);
}The outer braces are the transcriber's delimiters. The inner braces form a block expression, so the macro expands to { let a = 10; let b = 20; a + b }. With only one pair, the expansion would be let a = 10; let b = 20; a + b, which is not a single expression and does not parse after let total =.
| Transcriber | Expands to | Works as |
|---|---|---|
| `{ $x * $x }` | `$x * $x` | An expression |
| `{{ let v = $x; v * v }}` | A block | An expression |
| `{ let $name = $val; }` | A `let` statement | A statement only |
| `{ struct $n; }` | An item | An item only |
The expansion context decides what is valid
The compiler parses the expansion according to where the macro was invoked. A macro called in expression position must expand to one expression. A macro called as a statement can expand to several statements. A macro called at module level can expand to items.
The make_var macro from the spine expands to a statement:
macro_rules! make_var {
($name:ident, $val:expr) => {
let $name = $val;
};
}
fn main() {
make_var!(answer, 42);
println!("{}", answer);
}The binding is visible after the call because the caller supplied the identifier answer. Chapter on hygiene covers why this works and why a name written inside the transcriber would not be visible.
Avoid a trailing ; in a transcriber meant for expression position. The compiler ignores it and emits a lint warning, and the habit hides real mistakes.
Metavariables are substituted as units
When the matcher captures $x:expr, the captured value is a parsed expression node. Pasting it into the transcriber does not re-parse it as loose text, so operator precedence cannot change the grouping. This is why square!(2 + 3) gives 25 and not 11.
Compare it with a macro that captures raw tokens:
macro_rules! bad_square {
($a:tt + $b:tt) => {
$a + $b * $a + $b
};
}
fn main() {
println!("{}", bad_square!(2 + 3));
}A tt fragment is a single token, and tokens are pasted as written. The expansion is 2 + 3 * 2 + 3, which is 11. The expr fragment is the safer default for arguments that are meant to be values.
A metavariable pasted twice is evaluated twice
A fragment is substituted once for every $x in the transcriber. If the expression has side effects, they happen each time.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
let mut n = 0;
let mut next = || {
n += 1;
n
};
println!("{}", square!(next()));
}The expansion is next() * next(), so the call runs twice. The first call returns 1, the second returns 2, and the program prints 2, not 1.
The fix is to evaluate the argument once and bind it to a local name:
macro_rules! square {
($x:expr) => {{
let v = $x;
v * v
}};
}
fn main() {
let mut n = 0;
let mut next = || {
n += 1;
n
};
println!("{}", square!(next()));
}This prints 1. Because of hygiene, the macro's v cannot clash with a variable named v in the caller's expression.
Using fragments in the right syntactic place
You can put a captured fragment anywhere its kind is allowed. An ident can name a variable, function, or type. A ty can appear in type positions. An expr can appear wherever an expression can. Some combinations need care.
A ty fragment cannot be followed directly by :: in expression position. Wrap it in angle brackets to use it as a qualified path:
macro_rules! new_of {
($t:ty) => {
<$t>::new()
};
}
fn main() {
let s: String = new_of!(String);
println!("{:?}", s);
}The expansion is <String>::new(). This is the usual form for calling associated functions on a captured type.
Turning input into text
The built-in macros stringify! and concat! work well inside transcribers. stringify! converts tokens into a string literal at compile time:
macro_rules! show {
($e:expr) => {
println!("{} = {:?}", stringify!($e), $e)
};
}
fn main() {
show!(1 + 2 * 3);
}This prints 1 + 2 * 3 = 7. The expression is both printed as source text and evaluated, which is the pattern behind assert! failure messages and dbg!.
Writing paths that survive the call site
The transcriber is pasted into someone else's code. A name like HashMap may not be imported there, or may refer to a different type. Use absolute paths for anything outside the macro's own input:
macro_rules! new_map {
() => {
::std::collections::HashMap::new()
};
}
fn main() {
let m: ::std::collections::HashMap<i32, i32> = new_map!();
println!("{}", m.len());
}The leading :: starts the lookup at the crate root, so a local module called std cannot interfere. For items in your own crate, use $crate::, described in the scoping and export chapter.
Repetitions in the transcriber
The matcher captures repeated input with $( ... ),*. The transcriber replays it with the same shape:
macro_rules! my_vec {
() => {
Vec::new()
};
($($x:expr),+ $(,)?) => {{
let mut v = Vec::new();
$( v.push($x); )+
v
}};
}
fn main() {
let a: Vec<i32> = my_vec![];
let b = my_vec![1, 2, 3,];
println!("{:?} {:?}", a, b);
}The line $( v.push($x); )+ is emitted once per captured $x. A metavariable captured at repetition depth one must be used at depth one in the transcriber. The next chapter covers the rules for depth and separators.
Common transcriber errors
- Missing inner braces. The expansion is several statements in expression position. Add a second pair of braces.
- Unbound
$name. If the matcher never defined$name, the transcriber cannot substitute it, and compilation fails with a parse error near the$. - Wrong depth. Using a metavariable captured inside
$( ... )*outside any repetition is rejected. Using it inside one repetition when it was captured under two also fails. - Double evaluation. The argument is pasted once per
$x. Bind it withletif it should run once. - Precedence surprises. These come from
ttfragments, which paste raw tokens. Preferexprfor values. - Context mismatch. An item such as
structcannot expand where an expression is expected, and a bareletcannot expand where a value is expected.
Exercise
The macro macro_rules! twice { ($e:expr) => { $e; $e } } is called as let n = twice!(compute());. What goes wrong, and how do you change the transcriber so it calls compute() once and returns its value?
Show answer
The expansion is compute(); compute(), which is two statements, not one expression, so it does not parse after let n =. It would also call compute twice. Use a block with a local binding: ($e:expr) => {{ let v = $e; v }}. Then the macro evaluates compute() once and returns the value.
Exercise
What does bad_square!(2 + 3) print for macro_rules! bad_square { ($a:tt + $b:tt) => { $a + $b * $a + $b }; }, and why does square!(2 + 3) with an expr fragment print a different number?
Show answer
bad_square! prints 11. The tt fragments paste the raw tokens, so the expansion is 2 + 3 * 2 + 3 and multiplication binds tighter than addition. An expr fragment is pasted as a single parsed expression, so square!(2 + 3) is (2 + 3) * (2 + 3), which is 25.