Sub topic 7
Writing a derive macro
A derive macro reads a struct or enum and emits extra items, usually a trait implementation. This chapter assumes you can set up a proc-macro crate, know what a TokenStream is, and have used syn and quote at a basic level.
How a derive macro works
A derive macro is a function marked with #[proc_macro_derive(Name)]. The compiler passes it the tokens of the annotated type. It returns new tokens. The compiler appends them next to the type. The original type is never changed or removed.
A worked example
Suppose a separate crate hello_macro defines a trait. The macro crate generates implementations of it.
pub trait HelloMacro {
fn hello_macro();
}The derive macro lives in the proc-macro crate:
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()
}Walk through it step by step:
parse_macro_input!parses the tokens into aDeriveInput. If parsing fails, it returns a compile error for you.input.identis the type's name.input.dataholds the fields or variants.input.genericsholds the generic parameters.name.to_string()produces aString. Interpolating it with#name_stremits a string literal.quote!substitutes each#variablewith its tokens..into()convertsproc_macro2::TokenStreamtoproc_macro::TokenStream.
A user then writes:
use hello_macro::HelloMacro;
use hello_macro_derive::HelloMacro;
#[derive(HelloMacro)]
struct Pancakes;
fn main() {
Pancakes::hello_macro();
}This assumes hello_macro re-exports the derive macro or that both crates are dependencies. Importing both names is allowed because a trait and a derive macro live in different namespaces.
Why `::hello_macro::HelloMacro`
The generated code is pasted into the user's crate. A bare HelloMacro would only resolve if the user imported the trait. A leading :: followed by the crate name works regardless of the imports at the call site.
Supporting generics
The call to split_for_impl returns three pieces. For struct Wrapper<T: Clone> where T: Send, they are:
| Piece | Used at | Example output |
|---|---|---|
| `impl_generics` | after `impl` | `<T: Clone>` |
| `ty_generics` | after the type name | `<T>` |
| `where_clause` | at the end of the header | `where T: Send` |
Bounds appear only in the first piece. Repeating them after the type name would not compile, which is why the three parts are separate.
Reading fields
Often you need the fields. Match on input.data and return an error for unsupported shapes. This derive generates an inherent method listing field names:
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),*]
}
}
})
}The #(#names),* form repeats the iterator's items, separated by commas. Keeping the logic in expand lets you use ? and return a syn::Result.
Common errors
- Forgetting
features = ["full"]onsynwhen parsing items beyond derive input. - Writing
HelloMacrowithout the::cratepath, which fails when the trait is not imported. - Using
unwraporpanic!on bad input. That produces a vague message. Return asyn::Errorinstead. - Ignoring generics, so the macro fails on
struct Foo<T>.
Exercise
A derive macro generates impl #name #ty_generics for struct Boxed<T: Display>(T); and the compiler reports an error about the impl header. Which split_for_impl piece is missing, and where should it go?
Show answer
The impl_generics piece is missing. It must follow the impl keyword, as in impl #impl_generics Trait for #name #ty_generics #where_clause, so the T: Display bound is declared before T is used.