Sub topic 3
Writing rules: matchers and multiple arms
This chapter assumes you can define and call a basic macro_rules! macro. It also assumes you know what an expression, an identifier, and a type are in Rust. Here you will learn how a macro with several rules chooses between them, how literal tokens and delimiters in a matcher behave, and why the order of your arms matters.
Anatomy of a rule
A macro_rules! definition is a list of rules, which the Rust reference calls arms. Each rule has a matcher on the left of => and a transcriber on the right. Rules are separated by semicolons.
macro_rules! name {
(matcher one) => { transcriber one };
(matcher two) => { transcriber two };
}- The matcher describes the tokens the caller may write. It is a pattern over tokens, not over values.
- The transcriber is the code the macro produces when its matcher succeeds.
- The semicolon after the last rule is optional.
- The delimiters around a matcher or a transcriber can be
(),[], or{}. They are equivalent, and most code uses()for matchers and{}for transcribers.
The compiler does not run a macro at runtime. It tries to match the tokens inside the invocation against each matcher. It expands the first matcher that fits and discards the rest.
How the compiler picks an arm
Matching proceeds from the first arm to the last. The first arm that matches the whole input wins. Later arms are never examined for that call.
Here is a macro with three arms that match three different shapes of input.
macro_rules! describe {
() => {
"empty"
};
(zero) => {
"the word zero"
};
($x:expr) => {
"some expression"
};
}
fn main() {
println!("{}", describe!());
println!("{}", describe!(zero));
println!("{}", describe!(1 + 2));
}This prints:
empty
the word zero
some expressiondescribe!()has no tokens, so only the first arm fits.describe!(zero)contains the identifier tokenzero. The second arm matches it literally.describe!(1 + 2)fails the first two arms, so the third arm parses it as one expression.
Order matters: specific arms first
Putting a broad arm before a narrow one hides the narrow one. Swap the last two arms of describe!:
macro_rules! describe_wrong {
() => {
"empty"
};
($x:expr) => {
"some expression"
};
(zero) => {
"the word zero"
};
}
fn main() {
println!("{}", describe_wrong!(zero));
}This prints some expression. The bare identifier zero is a valid expression (a path to a name), so the $x:expr arm matches first. The (zero) arm can never run.
Literal tokens in matchers
Anything in a matcher that is not a $name:fragment capture or a repetition must appear in the input exactly. This includes identifiers used as keywords, punctuation, and literals. Literal tokens are how you give a macro its own mini-syntax.
macro_rules! calc {
(add $a:expr, $b:expr) => {
$a + $b
};
(mul $a:expr, $b:expr) => {
$a * $b
};
(neg $a:expr) => {
-$a
};
}
fn main() {
println!("{}", calc!(add 2, 3));
println!("{}", calc!(mul 2 + 1, 4));
println!("{}", calc!(neg 7));
}This prints 5, 12, and -7.
add,mul, andnegare plain identifiers, but in a matcher they act as keywords. The input must contain that exact word.- The comma is also a literal token.
calc!(add 2 3)does not match. mul 2 + 1, 4gives 12 because$acaptures the whole expression2 + 1as one unit. The transcriber does not paste it as raw tokens, so the product is(2 + 1) * 4.
Punctuation such as => can also be a literal separator:
macro_rules! kv {
($k:expr => $v:expr) => {
($k, $v)
};
}
fn main() {
let pair = kv!("port" => 8080);
println!("{:?}", pair);
}This prints ("port", 8080). The compiler only allows certain tokens to follow each fragment type. => and , are always allowed after expr. The follow-set rules chapter covers the full list.
Delimiters inside a matcher
The delimiters around the whole invocation do not matter. These calls are the same to the compiler:
macro_rules! unit {
() => {
()
};
}
fn main() {
let a = unit!();
let b = unit![];
let c = unit! {};
println!("{:?} {:?} {:?}", a, b, c);
}Delimiters inside a matcher are part of the pattern, though. A bracketed group in the matcher must appear as a bracketed group in the input:
macro_rules! pair_sum {
([$a:expr, $b:expr]) => {
$a + $b
};
}
fn main() {
println!("{}", pair_sum!([1, 2]));
}This prints 3. Calling pair_sum!((1, 2)) fails, because the matcher requires square brackets inside the outer parentheses. The compiler treats each delimited group as a single token tree, so a mismatch in the delimiter kind is a mismatch in the pattern.
The whole input must match
An arm matches only if it consumes every token of the invocation. Leftover tokens make the arm fail, and the compiler moves on to the next arm. If every arm fails, you get an error like this:
error: no rules expected the token `3`The wording varies a little between compiler versions, but it always starts with "no rules expected". The error points at the first token that no arm could accept. For calc!(add 2 3), that token is the stray 3 after 2.
When a fragment fails to parse
A fragment capture such as $x:expr does more than compare tokens. It runs the real Rust parser on the input at that position. This leads to two behaviors.
- If the next token cannot even start that kind of fragment, the arm simply fails and the compiler tries the next one. A macro with arms
($x:expr)and(struct $n:ident)handlesstruct Foocorrectly, becausestructcannot begin an expression. - If the token can start the fragment but the parser then finds a syntax error, the macro matcher cannot recover. The compiler reports that parse error and does not try later arms. An example is
1 +matched against$x:expr, because the parser starts an expression and then finds nothing after the+.
The practical lesson is that the matcher cannot back up after a fragment has begun parsing. Design your arms so each one can be told apart from the others by its first token or two, ideally a literal keyword. A related rule applies to repetitions: the parser has to decide what to do at each step without looking ahead, which is why the follow-set rules exist.
Using several arms as an interface
Multiple arms let one macro name accept several call shapes, much like function overloading. A common layout is:
- The empty or simplest case first.
- Arms that begin with distinct keywords next.
- The general catch-all arm last.
The next example follows that layout. It builds a label from zero, one, or two parts:
macro_rules! label {
() => {
String::from("unnamed")
};
(id $n:expr) => {
format!("item-{}", $n)
};
(id $n:expr, tag $t:expr) => {
format!("item-{}-{}", $n, $t)
};
($s:expr) => {
String::from($s)
};
}
fn main() {
println!("{}", label!());
println!("{}", label!(id 7));
println!("{}", label!(id 7, tag "x"));
println!("{}", label!("custom"));
}This prints unnamed, item-7, item-7-x, and custom.
Consider label!(id 7, tag "x"). The second arm (id $n:expr) parses 7 as an expression and then finds a comma where the arm expects the end of input. That arm fails, and the compiler tries the third arm, which consumes everything. That works because the earlier arm fails on a leftover token, not on a fatal parse error. This is why the shorter id arm can safely sit before the longer one.
Summary of matching rules
| Element in a matcher | What it matches | On failure |
|---|---|---|
| Literal token (`add`, `,`, `=>`, `0`) | That exact token | The arm fails and the next arm is tried |
| `$x:expr` and other fragments | Whatever the Rust parser accepts for that fragment | The arm fails if the token cannot start the fragment. A syntax error after it starts is fatal |
| Delimited group `[ ... ]` | A group with the same delimiter kind | The arm fails and the next arm is tried |
| End of matcher | End of the invocation input | Leftover tokens make the arm fail |
Exercise
Given the macro below, what does show!(go) print, and how would you change the macro so that show!(go) prints "keyword go"?
macro_rules! show {
($x:expr) => { "expr" };
(go) => { "keyword go" };
}
fn main() {
println!("{}", show!(go));
}
Show answer
It prints "expr". The identifier go is a valid expression (a path), so the first arm matches and the second arm is never tried. Moving the (go) arm above the ($x:expr) arm makes it print "keyword go", because arms are tried from top to bottom and the specific arm must come first.
Exercise
Why does calc!(add 2 3) fail to compile with the calc! macro from this chapter, and what does the error start with?
Show answer
The add arm requires a literal comma between the two expressions. After parsing 2 as $a, the matcher expects , but finds 3, so the arm fails. No other arm begins with add, so no arm matches, and the error starts with "no rules expected" and names the unexpected token 3.