Sub topic 1
Declarative macros versus procedural macros
Prerequisites
This chapter assumes you can read and write Rust structs, enums, traits, and generics. You should know how Cargo packages and dependencies work, and you should have used derive attributes such as #[derive(Debug)]. You don't need to have written a macro before. Later chapters build the tools in detail. This chapter explains which kind of macro to reach for.
What a macro does
A macro is code that writes code. The compiler runs it during compilation and replaces the macro call with the code it produces. This step is called expansion. After expansion, the compiler checks and compiles the result like any other Rust code.
Rust has two macro systems:
- Declarative macros, defined with
macro_rules!. They match input against patterns and substitute it into templates. - Procedural macros. These are ordinary Rust functions that receive a stream of tokens and return a new stream of tokens.
Procedural macros come in three kinds: function-like, derive, and attribute. That gives four kinds of macro in total.
Declarative macros with macro_rules!
A declarative macro looks like a match expression. Each arm has a pattern on the left and a template on the right. The compiler tries the arms in order and uses the first one whose pattern matches.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
macro_rules! maximum {
($x:expr) => { $x };
($x:expr, $($rest:expr),+) => {{
let first = $x;
let others = maximum!($($rest),+);
if first > others { first } else { others }
}};
}
fn main() {
println!("{}", square!(7));
println!("{}", maximum!(3, 9, 4));
}The pattern $x:expr captures any expression and names it $x. The fragment specifier after the colon (expr, ident, ty, tt, and so on) says what kind of syntax to capture. The $(...),+ part is a repetition: one or more comma-separated items. The second arm of maximum! calls the macro again with the remaining items, so the macro is recursive.
Declarative macros have real strengths:
- They need no extra crate. You define them in the same crate where you use them, or export them with
#[macro_export]. - They are quick to write for small tasks.
- They are cheap to compile, because the compiler does the matching itself.
They also have limits:
- They can only rearrange the syntax they capture. They cannot inspect it. A
macro_rules!macro cannot ask "what are the field names of this struct?" unless you pass the field names in. - They cannot build new identifiers, such as turning
foointoget_foo, or compute anything about the input. - Complex repetition and recursion patterns are hard to read, and the error messages are poor.
- They cannot be applied with
#[derive(...)]or as an attribute on an item.
Procedural macros
A procedural macro is a Rust function that runs inside the compiler. It takes a TokenStream (the tokens of the macro input) and returns a TokenStream (the tokens to put in its place). Between those two steps you can run any Rust code you like: loops, match, string handling, lookups in a table. You can parse the input into a syntax tree, inspect it, and generate whatever output you need.
Here is the smallest working example of the idea. It is a function-like macro that ignores its input and returns a fixed function.
use proc_macro::TokenStream;
#[proc_macro]
pub fn make_answer(_input: TokenStream) -> TokenStream {
"fn answer() -> u32 { 42 }".parse().unwrap()
}Using it looks like this:
use my_macros::make_answer;
make_answer!();
fn main() {
println!("{}", answer());
}The function answer doesn't appear anywhere in the source of the second file. The macro created it during compilation.
Procedural macros have two requirements that macro_rules! does not:
- They must live in their own crate, set up as a
proc-macrocrate. The next chapter covers the Cargo configuration. - They run as compiled code, so the proc-macro crate and its dependencies must be built before the crate that uses the macro.
The three kinds of procedural macro
Each kind has a different attribute, a different call syntax, and different inputs.
| Kind | Declared with | Called as | Input | Output |
|---|---|---|---|---|
| Function-like | `#[proc_macro]` | `name!(...)` | The tokens between the delimiters | Replaces the whole call |
| Derive | `#[proc_macro_derive(Name)]` | `#[derive(Name)]` | The struct, enum, or union | Is appended after the type |
| Attribute | `#[proc_macro_attribute]` | `#[name(...)]` | Attribute arguments and the annotated item | Replaces the item |
Function-like macros
These look like macro_rules! calls, but the input can follow any grammar you can parse. Use them to define a small embedded language, such as an HTML template, a SQL query checked at compile time, or a custom list syntax. The add!(1, 2) macro in a later chapter is of this kind.
Derive macros
A derive macro attaches to a struct, enum, or union through #[derive(...)]. It cannot change the type. It can only add new items next to it, usually a trait implementation. This is how Debug, Clone, and Serialize work. Derive macros can also declare helper attributes, such as #[serde(rename = "x")], that users put on fields.
Attribute macros
An attribute macro receives two token streams: the arguments inside the attribute, and the item it is attached to. Whatever it returns replaces that item. It can wrap a function, add methods, or delete the item entirely. Web frameworks use this for route handlers, and test frameworks use it for #[test]-like markers.
How the compiler runs a procedural macro
The compiler does not give your macro a finished syntax tree. It gives raw tokens. Your macro must parse them itself, usually with the syn crate, and build the output, usually with the quote crate.
flowchart TDThe diagram below shows the full path.
Three points follow from this flow:
- The macro sees syntax only. It has no type information. A derive macro on
struct A { x: Foo }can see the textFoo, but it cannot ask whetherFooimplementsClone. - The output is checked after expansion. If your macro emits invalid Rust, the error shows up when the compiler processes the expanded code, and it may point at confusing locations.
- A panic inside the macro becomes a compile error. This works, but the message is rarely helpful. Later chapters show how to report errors with
syn::Errorinstead.
Choosing between them
Start from what you need to do, not from which macro sounds more powerful.
| Need | Use |
|---|---|
| Remove repeated boilerplate with a fixed shape, such as a few similar `impl` blocks | `macro_rules!` |
| A shorthand for a common expression, like `vec!` or `matches!` | `macro_rules!` |
| Generate a trait impl from the fields or variants of a type | Derive macro |
| Read field names, types, or attributes of a type | Derive macro |
| Wrap or transform an existing function or item | Attribute macro |
| Parse a custom syntax that doesn't fit Rust patterns | Function-like procedural macro |
| Produce clear, targeted compile errors for bad input | Procedural macro |
Some trade-offs matter in practice:
- Compile time. A proc-macro crate and its dependencies (
synwith thefullfeature is sizable) add to build time, especially in a clean build. Amacro_rules!macro costs almost nothing. - Maintenance. A
macro_rules!macro is short but can become unreadable when it grows. A procedural macro is longer but is ordinary Rust that you can split into functions and test. - Tooling. Editors and tools such as rust-analyzer handle both, but proc-macro output is harder to see. You will need
cargo expandto read the generated code. - Diagnostics. A procedural macro can point an error at the exact token that is wrong. A
macro_rules!macro can only report that no arm matched.
A good rule is to start with macro_rules!. Move to a procedural macro when you need to inspect a type, build identifiers, use #[derive] or attribute syntax, or give good errors.
Common mistakes
- Trying to use
macro_rules!to read struct fields. The macro only sees what you pass in. Use a derive macro, which receives the whole type. - Putting
#[proc_macro]functions in a normal library crate. The compiler rejects it. Procedural macros need a crate withproc-macro = true. - Exporting other items from the proc-macro crate. Such a crate can export only procedural macros. Shared types belong in a separate crate that both the macro crate and its users depend on.
- Expecting the macro to see types. It only sees tokens, so it cannot resolve names or check trait bounds.
- Assuming a derive macro can modify the struct it annotates. It can only add new items.
Exercise
You want #[derive(FieldNames)] to give a struct a method that returns its field names as strings. Why can't a macro_rules! macro do this on its own, and which kind of procedural macro fits?
Show answer
A macro_rules! macro only sees the tokens passed to its call, and it can't be attached with #[derive]. It would force the user to write the field names out again. A derive macro receives the whole struct definition, so it can read the field names and generate the method. A derive macro is the right kind.
Exercise
A colleague wants to wrap many functions so each prints its name before running. Which kind of macro fits, and what does it receive and return?
Show answer
An attribute macro (#[proc_macro_attribute]). It receives two token streams: the attribute arguments and the annotated function. It returns tokens that replace the function, here the original function with an added print statement at the start of its body.
Exercise
A macro needs to check that a type implements Clone before generating code. Can a procedural macro do this directly? Why or why not?
Show answer
No. A procedural macro runs on tokens before type checking, so it sees only the syntax of the type name and has no information about which traits it implements. It can emit code that requires Clone, and the compiler will report an error if the bound isn't met.