Write a Rust procedural macro (Derive) that generates a builder method for every field…
- User
Write a Rust procedural macro (Derive) that generates a builder method for every field in a struct.
Assistant
Write a Rust procedural macro (Derive) that generates a builder method for every field in a struct.
1. Understand the Goal: The user wants a Rust procedural macro, specifically a derive macro (#[derive(Builder)]). This macro should generate a "builder pattern" implementation for any struct it is applied to. This means for a struct like:
rust struct MyStruct { a: i32, b: String, }
It should generate code that allows construction like:
rust let val = MyStructBuilder::default().a(10).b("hello".to_string()).build().unwrap();
Identify Key Components:
proc-macro crate.syn (parsing), quote (code generation), proc-macro2 (stable API for procedural macros).TokenStream representing the struct.TokenStream representing the generated code (impl blocks).Step-by-Step Implementation Plan:
Step 1: Project Setup.
cargo new derive_builder --lib.Cargo.toml:
[lib] -> proc-macro = true[dependencies] -> syn, quote, proc-macro2.Step 2: The Macro Entry Point.
pub fn derive_builder(input: TokenStream) -> TokenStream.let input = parse_macro_input!(input as DeriveInput);.Step 3: Inspect the Struct.
input.data.input.ident).Fields::Named).Step 4: Generate the Builder Struct.
{OriginalName}Builder.Option.serde attributes or generic bounds? Keep it simple for the prompt: just basic types.Step 5: Implement the Builder Logic.
new() or default(): Initialize all fields to None.foo: T, generate a method foo(&mut self, value: T) -> &mut Self that sets self.foo = Some(value).build(): Check if all fields are Some. If yes, construct the struct. If no, return an error (or panic, but Result is better).Step 6: Code Generation with quote.
#(#fields)*).Refining the Code Generation (Mental Draft):
Original Struct: StructName
Builder Struct: StructNameBuilder
Fields: id: u32, name: String
Builder Fields: id: Option<u32>, name: Option<String>
Setters:
pub fn id(&mut self, value: u32) -> &mut Self {
self.id = Some(value);
self
}
Build Method:
pub fn build(&self) -> Result<StructName, String> {
Ok(StructName {
id: self.id.clone().ok_or("id not set")?,
name: self.name.clone().ok_or("name not set")?,
})
}
Note: Using clone() is easier if fields don't implement Into, but taking ownership in build(self) is more idiomatic for builders to avoid unnecessary clones. Let's switch build to take self. This avoids .clone() requirements on the types, assuming the builder consumes itself.
Revised Build Method:
pub fn build(self) -> Result<StructName, String> {
Ok(StructName {
id: self.id.ok_or("id not set")?,
name: self.name.ok_or("name not set")?,
})
}
Handling Generics:
struct S<T>, the builder should be struct SBuilder<T>.impl_generics, ty_generics, where_clause.Writing the Code (Mental Sandbox):
use proc_macro::TokenStream;
use quote::{quote, format_ident};
use syn::{parse_macro_input, DeriveInput, Data, 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_name = format_ident!("{}Builder", name);
let fields = match &input.data {
Data::Struct(data) => match &data.fields {
Fields::Named(fields) => &fields.named,
_ => panic!("Only named fields supported"),
},
_ => panic!("Only structs supported"),
};
// 1. Create fields for the Builder struct (Option)
let builder_fields = fields.iter().map(|f| {
let name = &f.ident;
let ty = &f.ty;
quote! { #name: Option<#ty> }
});
// 2. Create initialization (None)
let init_fields = fields.iter().map(|f| {
let name = &f.ident;
quote! { #name: None }
});
// 3. Create setter methods
let setter_methods = fields.iter().map(|f| {
let name = &f.ident;
let ty = &f.ty;
quote! {
pub fn #name(&mut self, value: #ty) -> &mut Self {
self.#name = Some(value);
self
}
}
});
// 4. Create build extraction
let build_fields = fields.iter().map(|f| {
let name = &f.ident;
let error_msg = format!("Field {} not set", name.as_ref().unwrap());
quote! {
#name: self.#name.take().ok_or(#error_msg)?
}
});
// Generics handling (simplified)
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let expanded = quote! {
pub struct #builder_name #ty_generics #where_clause {
#(#builder_fields),*
}
impl #impl_generics #builder_name #ty_generics #where_clause {
pub fn new() -> Self {
Self {
#(#init_fields),*
}
}
#(#setter_methods)*
pub fn build(mut self) -> Result<#name #ty_generics, String> {
Ok(#name {
#(#build_fields),*
})
}
}
};
TokenStream::from(expanded)
}
Refining for the User:
Cargo.toml, lib.rs).Self-Correction / Edge Cases:
pub, the builder should likely be pub.Option, wrapping it in Option> is redundant but "correct" for a naive implementation. The prompt asks for a basic macro, so wrapping everything in Option is the standard approach unless specified otherwise.Cargo.toml (e.g., syn = { version = "1.0", features = ["full"] }).Final Output Generation:
Structure the response:
Cargo.toml content.src/lib.rs content (the macro code).src/main.rs in a different crate).Code Polish: Ensure the quote syntax is correct. format_ident is useful for the Builder struct name.
(Self-Correction during drafting): Should I use proc_macro2::Span::call_site()? Yes, usually implicitly handled by quote. Should I verify visibility? For a simple example, assuming pub is safer, but ideally, I should capture the visibility of the struct and apply it to the builder struct. Let's keep it simple and make the builder struct pub for demonstration, or better yet, try to preserve visibility if easy. Actually, keeping it simple is best: just pub struct Builder.
Wait, Generics: If I use split_for_impl, I must be careful about where the where clause goes. It goes after the type parameters in the struct definition and the impl block.
Let's write the actual code logic for the response.
Dependency versions:
syn = { version = "1", features = ["full", "parsing", "extra-traits"] } (Extra traits helps debugging but not strictly needed. Full feature is needed for parsing structs).
quote = "1"
proc-macro2 = "1"
Implementation Details:
DeriveInput.Data::Struct. Panic otherwise.Fields::Named. Panic otherwise.ident.builder_ident.fields to generate:
optionized_fields: foo: Option<String>initializers: foo: Nonesetters: fn foo(...)extractors: foo: self.foo.ok_or(...)?Looks solid. I will present this as a complete crate.
To create a procedural macro in Rust, you need to create a separate crate of type proc-macro. This is because procedural macros are compiled as plugins to the compiler.
Here is the complete step-by-step implementation.
You cannot write a procedural macro in the same crate where you intend to use it. You need a "library" crate for the macro and a binary crate to use it.
Create a directory for your project:
mkdir my_project
cd my_project
Create the macro crate:
cargo new derive_builder --lib
Create the usage crate:
cargo new my_app
derive_builder)Open derive_builder/Cargo.toml and add the necessary dependencies. We need syn to parse the code, quote to generate code, and proc-macro2 as a bridge.
File: derive_builder/Cargo.toml
[package]
name = "derive_builder"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = { version = "1.0", features = ["full", "parsing"] }
quote = "1.0"
proc-macro2 = "1.0"
derive_builder/src/lib.rs)This is the core logic. We will parse the struct, iterate over its fields, and generate a Builder struct along with setter methods and a build method.
File: derive_builder/src/lib.rs
my_app)Now we need to link the macro crate and use it.
File: my_app/Cargo.toml
[package]
name = "my_app"
version = "0.1.0"
edition = "2021"
[dependencies]
derive_builder = { path = "../derive_builder" }
File: my_app/src/main.rs
use derive_builder::Builder;
#[derive(Builder)]
pub struct User {
id: u32,
username: String,
email: String,
active: bool,
}
fn main() {
// Use the generated builder
let user = User::builder()
.id(1)
.username("rustacean".to_string())
.email("rust@example.com".to_string())
.active(true)
.build();
match user {
Ok(u) => println!("User created: {} ({})", u.username, u.email),
Err(e) => println!("Error creating user: {}", e),
}
// Example of missing a field
let incomplete_user = User::builder()
.id(2)
.username("incomplete".to_string())
.build();
if incomplete_user.is_err() {
println!("Expected error: {:?}", incomplete_user.unwrap_err());
}
}
From the root my_project folder:
cd my_app
cargo run
syn parses the Rust code into a data structure (AST) we can manipulate.UserBuilder where every field is wrapped in Option.builder() function on User that initializes the builder with all fields set to None.Option and return &mut Self (allowing chaining).build() method that checks if all fields are Some. If they are, it constructs the User. If not, it returns an error.use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, DeriveInput, Data, Fields, Ident};
#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(input as DeriveInput);
// Get the name of the struct (e.g., "MyStruct")
let struct_name = input.ident;
// Generate the name for the builder (e.g., "MyStructBuilder")
let builder_name = format_ident!("{}Builder", struct_name);
// Ensure we are working with a struct
let fields = match input.data {
Data::Struct(data) => match data.fields {
Fields::Named(fields) => fields,
_ => panic!("Only structs with named fields are supported"),
},
_ => panic!("Only structs are supported"),
};
// 1. Generate fields for the Builder struct (wrapped in Option)
// For field `name: String`, generate `name: Option<String>`
let builder_fields = fields.named.iter().map(|f| {
let name = &f.ident;
let ty = &f.ty;
quote! {
#name: Option<#ty>
}
});
// 2. Generate initialization code for the Builder struct (all None)
let builder_init = fields.named.iter().map(|f| {
let name = &f.ident;
quote! {
#name: None
}
});
// 3. Generate setter methods for the Builder
// For field `name: String`, generate `fn name(&mut self, value: String) -> &mut Self`
let setter_methods = fields.named.iter().map(|f| {
let name = &f.ident;
let ty = &f.ty;
quote! {
pub fn #name(&mut self, value: #ty) -> &mut Self {
self.#name = Some(value);
self
}
}
});
// 4. Generate the extraction code for the final build method
// For field `name: String`, generate `name: self.name.ok_or("missing name")?`
let build_fields = fields.named.iter().map(|f| {
let name = &f.ident;
let name_str = name.as_ref().unwrap().to_string(); // Convert Ident to string for error message
quote! {
#name: self.#name.clone().ok_or(format!("Field {} is not set", #name_str))?
}
});
// Assemble the output code using the `quote` crate
let expanded = quote! {
// The Builder Struct
pub struct #builder_name {
#(#builder_fields),*
}
impl #builder_name {
// Setters
#(#setter_methods)*
// The Build Method
pub fn build(&self) -> Result<#struct_name, Box<dyn std::error::Error>> {
Ok(#struct_name {
#(#build_fields),*
})
}
}
// Implement a default() method on the original struct to create the builder
impl #struct_name {
pub fn builder() -> #builder_name {
#builder_name {
#(#builder_init),*
}
}
}
};
// Hand the output tokens back to the compiler
TokenStream::from(expanded)
}