How do you write a Rust #[proc_macro_derive] function with syn and quote that generates a builder for a named-field struct?
answer
- parse, inspect, generate, convert
- parse_macro_input! as DeriveInput
- Data::Struct and Fields::Named
- #var and #( ... )* in quote!
- absolute paths in the output
basics
~20 sParse the input with syn's parse_macro_input!(input as DeriveInput), take the struct's ident and named fields from its data, build the output with quote! using #name interpolation and #( ... )* repetitions, then return it with .into().
solid answer
~30 sStart with `let input = parse_macro_input!(input as DeriveInput);`, which on a parse failure returns a `compile_error!` for you. `DeriveInput` gives you `ident`, `generics`, `attrs` and `data`; match `Data::Struct` and `Fields::Named` and return a `syn::Error` for enums or tuple structs. Make new names with `format_ident!("{}Builder", name)`. Then write the output in `quote!`: `#name` splices one value, `#( #names: Option<#tys>, )*` repeats once per field, walking both lists together. `quote!` produces a `proc_macro2::TokenStream`, so finish with `.into()`. Because the output is pasted at the call site unhygienically, write `::core::option::Option` rather than `Option` so a user's own type of that name cannot capture it.
code
rust · 36 linesuse proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, Data, DeriveInput, Fields};
#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let builder = format_ident!("{}Builder", name);
let Data::Struct(data) = &input.data else {
return syn::Error::new_spanned(name, "Builder supports only structs")
.to_compile_error()
.into();
};
let Fields::Named(fields) = &data.fields else {
return syn::Error::new_spanned(&data.fields, "Builder needs named fields")
.to_compile_error()
.into();
};
let names: Vec<_> = fields.named.iter().map(|f| &f.ident).collect();
let tys: Vec<_> = fields.named.iter().map(|f| &f.ty).collect();
quote! {
#[derive(Default)]
pub struct #builder { #( #names: ::core::option::Option<#tys>, )* }
impl #name {
pub fn builder() -> #builder { ::core::default::Default::default() }
}
impl #builder {
#( pub fn #names(mut self, v: #tys) -> Self { self.#names = ::core::option::Option::Some(v); self } )*
pub fn build(self) -> ::core::result::Result<#name, &'static str> {
::core::result::Result::Ok(#name { #( #names: self.#names.ok_or(stringify!(#names))?, )* })
}
}
}
.into()
}go deeper
Recall the two crates: syn turns tokens into a syntax tree, quote turns a template with #variables back into tokens.
Walk through DeriveInput's fields, matching Data::Struct and Fields::Named, quote's #var and #( ... )* repetition, and why the last step is .into().
Show the habits that make a derive robust: parse_macro_input! instead of unwrap, errors returned with spans, absolute paths in output, and logic in a proc_macro2 function you can unit-test.
Mention what a derive dependency costs everyone downstream: syn and quote compiled before any user code, and generated names landing in users' modules, so keep the output small and predictable.
## The pipeline Almost every derive written with **syn** (a parser for Rust syntax) and **quote** (a quasi-quoting code generator) follows the same four steps: 1. **Parse** the incoming `proc_macro::TokenStream` into a syntax tree: `parse_macro_input!(input as DeriveInput)`. 2. **Inspect** the tree: the type's name, its fields, their types and attributes, its generics. 3. **Generate** new tokens with `quote!`, splicing in pieces of the tree. 4. **Convert** the result back into a `proc_macro::TokenStream` with `.into()` and return it. ## Parsing with syn `syn::DeriveInput` is the tree for anything a derive can be placed on. Its fields are: - `attrs`, the outer attributes, including doc comments as `#[doc]`; - `vis`, the visibility, such as `pub`; - `ident`, the type's name; - `generics`, its lifetime, type and const parameters and where clause; - `data`, one of `Data::Struct`, `Data::Enum` or `Data::Union`. A struct's `fields` are `Fields::Named` (`{ host: String }`), `Fields::Unnamed` (tuple structs) or `Fields::Unit`. Each `syn::Field` carries `ident` (an `Option`, `None` for tuple fields), `ty` and `attrs`. A builder only makes sense for named fields, so the derive matches those and returns an error for everything else. `parse_macro_input!` matters: on a parse failure it **returns early** with the error rendered as `compile_error!`, so the user sees a normal compile error. The Rust Book's first example calls `syn::parse(input).unwrap()` instead and says so as a simplification; that turns every parse failure into a panic. `DeriveInput` is behind syn's `derive` feature, which is on by default. ## Generating with quote Inside `quote! { ... }`, ordinary tokens are copied literally and `#var` splices any value that implements `ToTokens`: an `Ident`, a `Type`, a `Generics`, another token stream. - `#( ... )*` repeats its body once per element of every iterable spliced inside it; with two lists inside, such as `#names` and `#tys`, it walks them in step. - `#( ... ),*` puts a comma between repetitions. - `format_ident!("{}Builder", name)` builds a new identifier, used here for `ServerConfigBuilder`. - `stringify!(#names)` in the output turns a field name into a string literal for an error message. ## Two TokenStream types | Type | Comes from | Usable where | |---|---|---| | `proc_macro::TokenStream` | the compiler's `proc_macro` crate | only inside a running procedural macro | | `proc_macro2::TokenStream` | the `proc-macro2` crate | anywhere, including unit tests | `quote!` returns the `proc_macro2` type, which is why the last step is `.into()`. Keeping the real work in a function that takes and returns `proc_macro2` values lets you unit-test it without a compiler driving it. ## Writing output that works in any crate A procedural macro's output is **unhygienic**: rustc treats it as if the user had typed it at the call site. Two consequences follow: - Prefer **absolute paths** (`::core::option::Option`, `::core::default::Default`): a bare `Option` would resolve to whatever `Option` the user's module defines or imports. - A trait the derive implements must be reachable from the user's crate; derives usually name it by a full path such as `::my_crate::Describe`. Generated names such as `ServerConfigBuilder` also land in the user's module and can clash with the user's own items, so pick names the user is unlikely to write. ## What usually goes wrong - Forgetting `.into()` and returning a `proc_macro2::TokenStream`: a type mismatch. - Unwrapping the parse result, so bad input panics instead of producing an error at the right place. - Ignoring `generics`, which breaks the derive on `struct Labeled<T>`. - Assuming field types: the derive sees how a type is spelled, not which traits it implements.
- Why put the expansion logic in a separate function using proc_macro2 types?`proc_macro::TokenStream` only works while the compiler is running the macro, so code using it cannot run in a normal `#[test]`. A function `fn expand(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream>` can be called from unit tests with `syn::parse_quote!` input, and the thin `#[proc_macro_derive]` wrapper only parses, calls it and converts the result.
- How does the derive handle a tuple struct or an enum?Match `input.data` and its `fields`: anything other than `Data::Struct` with `Fields::Named` returns `syn::Error::new_spanned(node, message).to_compile_error()`. The user then gets a normal compile error underlining the enum's name or the tuple fields, rather than a panic or confusing errors from generated code.
- Unwrapping syn::parse is fine because a panic is a clean error.
- quote! returns a proc_macro::TokenStream, so .into() is unnecessary.
- Writing Option in generated code always means std's Option.
- A derive can read each field's type and know which traits it implements.
- #( ... )* needs an explicit count of how many times to repeat.