8 Rust Macro Techniques That Fix Broken Arms, Hygiene Bugs, and Expansion Errors for Good
Master Rust declarative macros with 8 practical techniques covering arm ordering, hygiene, $crate, and debugging with cargo expand.
The first time I wrote a Rust macro, I felt like a wizard. Twelve characters of syntax, and suddenly my code was writing more code for me. The second time I wrote one, I broke it. I added a new pattern at the top of my rule list, and every other pattern underneath stopped firing. I spent an entire evening staring at my screen before I realized the new arm was too greedy and had swallowed everything below it.
That night taught me the one idea that makes declarative macros click. A macro_rules! block is not a function. It is a match statement that runs at compile time. You give it a list of patterns, Rust tries them from top to bottom, and the first one that fits wins. Everything else is a detail on top of that. Once I accepted this, the eight techniques below stopped feeling like folklore and started feeling like common sense.
Order your arms from specific to general, always. This is the rule I broke that night. Here is what I wrote, roughly, and why it failed.
macro_rules! describe {
($($rest:tt)*) => { "something else" }; // too greedy
(0) => { "zero" };
($n:expr) => { "some number" };
}
The first arm matches literally anything, so the second and third arms are dead code. Rust never complains, because a macro is allowed to have unreachable arms. The fix is to move the catch-all to the bottom.
macro_rules! describe {
(0) => { "zero" };
($n:expr) => { "some number" };
($($rest:tt)*) => { "something else" };
}
Now describe!(0) returns "zero", describe!(42) returns "some number", and describe!(foo bar) returns "something else". The order matters because of the first-match-wins rule, and the first-match-wins rule matters because a token-tree pattern can match almost anything.
The second technique is picking fragment specifiers on purpose. A fragment specifier is the little tag after a dollar sign that tells the parser what kind of token to expect. $x:expr wants an expression. $x:ident wants a single identifier. $x:ty wants a type. $x:path wants a path like std::mem::swap. $x:pat wants a pattern. $x:literal wants a literal. $x:block wants a braced block. $x:stmt wants a statement. $x:tt wants a single token tree, which is anything in parentheses, brackets, or braces, or any single token.
I used to reach for tt every time because it felt safe. That is a trap. A pattern of $x:tt matches a single token, so it will not match 1 + 2 as a unit. It matches 1 and then the + becomes a separate token in your stream, which is almost never what you want. The correct choice is expr for values, ident for names, and tt only when you genuinely want to capture something without understanding it.
There is a subtlety with expr. It is greedy. If you write a rule where $x:expr is followed by a +, the parser may not know where the expression ends and the operator begins. The classic failure looks like this.
macro_rules! bad {
($e:expr + $rest:expr) => { $e + $rest };
}
// bad!(1 + 2 + 3) // parse error: the first expr eats too much
The first $e:expr happily consumes 1 + 2, and then the pattern has no + left to match. The fix is to change the fragment specifier or to wrap the sub-expression in parentheses at the call site. This is why so many real macros ask you to write (1 + 2) instead of 1 + 2. It is not a design flaw. It is the parser being predictable.
When an arm refuses to match and you cannot see why, the fragment specifier is almost always the suspect. Change it to tt and see if the arm starts matching. If it does, you now know the shape of your problem.
The third technique is building repetition with separators, and tolerating a trailing comma. Repetition in a declarative macro uses $(...)* or $(...),*, with the separator between the closing paren and the star. The $(,)? trick at the end makes a trailing comma optional.
macro_rules! names {
($($name:expr),* $(,)?) => {
vec![$(String::from($name)),*]
};
}
Now names!("a", "b") and names!("a", "b",) both compile. That trailing comma looks like a small thing until you write a macro that takes ten arguments and someone wants to add an eleventh on a new line. Supporting it costs you six characters and it earns you a hundred thank-yous.
I like to use square brackets for list-style macros because the call site reads better. names!["a", "b", "c"] looks like a list. names!("a", "b", "c") looks like a function call. The delimiters are interchangeable as far as the macro is concerned, so pick the one that signals intent to the reader.
The fourth technique is something with an intimidating name that hides a simple idea. It is called recursive TT munching, and it is how you fold a variable-length list into a single value using nothing but macro rules.
The problem is that Rust’s repetition syntax has no accumulator. $(...)* produces a sequence of expansions, not a sum. If you want to add up ten numbers at compile time, you peel them off one at a time.
macro_rules! sum_all {
() => { 0 };
($head:expr $(, $tail:expr)*) => { $head + sum_all!($($tail),*) };
}
let total = sum_all!(1, 2, 3, 4); // expands to 1 + 2 + 3 + 4 + 0
The base case matches an empty token stream and returns 0. The recursive case takes the first expression, then calls itself with the rest. Each recursive call strips one item off the front. The compiler expands this eagerly until the base case is reached. The practical limit is the compiler’s recursion depth, which is generous but not infinite. For most macro use, it is more than enough.
I use this pattern for building typestate chains, constructing fixed-size arrays, and generating match arms for enum variants. Every time, the shape is the same: one arm peels the head, one arm handles the empty tail.
The fifth technique is keeping internal rules in a namespace the caller cannot reach. Any macro that supports optional arguments or defaults needs helper arms. The trick is to prefix them with @ or @impl so they stand apart from the public surface.
macro_rules! connect {
(@default) => { 8080 };
($host:expr) => { connect!($host, connect!(@default)) };
($host:expr, $port:expr) => {
// real implementation here
};
}
A caller writes connect!("localhost") or connect!("localhost", 9000). The @default arm is visible in the source, but the @ prefix is a convention that says do not use this. A caller who writes connect!(@default) gets the default port back, which is harmless, but they would never do that because the documentation says not to.
Some macro authors use a second internal macro instead of the @ trick. I prefer @ because it keeps everything inside one macro_rules! block. Fewer moving parts, fewer places for a bug to hide.
The sixth technique is referencing your own crate’s items through $crate. This one prevents a class of bug that is nearly impossible to debug from the outside.
When you export a macro from a library with #[macro_export], that macro expands in the caller’s crate. The caller’s scope is not your scope. Your types are not in their modules. Your imports are not in their imports. A bare name like Level::Error might refer to their Level, not yours, or might not resolve at all.
$crate solves this. It expands to the path of the crate that defined the macro, regardless of where the macro is called.
#[macro_export]
macro_rules! log_error {
($msg:expr) => {
$crate::logging::record($crate::Level::Error, $msg)
};
}
A user in any crate can call log_error! ("something went wrong") without importing logging or Level. The macro carries its own context with it. Every time I have forgotten $crate, I have shipped a release that failed to compile for somebody else. Every time I have remembered it, nothing went wrong.
The habit is cheap. Get into it on the first macro you write and never break it.
The seventh technique is understanding what hygiene does and does not protect. Hygiene is Rust’s way of keeping variables introduced inside a macro from colliding with variables at the call site.
macro_rules! double {
($x:expr) => {{
let y = $x;
y + y
}};
}
fn main() {
let y = 10;
println!("{}", double!(y)); // 20, not a collision
}
The y inside the macro and the y at the call site are different variables. This is hygiene at work. The macro’s y is invisible to the caller, and the caller’s y is invisible to the macro.
But hygiene is partial. It only protects local variables and labels. It does not protect item names, type names, method calls, or trait imports. If your macro writes Vec::new(), it uses whatever Vec is in scope at the call site. If the caller has redefined Vec, your macro uses their version.
macro_rules! make_thing {
() => { Thing::new() }; // Thing must be in scope at the call site
}
The fix is either to fully qualify the path with $crate:: or to accept that your macro expects certain names to be in scope and document that requirement. Most library macros choose the first option. It is safer and it makes the crate self-contained.
The rule I follow is simple. Anything I write inside a macro that is not a local variable is public surface. Treat it with the same care you treat a public function signature.
The eighth technique is inspecting your expansions and locking down their behavior with tests. Reading the expanded output is the fastest way to debug a stubborn macro. cargo expand is the tool I use for this. It runs the compiler’s expansion pass and prints the result.
cargo install cargo-expand
cargo expand --bin my_project
The output shows what every macro in your crate turned into. If an arm is firing when it should not, the expansion tells you why. If an arm is not firing at all, the expansion tells you what actually ran instead. I have solved more macro bugs with cargo expand than with any other technique on this list.
For testing, the trybuild crate runs compile-fail cases and compares the compiler’s error output to a snapshot. This protects your macro’s diagnostics the same way assert_eq! protects its results.
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/*.rs");
}
Each file in tests/ui/ contains code that should fail to compile, along with a matching .stderr file that captures the expected error. When the compiler changes its wording, trybuild tells you. When your macro starts accepting input it should reject, trybuild tells you that too.
If the generated code itself is the contract, macrotest lets you snapshot the expansion, so you can compare it against a known-good version. That is a heavier tool, and I only reach for it when the macro generates something that is part of my public API.
The goal of all eight techniques is the same. I want a macro whose rules read as documentation of the syntax it accepts, whose errors point at the caller’s mistake, and whose internals stay out of sight. A macro that reads like a small language of its own is a pleasure to use. A macro that reads like a puzzle is a maintenance burden that nobody wants to inherit.
I wrote my first macro because I wanted to avoid writing a hundred similar functions by hand. I kept writing them because the syntax is expressive and the compile-time error messages, when the macro is written carefully, are better than what a hand-written function would give me. The eight techniques above are what I wish someone had told me on day one, before I spent a night staring at a screen wondering why my arms had stopped firing.
Start with the ordering rule. Add the $crate habit immediately. Learn cargo expand early. Everything else follows from there, and one day you will look at a macro_rules! block and see a match statement instead of a mystery.