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, patterns, and items. It covers what each fragment specifier matches, what it does to the tokens it captures, and which errors come from choosing the wrong one.
What a fragment specifier does
A matcher variable has the form $name:specifier. The specifier tells the macro parser which piece of Rust grammar to parse at that position. A specifier is not a regular expression over text. The compiler runs its real parser for that grammar and binds the result to $name.
This has two consequences you will meet repeatedly:
- The captured fragment is a single syntax node.
$x:exprbound to2 + 3is one expression, not three tokens. - Most captured fragments are opaque. After capture, the macro can only paste them back or pass them to another macro as a whole. It cannot take them apart with later matchers, except for
ident,lifetime, andtt.
The specifiers at a glance
| Specifier | Matches | Example input | Column | Column |
|---|---|---|---|---|
| `expr` | An expression | `a + 1`, `foo(2)`, `if c { 1 } else { 2 }` | ||
| `ident` | An identifier or keyword (not `_`) | `counter`, `self` | ||
| `ty` | A type | `i32`, `Vec<String>`, `&'a str` | ||
| `pat` | A pattern (with top-level `\ | ` in edition 2021 and later) | `Some(x)`, `1 \ | 2` |
| `pat_param` | A pattern without top-level `\ | ` | `Some(x)` | |
| `stmt` | A statement without a trailing semicolon | `let x = 1` | ||
| `block` | A block expression | `{ a; b }` | ||
| `item` | An item | `fn f() {}`, `struct S;` | ||
| `path` | A path as used in types or expressions | `std::fmt::Debug` | ||
| `meta` | The contents of an attribute | `derive(Debug)`, `cfg(test)` | ||
| `lifetime` | A lifetime | `'a`, `'static` | ||
| `vis` | A possibly empty visibility | `pub`, `pub(crate)`, nothing | ||
| `literal` | A literal, optionally with a leading `-` | `42`, `-1.5`, `"hi"` | ||
| `tt` | A single token tree | `foo`, `+`, `( ... )`, `[ ... ]` |
expr: whole expressions
The expr fragment parses a complete expression and keeps it grouped. The square example from the plan shows why that matters.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}This prints 25. If macros pasted raw text, 2 + 3 * 2 + 3 would give 11. Because $x is a parsed expression, the compiler treats each use as one node, as if it were wrapped in parentheses.
An expr fragment is evaluated wherever you paste it. If the transcriber uses $x twice, the expression runs twice. A call like square!(next()) calls next() two times. Bind it first when that matters:
macro_rules! square_once {
($x:expr) => {{
let v = $x;
v * v
}};
}
fn main() {
let mut n = 0;
let mut next = || { n += 1; n + 1 };
println!("{}", square_once!(next()));
}This prints 4, and next runs once.
Expressions and statements
A bare expr cannot match something like let x = 1, because a let binding is a statement. It also does not accept an empty input. Use stmt for statements and $(...)? when an expression is optional.
ident: names you choose and names you read
An ident matches one identifier token. Keywords such as self and fn also match, but _ does not. Identifiers are the main tool for letting callers name things.
macro_rules! make_var {
($name:ident, $val:expr) => {
let $name = $val;
};
}
fn main() {
make_var!(answer, 42);
println!("{}", answer);
}This works because the caller wrote answer, so the name carries the caller's hygiene context and is visible after expansion. Chapter on hygiene covers the rules in full. For now, remember that a name written inside the macro body is not visible outside, but a name that came in as ident is.
An ident is also useful for pairing with a field or function name:
macro_rules! getter {
($field:ident : $ty:ty) => {
fn $field(&self) -> &$ty {
&self.$field
}
};
}
struct User { name: String }
impl User {
getter!(name: String);
}
fn main() {
let u = User { name: "Ada".to_string() };
println!("{}", u.name());
}Here the same $field becomes both a method name and a field access. Note that macros cannot build new identifiers by joining pieces, such as turning name into get_name. That needs a procedural macro or an external crate.
ty: types
A ty fragment parses any type, including generics, references, tuples, and function pointers.
macro_rules! default_of {
($t:ty) => {
<$t as Default>::default()
};
}
fn main() {
let a = default_of!(i32);
let b = default_of!(Vec<u8>);
let c = default_of!((bool, String));
println!("{} {:?} {:?}", a, b, c);
}The <$t as Default> form is the safe way to use a captured type in an expression. Writing $t::default() fails for types like Vec<u8> or tuples, because the path syntax does not accept them there.
pat and pat_param
The pat fragment matches a pattern. From edition 2021, pat accepts top-level alternatives such as 1 | 2. This can collide with a | separator in your matcher. Use pat_param when you need a pattern that stops before a top-level |.
macro_rules! is_match {
($value:expr, $pat:pat) => {
match $value {
$pat => true,
_ => false,
}
};
}
fn main() {
println!("{}", is_match!(Some(3), Some(1..=5)));
println!("{}", is_match!(7, 1 | 7));
}This prints true twice. In edition 2018, the second call would not parse as written, because pat stopped at the |.
stmt, block, and item
stmtmatches a statement and does not include the trailing semicolon. Add the semicolon in the transcriber.blockmatches{ ... }and is useful when you wrap user code, for example in a timing or logging macro.itemmatches a whole item, such as a function, struct, orimpl. It lets a macro take definitions as input and add to them.
macro_rules! with_log {
($body:block) => {{
println!("start");
let r = $body;
println!("end");
r
}};
}
macro_rules! pub_items {
($($i:item)*) => { $( $i )* };
}
pub_items! {
fn one() -> i32 { 1 }
struct Marker;
}
fn main() {
let v = with_log!({ one() + 1 });
println!("{}", v);
}path, meta, lifetime, vis, and literal
These narrower fragments exist so a macro can accept exactly one syntactic role.
pathacceptsstd::collections::HashMaporSelf::CONST. Use it for trait names and function paths.metaaccepts the inside of an attribute, so#[$m]can re-apply what the caller passed.lifetimeaccepts'a, which cannot be written as anident.vismay match nothing. Place it where a visibility could appear and it handles bothstruct Sandpub struct S.literalaccepts a literal only, which is stricter thanexpr.
macro_rules! make_struct {
($vis:vis struct $name:ident { $($fvis:vis $field:ident : $ty:ty),* $(,)? }) => {
#[derive(Debug)]
$vis struct $name {
$($fvis $field: $ty),*
}
};
}
make_struct!(pub struct Point { pub x: i32, y: i32 });
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
}Because vis can be empty, never wrap it in $(...)?. The macro already handles the empty case.
tt: the escape hatch
A tt is a token tree. It is either one token (an identifier, a literal, a punctuation mark) or a bracketed group ( ... ), [ ... ], { ... } with everything inside it. It is the loosest fragment: nearly any input matches, and it is never reparsed, so you can inspect it with later arms.
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}
fn main() {
println!("{}", count!(a b c));
}This prints 3. A tt is the right choice when you want to forward input unchanged, match your own mini-syntax, or recurse over input. Recursion is a later chapter.
Choosing a specifier
- Use the narrowest specifier that describes the role.
identfor names,tyfor types,exprfor values. - Use
ttwhen no grammar fits, or when you need to match literal tokens in later arms. - Remember that opaque fragments stay opaque. An
exprthat was captured cannot later match a literal pattern like0. Capture asttif you need to examine it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `no rules expected the token` | The input does not parse as the specifier, for example a `let` passed to `expr` | Use `stmt`, or change the arm order |
| `expected type, found ...` after pasting | A `ty` or `expr` used where the other is required | Match the specifier to the use site |
| Value computed twice | `$x:expr` used more than once | Bind it with `let` |
| `$t::new()` fails | A `ty` fragment in path position | Write `<$t>::new()` |
| Unexpected fragment-parse failure | The parser commits to a fragment once it starts | Put more specific arms first |
The last row matters. When the parser begins an expr, ty, or similar fragment and fails, it does not try the next arm. It reports an error. Put arms with literal tokens or narrower patterns before arms that start with a broad fragment.
Exercise
A macro is defined as macro_rules! twice { ($e:expr) => { $e + $e }; }. What does twice!(counter()) do if counter() increments a global and returns it, and how would you change the macro so it calls counter() once?
Show answer
It calls counter() twice, because the expression is pasted at both places. Bind it first: ($e:expr) => {{ let v = $e; v + v }};.
Exercise
You want describe!(Vec<u8>) to expand to code that calls Default::default() for that type. Which specifier do you use for the argument, and why is <$t as Default>::default() better than $t::default()?
Show answer
Use ty. The qualified form <$t as Default>::default() works for every type, including generics and tuples, while $t::default() puts a type where a path is expected and fails for some of them.
Exercise
Why does a matcher that uses $v:vis not need $(...)? around it?
Show answer
A vis fragment can match an empty input, so it already handles both a present and an absent visibility keyword.