Sub topic 4
Fragment specifiers: expr, ident, ty, tt and more
This chapter assumes you can write a basic macro_rules! macro with several arms, and that you know Rust expressions, types, and identifiers. A fragment specifier tells the macro parser what kind of syntax a matcher variable captures.
What a fragment specifier does
In a matcher, $x:expr means "parse a Rust expression here and call it $x". The text after the colon is the fragment specifier. The compiler parses the input as that kind of syntax. If the input does not parse, the arm does not match.
The parsed fragment stays whole. This is why square!(2 + 3) below prints 25 and not 11. The argument is one expression, so the expansion multiplies two complete expressions.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}The common specifiers
| Specifier | Matches | Example input | Column |
|---|---|---|---|
| `expr` | An expression | `a + 1`, `foo()` | |
| `ident` | An identifier or keyword | `total`, `Point` | |
| `ty` | A type | `i32`, `Vec<String>` | |
| `tt` | One token tree | `+`, `foo`, `(a, b)` | |
| `pat` | A pattern | `Some(x)`, `1 \ | 2` |
| `stmt` | A statement without trailing semicolon | `let a = 1` | |
| `block` | A braced block | `{ a + b }` | |
| `item` | An item such as a function or struct | `fn f() {}` | |
| `path` | A path | `std::mem::swap` | |
| `literal` | A literal, optionally negative | `42`, `"hi"`, `-1` | |
| `lifetime` | A lifetime | `'a` | |
| `vis` | A possibly empty visibility | `pub`, `pub(crate)` | |
| `meta` | The contents of an attribute | `derive(Debug)` |
Choosing between them
Pick the narrowest specifier that fits. It gives clearer errors and keeps rules from matching input you did not intend.
- Use
exprwhen the caller supplies a value to compute. - Use
identwhen the caller supplies a name, such as a variable, field, or function name. - Use
tywhen the caller supplies a type. - Use
ttwhen you need to accept almost anything, or when you want to inspect tokens yourself.
ident: names from the caller
An ident lets the caller choose a name that is visible after expansion. This macro introduces a binding with a caller-chosen name.
macro_rules! make_var {
($name:ident, $val:expr) => {
let $name = $val;
};
}
fn main() {
make_var!(answer, 42);
println!("{}", answer);
}ty: types in generated code
The ty specifier is useful when generating items. Here ident and ty combine in a repetition, which the next chapter covers in detail.
macro_rules! make_struct {
($name:ident { $($field:ident : $ty:ty),* $(,)? }) => {
#[derive(Debug)]
struct $name {
$($field: $ty),*
}
};
}
make_struct!(Point { x: i32, y: i32 });
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
}tt: the catch-all
A token tree is either a single token or a group of tokens inside matching (), [], or {}. The brackets and everything inside them count as one tt. This makes tt the most flexible specifier, and it is the basis of recursive macros.
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}
fn main() {
println!("{}", count!(a b c));
}Each step takes one token tree off the front and expands to 1 + 1 + 1 + 0, which prints 3.
Common errors
- Once a fragment is parsed as
expr,ty, or similar, you cannot match it against literal tokens in a later macro call. It is an opaque unit. Onlyident,lifetime, andttcan be re-matched. Usettif you need to look inside. - Specifiers are tried in order, and a parse failure inside a fragment is a hard error. The compiler does not fall back to the next arm. Put more specific arms first.
- An
exprdoes not match a statement such aslet a = 1. Usestmtfor that. - Restrictions apply to what may follow a fragment. For example,
exprcan only be followed by=>,,, or;. The follow-set chapter covers these.
Exercise
A macro has the arm ($x:expr) => { $x * 2 }. You call it as double!(1 + 2). What does it return, and which specifier would you change to get a different result, if any?
Show answer
It returns 6. The expr fragment is parsed as one expression, 1 + 2, and stays grouped, so the result is (1 + 2) * 2. Changing $x to tt would not compile for this input, because 1 + 2 is three token trees and a single tt captures only the first.
Exercise
You want a macro new_fn!(name, i32) that generates a function called name returning a value of type i32. Which specifiers do you use for the two arguments?
Show answer
Use $name:ident for the function name and $t:ty for the type, for example ($name:ident, $t:ty) => { fn $name() -> $t { Default::default() } };.