Rust macros
A macro is code that writes code at compile time. macro_rules matches patterns of tokens and pastes them into a template. Procedural macros, like derive, are small Rust programs that read your struct and return new code, usually with the syn and quote crates. Macros remove boring repeated code, but they make builds slower and errors harder to read. A specialist tries functions, generics and traits first, and writes a macro only when they cannot do the job.
Author: bezzad
Contents
The problem: the same code twenty times
Our online shop sends events to a message queue: OrderPlaced, OrderPaid, OrderShipped, and about twenty more. Each event type needs the same small code:
pub trait Event {
const NAME: &'static str;
}
impl Event for OrderPlaced {
const NAME: &'static str = "order.placed";
}
impl Event for OrderPaid {
const NAME: &'static str = "order.paid";
}
// ... and twenty more blocks like this
Twenty copies means twenty places for a typo. A generic function cannot help here, because we need a new impl block for each type. This is a job for a macro.
You already use macros every day: println!, vec!, format! and #[derive(Debug)] are all macros. The ! and the derive attribute tell you that code is generated before the compiler checks types.
First rule: try something simpler
Before you write a macro, ask:
- Can a function do it? Functions are easier to read, test and debug.
- Can a generic or a trait with a default method do it?
- Can a const or a small build script do it?
Write a macro only if the answer is no, for example when you must create new items (impl blocks, functions, structs), take a variable number of arguments, or read the fields of a struct.
macro_rules: patterns and templates
A declarative macro has one or more arms. Each arm is a pattern on the left and a template on the right:
macro_rules! impl_event {
($($ty:ident => $name:literal),* $(,)?) => {
$(
impl Event for $ty {
const NAME: &'static str = $name;
}
)*
};
}
impl_event! {
OrderPlaced => "order.placed",
OrderPaid => "order.paid",
OrderShipped => "order.shipped",
}
- Fragments: $ty:ident matches one name, $name:literal matches one literal. Other common kinds are expr (an expression), ty (a type), path, pat (a pattern), block and tt (any single token tree).
- Repetition: $( … ),* means “zero or more, separated by commas”. Use + for “one or more” and ? for “zero or one”. The trailing $(,)? allows a comma after the last line.
- The template repeats too: each $( … )* in the template runs once for each match.
- The macro input is not Rust code yet. It is only tokens. Types and names are checked after expansion, in the generated code.
Pitfalls of macro_rules
- An expression is pasted, not evaluated. If a template uses $e two times, the expression runs two times:
macro_rules! max {
($a:expr, $b:expr) => {
if $a > $b { $a } else { $b }
};
}
// next_order_id() is called up to two times!
let id = max!(next_order_id(), 1000);
The fix is to bind each input to a variable once, inside a block:
macro_rules! max {
($a:expr, $b:expr) => {{
let (a, b) = ($a, $b);
if a > b { a } else { b }
}};
}
- Hygiene: a local variable made inside a macro does not clash with a variable of the same name at the call site. This protects you, but it only works for local variables and labels. Functions, types and other items made by a macro are visible like normal code.
- Paths in exported macros: a macro marked #[macro_export] is used from other crates. Inside it, write $crate::Event instead of Event, so the path works wherever it is called.
- Order matters: arms are tried from top to bottom, and a macro_rules macro defined in a file can only be used after its definition in that file.
Procedural macros: Rust code that writes Rust code
Some jobs are too hard for patterns: reading every field of a struct, reading attributes, or giving a clear error. For these there are procedural macros. There are three kinds:
- Derive macros: #[derive(Event)] on a struct or enum. They add new code next to it, and cannot change it.
- Attribute macros: #[route(GET, “/orders”)] on a function or item. They get the item and can replace it.
- Function-like macros: sql!(…). They look like macro_rules calls, but run Rust code.
A procedural macro lives in its own crate, with this line in Cargo.toml:
[lib]
proc-macro = true
Here is a derive macro that writes the Event impl for us. The struct name becomes the event name:
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Event)]
pub fn derive_event(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let ty = &input.ident;
let name = ty.to_string();
quote! {
impl ::shop_events::Event for #ty {
const NAME: &'static str = #name;
}
}
.into()
}
Now each event needs only one line:
#[derive(Debug, Event)]
pub struct OrderPaid {
pub order_id: u64,
pub cents: u64,
}
- syn parses the tokens into a tree (DeriveInput has the name, the generics, the fields and the attributes).
- quote builds new tokens. #ty and #name insert values from your Rust code.
- Full paths like ::shop_events::Event make the code work even if the user did not import the trait.
- Generics: a real derive must also copy the generics of the struct. syn has split_for_impl for this.
Good error messages
A macro that panics shows the user a confusing message. Return a compile error that points at the right place:
use syn::{Data, Error};
if !matches!(input.data, Data::Struct(_)) {
return Error::new_spanned(&input.ident, "Event works only on structs")
.to_compile_error()
.into();
}
The error is shown under the name of the type, like a normal compiler error. In macro_rules, the compile_error! macro does the same in an arm that matches wrong input.
The cost of macros
- Build time: syn and the macro crate must compile before your code. Many derive macros on many types can add seconds to every build.
- Reading and debugging: you do not see the generated code. The cargo expand tool (from the cargo-expand crate) prints the code after expansion.
- Testing: test the generated code like normal code. For “this must not compile” cases, the trybuild crate runs small files and checks the error message.
- Security: a procedural macro runs on your machine at build time, with full access, like a build script. Only add macro crates you trust.
- Tools: IDE support inside macro calls is weaker than in normal code.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| A macro where a function is enough | Harder to read, test and debug. | Use a function, generic or trait first. |
| Using $e two times in a template | Side effects run twice. | Bind it once: let value = $e; |
| Short paths in an exported macro | Fails when the caller did not import them. | Use $crate:: or full paths like ::my_crate:: |
| panic! inside a procedural macro | A confusing message with no location. | syn::Error::new_spanned and to_compile_error. |
| Derive that ignores generics | Fails on structs with type parameters. | Use split_for_impl from syn. |
| Never looking at the expanded code | Hidden bugs and slow builds. | Read the output of cargo expand. |
Summary in 7 lines
- A macro writes code at compile time. Types are checked after expansion.
- Try functions, generics and traits first. Use a macro only for what they cannot do.
- macro_rules matches token patterns with fragments like ident, expr and ty, and repeats with $( ),*.
- Bind an expression once, and use $crate:: paths in exported macros.
- Procedural macros (derive, attribute, function-like) live in their own proc-macro crate.
- syn parses the input and quote builds the output. Return errors with a span, never panic.
- Macros cost build time and readability. Check them with cargo expand and test them with trybuild.