Declarative macros
macro_rules! defines a declarative macro by matching token patterns and expanding a template. It is the tool behind vec! and most small helper macros you will write.
Detailed Explanation
macro_rules! my_vec { ( $( $x:expr ),* ) => { ... } } is the usual shape. The matcher on the left binds fragments: $x:expr is an expression, $name:ident is an identifier, $t:ty is a type. The repeater $( ... ),* matches zero or more copies separated by commas. The template on the right uses those bindings. The compiler tries each arm in order, first match wins.
Fragment specifiers are the type system of macro_rules. expr, ident, ty, path, tt (one token tree), block, item, lifetime cover most needs. Once something is captured as expr, you cannot reparse it as ident. That is why nested macros and "parse this as either a type or an expression" get painful, and why people graduate to procedural macros.
Hygiene means a let x inside the expansion is not the caller's x. If you want to use a name from the call site, the caller must pass it in. If you want to call an item in your crate, write $crate::module::item so the path works when the macro is exported and used elsewhere. Export with #[macro_export], which places the macro at the crate root.
Declarative macros are not functions. They have no types until after expansion. They can accept a variable number of arguments. They can generate impl blocks for a list of types, which is the impl_for_all! pattern that predates (and still complements) generic impls when the bodies differ.
What they cannot do well: parse attribute-like key-value lists with optional commas, compute, or look at type information. There is no if this type implements Debug in macro_rules. There is no arithmetic on 3. Repeaters and tt munchers are the workarounds, and they become unreadable.
When you write macro_rules!: vec!-style constructors, impl Trait for A, B, C, a logging wrapper that captures file and line. When the matcher becomes a parser, stop and write a proc macro. When a generic function would do, write the function.
Code Examples
macro_rules! max_of {
($x:expr) => { $x };
($x:expr, $( $rest:expr ),+) => {
{
let a = $x;
let b = max_of!($( $rest ),+);
if a > b { a } else { b }
}
};
}
fn main() {
println!("{}", max_of!(3, 9, 4)); // prints: 9
}Common Gotchas
First matching arm wins
Put the more specific arm above the catch-all `tt` muncher, or the specific arm will never run.
A captured `expr` cannot be reused as two expressions that both move
Bind it in the expansion: `let v = $x;`. Expanding `$x + $x` on a `String` tries to move twice.
`#[macro_export]` puts the macro at the crate root
Callers write `use your_crate::max_of;` not `use your_crate::macros::max_of;` unless you re-export by hand.
Use `$crate` in exported macros
A path like `crate::foo` inside the template looks up `foo` in the caller's crate, not yours.