Sub topic 12
Inspecting expansions and reading macro errors
This chapter assumes you can write a macro_rules! macro with several rules, fragment specifiers such as expr and ident, and repetitions like $( ... ),*. You should also be able to build and run a Cargo project. Some tools below need a nightly toolchain, and the text says so where that applies.
Why macro bugs are hard to see
A macro runs before type checking. The compiler matches your invocation against each rule, substitutes the captured fragments into the transcriber, and only then checks the resulting code. An error can therefore come from two places:
- Matching: no rule accepted the tokens you wrote.
- Expansion: a rule matched, but the code it produced does not compile.
The error text looks different in each case, and the fix lives in different parts of the macro. The first debugging step is always to decide which phase failed.
Printing what the macro received
stringify! turns tokens into a string literal without evaluating them. It is the cheapest way to see what a fragment captured.
macro_rules! show {
($e:expr) => {
println!("{} = {:?}", stringify!($e), $e)
};
}
fn main() {
let a = 2;
show!(a * 3 + 1);
}This prints a * 3 + 1 = 7. The first part is the source text of the expression, and the second is its value. Many test and assertion macros are built on this idea.
compile_error! stops compilation with a message you write. Put it in a final catch-all rule so that bad input produces a readable error instead of the generic "no rules expected" message.
macro_rules! my_max {
($x:expr) => { $x };
($x:expr, $($rest:expr),+) => {{
let a = $x;
let b = my_max!($($rest),+);
if a > b { a } else { b }
}};
($($other:tt)*) => {
compile_error!(concat!(
"my_max! expects one or more comma-separated expressions, got: ",
stringify!($($other)*)
))
};
}
fn main() {
println!("{}", my_max!(3, 9, 4));
}The program prints 9. If you call my_max!(1; 2), the first two rules fail and the third reports your own message. The tt repetition accepts any tokens, so the catch-all always matches. It must come last, because rules are tried in order.
Seeing the expanded code
Printing tokens shows the input. To see the output, ask the compiler for the expanded source.
| Tool | What it does | Needs nightly? |
|---|---|---|
| `cargo expand` | Prints your crate with every macro expanded. Install it with `cargo install cargo-expand`. | It invokes nightly rustc internally, so a nightly toolchain must be installed. |
| `rustc -Zunpretty=expanded src/main.rs` | The compiler flag that `cargo expand` wraps. It works only for single files with no dependencies. | Yes |
| rust-analyzer: "Expand macro recursively" | Shows the expansion of the macro under your cursor in the editor. | No |
| `trace_macros!(true);` | Prints each expansion step as the compiler performs it. | Yes, with `#![feature(trace_macros)]` |
Take this macro:
macro_rules! add_one {
($x:expr) => { $x + 1 };
}
fn main() {
let y = add_one!(41);
println!("{}", y);
}In the cargo expand output, the let line becomes let y = 41 + 1;. The println! call also expands, into a block of formatting machinery from the standard library. You can ignore that part. Scan for the lines you wrote.
trace_macros! is most useful for recursive macros. It prints a line for each call, such as count! { a b c }, followed by what that call expanded to. You can watch the input shrink one token tree per step. Wrap only the call you care about:
#![feature(trace_macros)]
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}
fn main() {
trace_macros!(true);
let n = count!(a b c);
trace_macros!(false);
println!("{}", n);
}Build this with a nightly compiler. It prints 3, and the compiler's notes show each recursive step.
Reading matching errors
Matching errors name the first token the compiler could not fit into any rule. The exact wording changes between compiler versions, but the meaning stays the same.
| Message | Usual cause | Fix |
|---|---|---|
| `no rules expected the token X` | The input has a token that no rule accepts at that position. | Compare the invocation with each matcher. Check separators, trailing commas, and `;` versus `,`. |
| `unexpected end of macro invocation` | The matcher wanted more tokens than you gave it. | Look for a missing argument, or make the part optional with `$(...)?`. |
| `local ambiguity when calling macro` | Two ways of matching are possible at the same point, usually between adjacent repetitions. | Add a distinct separator or a literal token between the repetitions. |
| `expected expression, found ...` | An `expr` fragment started to parse and hit invalid syntax. | Fix the argument. Other rules will not be tried. |
| `recursion limit reached while expanding` | A recursive macro nests more than 128 levels. | Add a base case, or raise the limit. |
| `variable 'x' is still repeating at this depth` | A repeating variable is used outside its `$(...)`. | Wrap the use in a repetition with matching depth. |
| `meta-variable ... repeats N times, but ... repeats M times` | Two variables in one repetition captured different counts. | Make the invocation supply equal counts, or restructure the matcher. |
Here is the classic repetition mistake:
macro_rules! sum_all {
($($x:expr),*) => {
0 $( + $x )*
};
}
fn main() {
println!("{}", sum_all!(1, 2, 3));
}This prints 6. The $x sits inside $( ... )*, so it repeats as it was captured. If you wrote 0 + $x outside the repetition, the compiler would report that x is still repeating at this depth.
Calling sum_all!(1; 2) gives a "no rules expected" error pointing at the ;. The compiler is telling you that after 1 it could accept a , or the end of input, and nothing else.
Fragment parsing commits early
When a matcher reaches an expr, ty, or similar fragment, the compiler runs its real parser on the input. If the first token cannot start such a fragment, the rule is skipped quietly and the next rule is tried. If the token can start one but the syntax goes wrong partway, the error is reported immediately, and later rules are never tried. This is why a catch-all tt rule cannot rescue a malformed expression. The fatal error comes from the earlier rule.
When the wrong rule matches
Sometimes nothing fails and the macro does the wrong thing. This happens when a general rule comes before a specific one.
macro_rules! describe {
($e:expr) => {
println!("expression: {}", stringify!($e))
};
($name:ident = $v:expr) => {
println!("assignment to {}", stringify!($name))
};
}
fn main() {
describe!(x = 5);
}This prints expression: x = 5. In Rust, x = 5 is itself a valid expression, so the first rule consumes the whole input and the second rule is dead code. The fix is to put the more specific rule first:
macro_rules! describe {
($name:ident = $v:expr) => {
println!("assignment to {}", stringify!($name))
};
($e:expr) => {
println!("expression: {}", stringify!($e))
};
}
fn main() {
describe!(x = 5);
describe!(1 + 2);
}Now the output is assignment to x followed by expression: 1 + 2.
Reading expansion errors
When matching succeeds and the generated code fails to compile, the error points at the invocation site, with a note such as "in this macro invocation" or "this error originates in the macro". Look at the line numbers in the note. The span of the real problem is often inside the transcriber, not at your call.
To debug this, use these steps:
- Run
cargo expandand find the code the macro produced. - Copy that code into a normal function or test file.
- Compile it by hand. The error is now an ordinary one, with ordinary line numbers.
- Fix the transcriber, then delete the copy.
Common causes are a missing semicolon or brace in the transcriber, a missing extra { } pair when the macro must expand to an expression with let statements, and a name that hygiene hid from the caller.
Recursion limits
The default recursion limit is 128. A recursive macro that peels one token per step hits it on inputs of about that many tokens. You can raise the limit at the crate root:
#![recursion_limit = "256"]Raising it hides a design problem when the macro recurses once per element. For long inputs, prefer a macro that handles several tokens per step, or use a repetition instead of recursion.
A debugging routine
Exercise
A macro has the rules ($e:expr) => { ... } first and ($a:ident, $b:ident) => { ... } second. You call it as pair!(left, right). Which rule runs, and what would you do to confirm it?
Show answer
The second rule runs. The first rule parses left as an expression, then finds a , where it expects the end of input, so that rule fails without a fatal error and matching continues with the next rule. To confirm it, run cargo expand and read the code generated at the call, or put stringify! in each transcriber to show which one was used.
Exercise
You write ($($x:expr),*) => { let v = vec![$x]; v } and the compiler says variable 'x' is still repeating at this depth. What is wrong, and how can you fix it?
Show answer
$x was captured inside a repetition but is used outside one. Wrap the use in a matching repetition, for example vec![$($x),*].