Sub topic 7
Writing a derive macro
A derive macro runs when the compiler meets #[derive(Name)] on a struct, enum, or union. It reads the definition of that type and returns extra items, usually an impl block. This chapter builds one end to end and covers the points that commonly go wrong.
This chapter assumes you have read the earlier chapters on proc-macro crates, TokenStream, syn parsing, and quote!. You should also be comfortable with traits and generics.
What a derive macro does
A derive macro is a function with this shape:
- It takes one
TokenStream, the tokens of the type the user annotated. - It returns one
TokenStream, the new items to add. - It is marked
#[proc_macro_derive(Name)], andNameis the word users write insidederive(...).
The returned tokens are appended after the original type. A derive macro cannot change or remove the type it was applied to. If you need to rewrite the item, use an attribute macro (a later chapter).
The two-crate layout
Rust requires a proc-macro crate to export only macros. It cannot also export the trait the macro implements. The usual layout is therefore two crates:
hello_macro: defines theHelloMacrotrait and re-exports the derive.hello_macro_derive: the proc-macro crate.
The proc-macro crate uses the configuration from the earlier chapter.
[package]
name = "hello_macro_derive"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
proc-macro2 = "1"The trait crate depends on the derive crate and re-exports it. The trait and the derive macro live in different namespaces, so both can be named HelloMacro. This is the same trick serde and the standard library use for Debug.
[package]
name = "hello_macro"
version = "0.1.0"
edition = "2021"
[dependencies]
hello_macro_derive = { path = "../hello_macro_derive" }pub trait HelloMacro {
fn hello_macro();
}
pub use hello_macro_derive::HelloMacro;The derive function
Here is the macro itself, in hello_macro_derive/src/lib.rs.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let name_str = name.to_string();
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let expanded = quote! {
impl #impl_generics ::hello_macro::HelloMacro for #name #ty_generics #where_clause {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", #name_str);
}
}
};
expanded.into()
}Each step does one job:
parse_macro_input!(input as DeriveInput)parses the tokens into a syntax tree. If parsing fails, the macro returns a compiler error for you and exits early.input.identis the type's name as anIdent. You can splice it intoquote!directly.name.to_string()produces aString. Interpolating aStringintoquote!yields a string literal token, so#name_strbecomes"Pancakes"in the output.split_for_impl()returns three pieces of the generics. They are covered in the next chapter, but you should include them now so the macro works for generic types from the start..into()convertsproc_macro2::TokenStream(whatquote!returns) intoproc_macro::TokenStream(what the compiler expects).
Using it
use hello_macro::HelloMacro;
#[derive(HelloMacro)]
struct Pancakes;
#[derive(HelloMacro)]
struct Wrapper<T: Clone>(T);
fn main() {
Pancakes::hello_macro();
Wrapper::<u8>::hello_macro();
}The output is:
Hello, Macro! My name is Pancakes!
Hello, Macro! My name is Wrapper!For Wrapper<T: Clone>, the macro emits roughly impl<T: Clone> ::hello_macro::HelloMacro for Wrapper<T> { ... }. Without split_for_impl, the generated impl would not compile, because T would be undeclared.
What DeriveInput contains
DeriveInput has these fields:
| Field | Type | Meaning |
|---|---|---|
| `attrs` | `Vec<Attribute>` | Attributes on the type, such as `#[describe(...)]` |
| `vis` | `Visibility` | `pub`, `pub(crate)`, or inherited |
| `ident` | `Ident` | The type's name |
| `generics` | `Generics` | Type parameters, lifetimes, const generics, and the `where` clause |
| `data` | `Data` | `Data::Struct`, `Data::Enum`, or `Data::Union` |
Most real derive macros look inside data. The next example generates a method that lists a struct's field names. It also shows the standard error-handling structure: the work happens in a function that returns syn::Result, and the entry point turns any error into a compile error.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Error, Fields};
#[proc_macro_derive(FieldNames)]
pub fn field_names(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand(input)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
fn expand(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
let name = &input.ident;
let fields = match &input.data {
Data::Struct(DataStruct {
fields: Fields::Named(f),
..
}) => &f.named,
_ => {
return Err(Error::new_spanned(
&input.ident,
"FieldNames only supports structs with named fields",
))
}
};
let names = fields.iter().map(|f| f.ident.as_ref().unwrap().to_string());
let (ig, tg, wc) = input.generics.split_for_impl();
Ok(quote! {
impl #ig #name #tg #wc {
pub fn field_names() -> &'static [&'static str] {
&[#(#names),*]
}
}
})
}Points worth noting:
- This macro generates an inherent
impl(no trait), which is legal. The generated method belongs to the annotated type. #(#names),*repeats the interpolation once per item in the iterator, separated by commas. For a struct with fieldsxandy, it expands to&["x", "y"].- The
unwrap()onf.identis safe here becauseFields::Namedguarantees every field has a name. Error::new_spanned(&input.ident, ...)attaches the message to the type's name. The user sees the error underlined at their own code, not inside your macro.
If a user writes #[derive(FieldNames)] struct Point(i32, i32);, the compiler reports FieldNames only supports structs with named fields at Point.
Gotchas
- Use absolute paths in generated code. The macro emits
::hello_macro::HelloMacro, notHelloMacro. The user's module might not import the trait, or might define something else with the same name. The leading::forces resolution from the crate root of an extern crate. The user's crate must depend onhello_macrofor this to work, which is why the derive is re-exported from the trait crate. - Proc macros are not hygienic by default. Identifiers you create with
quote!can collide with names in the user's code. Pick unlikely names for local variables in generated code. The spans and hygiene chapter covers this in detail. - Derive adds items; it never edits the type. If your macro needs to add a field or change a signature, it cannot be a derive macro.
- All three data kinds can reach your macro. If you only support structs, say so with an error, as
FieldNamesdoes. Do not assume. - Bounds on generics are not added for you.
split_for_implcopies the bounds the user wrote. If the generated body requiresT: Display, you must add that bound to thewhereclause yourself. Standard derives likeClonedo this automatically, and you need to write the same logic in your own macro. - Name matching. The name in
#[proc_macro_derive(HelloMacro)]is what users write. The Rust function name (hello_macro_derive) is not visible to users.
Checking your understanding
Exercise
The HelloMacro derive writes ::hello_macro::HelloMacro in its output instead of HelloMacro. Give one concrete situation where the shorter form would break.
Show answer
If the user's module has not imported the trait (no use hello_macro::HelloMacro; for the trait), the name HelloMacro would not resolve in the generated impl and compilation would fail. It would also break if the user's module defines its own, unrelated item called HelloMacro, because the generated code would then refer to that item. The absolute path ::hello_macro::HelloMacro always names the trait from the extern crate.
Exercise
Extend FieldNames so that a tuple struct such as struct Point(i32, i32); is accepted and Point::field_names() returns &["0", "1"]. Which part of the code must change?
Show answer
The match in expand must also accept Fields::Unnamed. For named fields, keep using f.ident. For unnamed fields, use fields.iter().enumerate() and map each index to i.to_string(). Because the two branches produce different iterator types, collect each into a Vec<String> and return that from the match. The rest of the function, including the quote! block with #(#names),*, stays the same because Vec<String> also works in a repetition.