Sub topic 2
Your first macro_rules! macro
This chapter builds a working declarative macro from scratch and names each part of it. It also shows what the compiler does when you invoke one. I assume you can write Rust functions, structs, and let bindings, and that you can use println! and run a project with Cargo. I also assume you know what an expression, a type, and an identifier are. The earlier chapter covered why macros exist. Here the goal is to write one and watch it expand.
The smallest possible macro
A declarative macro is defined with macro_rules!, followed by the macro's name and a body in braces. The body holds one or more rules. This macro has a single rule that takes no input:
macro_rules! say_hello {
() => {
println!("Hello from a macro!");
};
}
fn main() {
say_hello!();
}Running this prints Hello from a macro!.
A rule has two halves separated by =>:
- The matcher is on the left, here
(). It describes the tokens the caller may write between the macro's delimiters. An empty matcher accepts an empty invocation. - The transcriber is on the right, here
{ println!(...); }. It is the code that replaces the invocation.
The outer braces of the transcriber are not part of the output. They only mark where the transcriber starts and ends. Everything inside is what the compiler pastes into your program.
A semicolon follows each rule. It is required between rules and optional after the last one, but writing it after every rule is the common style.
Invoking a macro
You invoke a macro by writing its name, a !, and a delimited group of tokens. All three delimiter styles are allowed, and they mean the same thing to the macro:
macro_rules! say_hello {
() => {
println!("Hello from a macro!");
};
}
fn main() {
say_hello!();
say_hello![];
say_hello! {}
}By convention, parentheses are used for most macros, square brackets for collection-like macros such as vec![], and braces for macros that define items. Braces matter for one practical reason. An invocation in statement position that uses braces needs no trailing semicolon, as the last line above shows.
A macro that takes an argument
A macro without input is not very useful, so here is one that takes an expression:
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}This prints 25.
The matcher $x:expr has two parts. $x is a metavariable, a name that the macro binds to part of the input. expr is a fragment specifier. It tells the compiler to parse that part of the input as one complete expression. The next chapters cover the other specifiers.
In the transcriber, $x stands for whatever expression was captured. Because 2 + 3 was parsed as a single expression, the expansion behaves like (2 + 3) * (2 + 3). It does not behave like 2 + 3 * 2 + 3, which would give 11. The compiler keeps the captured expression as one unit in the syntax tree, so operator precedence does not leak across the boundary. This is the main difference from textual macros such as the C preprocessor's.
What the compiler does with an invocation
Macro expansion happens during compilation, before type checking. The compiler does not run your macro as a function. It matches tokens against patterns and substitutes the result into the syntax tree.
Three consequences follow from this model:
- Macros are checked twice. The macro definition is only checked for basic syntax errors when it is defined. Type errors in the transcriber show up at the call site, after expansion.
- Rules are tried in order. The first rule whose matcher fits is used. If none fits, you get a compile error. With one rule there is nothing to order, but the next chapter relies on this.
- The result must parse in its position. The expansion has to be valid where you invoked the macro. For example,
square!(4)in expression position must expand to an expression.
Works with any type that supports `*`
A function fn square(x: i32) -> i32 accepts only i32. The macro does not mention any type. It pastes $x * $x into your code, and the type checker then verifies the result:
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(7));
println!("{}", square!(1.5));
println!("{}", square!(3u8));
}This prints 49, 2.25, and 9. Calling square!("text") fails with a normal type error such as "cannot multiply &str by &str", reported at the invocation site.
A common gotcha: the expression is evaluated twice
Substitution is not the same as passing an argument. The transcriber contains $x twice, so the captured expression appears twice in the expansion. If the expression has side effects, they happen twice:
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
let mut n = 0;
let mut next = || {
n += 1;
n
};
println!("{}", square!(next()));
}This prints 2, not 1. The expansion is next() * next(), which evaluates 1 * 2. A function would call next() once, because arguments are evaluated before the call.
The usual fix is to bind the value once inside the transcriber:
macro_rules! square {
($x:expr) => {{
let value = $x;
value * value
}};
}
fn main() {
let mut n = 0;
let mut next = || {
n += 1;
n
};
println!("{}", square!(next()));
}This prints 1. The transcriber now has two pairs of braces. The outer pair delimits the transcriber, as before. The inner pair makes the expansion a block expression, so the let statement and the final value * value form one expression. Without the inner braces, the expansion would be a statement followed by an expression, which cannot appear where a single expression is expected.
Where the expansion can appear
The same macro name can be used in several positions, and the compiler parses the expansion according to the position:
| Invocation position | Expansion parsed as |
|---|---|
| Right side of `let x = ...;` | An expression |
| A line of its own in a function body | Zero or more statements |
| At module level | Zero or more items |
| After `:` in a type position | A type |
A macro can therefore define a variable when it is called as a statement:
macro_rules! make_var {
($name:ident, $val:expr) => {
let $name = $val;
};
}
fn main() {
make_var!(answer, 42);
println!("{}", answer);
}This prints 42. The macro expands to a statement, so it works on a line of its own. It would fail inside an expression such as let y = make_var!(z, 1);, because let is not an expression. The identifier answer is visible after the call because the caller wrote it. The hygiene chapter explains why names the macro invents itself are treated differently.
Definition order and scope
Unlike functions, a macro_rules! macro must be defined before the code that uses it, in the order the compiler reads the file. This fails:
fn main() {
say_hello!();
}
macro_rules! say_hello {
() => {
println!("hi");
};
}The compiler reports "cannot find macro say_hello in this scope". Moving the definition above main fixes it. A macro defined inside a module is visible only to the rest of that module unless you take further steps. A later chapter covers #[macro_export] and $crate, which control how macros cross module and crate boundaries.
Reading your first error
If an invocation does not fit any rule, the compiler reports the first token it could not match. With the one-rule square macro, square!(2, 3) produces an error like this:
error: no rules expected the token `,`The macro parsed 2 as the expression for $x, then found a comma where the matcher ended. An empty call, square!(), gives "unexpected end of macro invocation", because the matcher needed an expression and found nothing. In both cases the error points at the invocation, and the fix is usually to change either the call or the matcher. A later chapter covers reading these messages in more depth.
Summary of the parts
| Part | Example | Role |
|---|---|---|
| Name | `square` | What you call, followed by `!` |
| Matcher | `($x:expr)` | Pattern the input tokens must fit |
| Metavariable | `$x` | Name bound to the matched fragment |
| Fragment specifier | `expr` | How the input is parsed |
| Transcriber | `{ $x * $x }` | Code that replaces the call |
| Rule separator | `;` | Separates rules in the body |
Exercise
Write a macro named cube that returns its argument multiplied by itself three times. The argument must be evaluated only once. What does cube!(1 + 1) print when passed to println!("{}", ...)?
Show answer
Bind the value once inside a block transcriber:
macro_rules! cube {
($x:expr) => {{
let value = $x;
value value value
}};
}
fn main() {
println!("{}", cube!(1 + 1));
}
It prints 8. The expr fragment keeps 1 + 1 as one expression, so value is 2 and the result is 2 2 2. The inner braces make the expansion a single block expression, and the let binding ensures the argument is evaluated once.
Exercise
A macro is defined as macro_rules! shout { ($s:expr) => { println!("{}!", $s); }; }. What error does shout!("a", "b"); produce, and why?
Show answer
The compiler reports "no rules expected the token ,". The only rule's matcher is $s:expr, so the macro parses "a" as the expression and then finds a comma where the matcher has already ended. No other rule exists, so the invocation is rejected.