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. Fragment specifiers such as $a:expr appear here without detail. The next chapter covers them.
Anatomy of a rule
A macro is a list of rules separated by semicolons. Each rule has two halves joined by =>:
- The matcher is the pattern on the left. It describes the tokens the caller may write.
- The transcriber is the code on the right. It describes what the compiler substitutes.
Both halves sit inside their own delimiters. These can be (), [], or {}, and the choice makes no difference to matching. The delimiters the caller uses at the call site are also free. vec![1] and vec!(1) mean the same thing.
Literal tokens and metavariables
A matcher mixes two kinds of items. Plain tokens, such as add or ,, must appear exactly as written. A metavariable, such as $a:expr, matches a piece of code and gives it a name for use in the transcriber.
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 4, 5));
println!("{}", calc!(neg 7));
}This prints 5, 20, and -7. The words add, mul, and neg are not keywords. They are literal tokens that select a rule.
How the compiler picks an arm
The compiler tries the rules from top to bottom. The first rule whose matcher fits the whole input wins. Later rules are never examined. If a rule fails partway through, the compiler discards its partial work and tries the next rule. If every rule fails, you get a compile error.
Order matters
Put specific rules before general ones. A general rule placed first will swallow input that a specific rule was meant to handle.
macro_rules! describe {
() => { "empty" };
(zero) => { "the word zero" };
($other:tt) => { "one token" };
($($rest:tt)*) => { "many tokens" };
}
fn main() {
println!("{}", describe!());
println!("{}", describe!(zero));
println!("{}", describe!(banana));
println!("{}", describe!(a b c));
}The output is empty, the word zero, one token, and many tokens. Now suppose the $other:tt rule came before (zero). The call describe!(zero) would then print one token, because a single tt matches zero first. The compiler doesn't warn you about this. The macro just gets the wrong answer.
The last rule uses $(...)*, which repeats a pattern. The chapter on repetitions explains it. Here it serves as a catch-all.
The no-match error
When no rule fits, the compiler reports the first token it could not place. Calling calc!(div 1, 2) fails like this:
error: no rules expected the token `div`The message points at where matching broke down. It does not name the rule you probably meant. When you see it, compare the input token by token against each matcher.
Rule hygiene for readers
- Separate rules with
;. The semicolon after the last rule is optional. - Write the empty-input rule
() => { ... }first. It is cheap to match and easy to read. - Keep a catch-all rule last. It can call
compile_error!("usage: calc!(add a, b)")to give callers a clear message instead of the generic one.
Exercise
A macro has two rules in this order: ($x:tt) => { "one" }; and (go) => { "go" };. What does calling the macro with go produce, and how do you get "go" instead?
Show answer
It produces "one". The compiler tries rules from top to bottom, and $x:tt matches the single token go first, so the second rule is never tried. Swap the two rules so the specific (go) rule comes before the general ($x:tt) rule.