Sub topic 14
Limits of macro_rules! and when to choose something else
This chapter assumes you can write multi-rule macro_rules! macros with fragment specifiers and repetitions, and that you know recursion and $crate. Here you learn where declarative macros stop being the right tool and what to use instead.
What macro_rules! cannot do
A macro_rules! macro matches token patterns and rewrites them. It has no way to inspect the program around it. These limits follow from that.
- It cannot read type information. A macro sees tokens, not types. It cannot ask whether
$timplementsDisplayor list the fields of a struct passed in elsewhere. - It cannot compute on tokens. There is no arithmetic on identifiers or literals. You cannot join
get_and a field name intoget_x. Thepastecrate does this. - It cannot generate new identifiers freely. Hygiene hides names the macro invents. Any name the caller must use has to come in as an
identargument. - It cannot be attached to an item. A declarative macro cannot be written as
#[my_macro]or#[derive(MyMacro)]. It is only called asname!(...). - Recursion has a cost. Counting by recursion expands once per token. Long inputs hit the default
recursion_limitof 128 and slow compilation.
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}
fn main() {
// Fine for a few tokens. A list of several hundred tokens would
// fail with "recursion limit reached while expanding `count!`".
println!("{}", count!(a b c d e));
}If you hit the limit, you can raise it with #![recursion_limit = "256"] at the crate root. That treats the symptom. Often a different design is better.
Error messages
When a rule fails to match, the compiler reports no rules expected the token. It does not say which rule you meant. Large macros with many arms give poor diagnostics, and errors inside the expansion point at the call site. If users of your macro will see these errors often, that is a reason to look elsewhere.
Alternatives
| Need | Better choice |
|---|---|
| Reuse logic over values | Function |
| Reuse logic over many types | Generic function or trait |
| Variable arguments, new syntax, or repeated items | `macro_rules!` |
| `#[derive(...)]` for a struct | Derive procedural macro |
| Attribute that rewrites an item | Attribute procedural macro |
| Parse arbitrary input or build identifiers | Function-like procedural macro |
A procedural macro is a Rust function that receives a token stream and returns one. It runs arbitrary Rust code at compile time, so it can parse a struct with the syn crate, build code with quote, and report errors with precise spans. The cost is that it must live in its own crate with proc-macro = true in Cargo.toml. It also adds dependencies and compile time.
Other options exist for narrower jobs:
- A
build.rsscript can generate source files before compilation, for example from a schema file. - Generics and traits often replace a macro that stamped out one function per type.
- Const generics and
const fncover many compile-time computations.
A practical rule
Start with a function. Move to generics if types vary. Use macro_rules! when the call syntax itself must be flexible, such as a variable number of arguments or a small domain-specific notation. Move to a procedural macro when you need to look inside a type definition or when the macro grows past a few readable arms.
Exercise
You want #[derive(Describe)] to print the field names of any struct. Can macro_rules! do this? If not, what should you use?
Show answer
No. A declarative macro is called as name!(...) and cannot be attached with #[derive] or read the fields of a separately defined struct. Write a derive procedural macro in a crate with proc-macro = true, parse the struct with syn, and generate the impl with quote.
Exercise
A recursive counting macro fails on a long token list with "recursion limit reached". Name two ways to respond.
Show answer
Raise the limit with #![recursion_limit = "256"], or redesign the macro to avoid one expansion per token, for example by using a repetition that expands in a single step, or by replacing the macro with a function or a procedural macro.