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. It also assumes you know hygiene, recursion, and #[macro_export] from the earlier chapters. Here you will learn what declarative macros cannot do, what each limit costs you in practice, and which tool to reach for instead.
What macro_rules! is good at
A macro_rules! macro matches token patterns and substitutes them into a template. It works well for:
- Removing repetitive syntax, such as
vec!-style constructors orimplblocks for many types. - Accepting a custom, small syntax inside a Rust program.
- Generating several similar items from one list.
The macro works on tokens, before the compiler has resolved names or types. Every limit in this chapter follows from that.
Limits you will hit
No access to types or semantic information
A macro sees Point as an identifier token. It does not know whether Point is a struct, what fields it has, or which traits it implements. The macro cannot read a struct definition elsewhere in the crate and generate code from it.
The next example shows both sides. The macro can repeat an impl for a list of types, because you supply the list. It cannot check whether each type is Display. If one is not, the error appears in the expanded code.
trait Describe {
fn describe(&self) -> String;
}
macro_rules! impl_describe {
($($t:ty),* $(,)?) => {
$(
impl Describe for $t {
fn describe(&self) -> String {
format!("{} is a {}", self, stringify!($t))
}
}
)*
};
}
impl_describe!(i32, u8, f64);
fn main() {
println!("{}", 5i32.describe());
println!("{}", 2.5f64.describe());
}This prints 5 is a i32 and 2.5 is a f64. If you add a type without Display, the compiler reports a missing trait bound inside the impl that the macro generated. The message points at the macro call site, which makes it harder to read than a normal error.
No computation on identifiers
A macro cannot join two identifiers into one, change case, or build a name like get_ plus a field name. Hygiene does not help here, because the macro simply has no operation for it. The usual fix is the third-party paste crate, which provides a paste! macro with [<get_ $name>] syntax. Without it, you must make the caller pass every final name:
macro_rules! getter {
($getter:ident, $field:ident, $t:ty) => {
fn $getter(&self) -> $t {
self.$field
}
};
}
struct Counter {
value: u32,
}
impl Counter {
getter!(get_value, value, u32);
}
fn main() {
let c = Counter { value: 7 };
println!("{}", c.get_value());
}The caller writes get_value and value separately. That duplication is the cost of having no way to join identifiers.
No arithmetic or general-purpose logic
A macro cannot add numbers, compare them, or loop with a counter. It can only match and rewrite tokens. Counting items is therefore done by recursion (the count! macro from the recursion chapter) or by a trick that moves the counting into ordinary Rust:
macro_rules! replace_with_unit {
($_t:tt) => {
()
};
}
macro_rules! count {
($($x:tt)*) => {
<[()]>::len(&[$(replace_with_unit!($x)),*])
};
}
fn main() {
println!("{}", count!(a b c d e f g h));
}This prints 8. The macro turns each token into (), builds an array of that many units, and asks for its length. The expansion is flat, so it does not hit the recursion limit.
Recursion depth and compile time
The compiler limits macro expansion depth. The default is 128. A tail-recursive macro that peels one token per step fails on long input with an error such as recursion limit reached while expanding. You can raise the limit with a crate-level attribute:
#![recursion_limit = "256"]
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}
fn main() {
println!("{}", count!(a b c));
}Raising the limit only moves the wall. Each recursive step re-parses the remaining tokens, so a macro that consumes N tokens one at a time does work proportional to N squared. For long lists, prefer a flat repetition such as $( ... )*, or process several tokens per step.
Weak error messages
When no rule matches, the compiler reports no rules expected the token. It points at the first token that failed in the last rule it tried, not at your intent. A macro with a custom syntax cannot give a tailored message like "expected a field name after the colon". It can only add a final catch-all rule that calls compile_error!:
macro_rules! checked_square {
($x:expr) => {
$x * $x
};
($($other:tt)*) => {
compile_error!("checked_square! takes exactly one expression")
};
}
fn main() {
println!("{}", checked_square!(4));
}This prints 16. Calling checked_square!(1, 2) would fail with your message rather than a parser error. This improves messages for known mistakes but does not fix the general problem.
Hygiene is partial
Hygiene covers local variables and labels. It does not cover items such as functions, structs, and statics. A macro that defines fn helper() can collide with a function of the same name at the call site. Types and paths also resolve at the call site, so a bare HashMap in a template can fail where the caller has not imported it. Use full paths like ::std::collections::HashMap and $crate:: for your own items, as shown in the scoping chapter.
Tooling
Editors and debuggers see expanded code, but not always cleanly. Autocomplete inside macro arguments is limited. Breakpoints and backtraces refer to the expansion site. Large macros are harder to test than functions, so test through the code they generate.
Alternatives to macro_rules!
Each limit above has a different remedy. The right choice depends on what you actually need.
| Need | Better tool | Why |
|---|---|---|
| Reuse logic over values | A plain function | Type-checked at the definition, clear errors, easy to test. |
| Reuse logic over many types | Generics and traits | The compiler checks bounds once, not per expansion. |
| Compile-time computation | `const fn`, `const` items, const generics | Real arithmetic and control flow at compile time. |
| Derive code from a struct's fields | A derive procedural macro | It receives the full parsed definition. |
| Add behaviour to an item with arguments | An attribute procedural macro | It can read and rewrite the whole annotated item. |
| Custom syntax with real parsing | A function-like procedural macro | You write a parser in Rust and report precise errors. |
| Code from external files or schemas | `build.rs` code generation | It runs before compilation and can read any file. |
| Joining or changing identifiers | `paste` crate | Fills the one gap `macro_rules!` has. |
Choosing a function or generic code first is a good default. A macro adds cost for every reader and for the compiler.
A procedural macro for comparison
A derive macro receives the parsed item, so it can read the type's name, fields, and generics. Procedural macros must live in their own crate with proc-macro = true.
[package]
name = "type_name_derive"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = "2"
quote = "1"use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(TypeName)]
pub fn derive_type_name(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let name = &ast.ident;
let text = name.to_string();
quote! {
impl #name {
pub fn type_name() -> &'static str {
#text
}
}
}
.into()
}Applying #[derive(TypeName)] to struct Point { x: i32 } adds Point::type_name(). This sketch ignores generics. A production derive would split them with ast.generics.split_for_impl(). The trade-offs:
- Power: it can inspect every field, attribute, and generic parameter, and it emits errors at exact spans.
- Cost: it needs a separate crate, the
synandquotedependencies, and longer clean builds. - Testing: you can test the generated code and the parsing logic with ordinary Rust tests.
Summary of trade-offs
macro_rules!has no type information, no identifier manipulation, no arithmetic, and a recursion limit.- Error messages point at the call site and often name the wrong cause.
compile_error!improves known cases. - Procedural macros,
build.rs, generics, andconst fneach cover part of whatmacro_rules!cannot. - A function is the default. A declarative macro is the next step. A procedural macro is for jobs that need to read the input item.
Exercise
You need a macro that, given struct User { id: u32, name: String }, generates a method field_names() returning ["id", "name"] without the caller listing the fields a second time. Can macro_rules! do this when applied to a separate existing struct? What would you use?
Show answer
No. A declarative macro invoked as #[something] struct User {...} cannot exist, and a separate call like field_names!(User) cannot look up the fields of a struct defined elsewhere, because macros see only the tokens they receive and not type definitions. A macro_rules! macro could work only if it also defined the struct, with the caller writing the field list inside the macro invocation. To read an existing struct, use a derive procedural macro, which receives the parsed struct and can iterate over its fields.
Exercise
A recursive macro that counts tokens one at a time fails with "recursion limit reached" on a list of 200 items. Give two ways to fix it, and say which is better.
Show answer
Raise the limit with #![recursion_limit = "256"] at the crate root, or rewrite the macro so the expansion is flat, for example by turning each token into () and taking the length of the resulting array with <[()]>::len(&[...]). The flat rewrite is better, because raising the limit still leaves expansion work that grows with the square of the input size and the limit can be hit again with longer lists.