Construct a Rust declarative macro macro_rules! that generates a Builder pattern for a…
- User
Construct a Rust declarative macro
macro_rules!that generates aBuilderpattern for a given struct. Assistant
Construct a Rust declarative macro macro_rules! that generates a Builder pattern for a given struct.
1. Understand the Goal: The user wants a Rust declarative macro (macro_rules!) that automatically generates the Builder pattern for a given struct. This is a classic metaprogramming exercise in Rust.
Analyze the Builder Pattern:
struct Foo { x: i32, y: String }).FooBuilder) containing Option<T> fields for each field in the original struct.new() method on the Builder to initialize it (usually with None for all fields).mut self, setting the field, returning Self).build() method on the Builder that checks if all fields are set (optional requirement, but standard for a robust builder) or constructs the final struct.Determine the Macro Interface:
make_builder! {
struct MyStruct {
field1: i32,
field2: String,
}
}
Design the macro_rules! Matching:
($vis:vis struct $name:ident {
$(
$field_vis:vis $field_name:ident : $field_type:ty
),* $(,)?
})
Implementing the Logic (Step-by-Step):
Part 1: The Original Struct. The macro needs to output the struct itself so the user doesn't have to write it twice.
$vis struct $name {
$(
$field_vis $field_name : $field_type
),*
}
Part 2: The Builder Struct.
We need a new name. Convention is $name + Builder.
Fields should be Option<$field_type>.
pub struct ${concat($name, Builder)} { // Wait, declarative macros can't concat identifiers easily in output positions without a trick.
Self-Correction on Identifier Concatenation: Declarative macros cannot create new identifiers by concatenation (like FooBuilder from Foo) directly. I have to take the builder name as an argument, or hardcode it relative to a module, or just require the user to name it.
Standard Solution: The user usually passes the builder name, OR the macro defines the struct inside a module with a specific name, OR we use the paste crate (but that's external).
Simple Solution for this prompt: Let's ask the user to provide the Builder name, or stick to a standard convention where the user inputs the struct definition.
Better approach for a general tutorial: Let's define the pattern as: builder!(StructName { ... }) and generate StructName and StructNameBuilder. Wait, StructNameBuilder is hard.
Alternative: Let's assume the struct is already defined, and the macro generates the impl? No, the prompt implies generating the whole pattern.
Let's try the "Helper Module" approach or simply ask for the Builder name.
Let's go with asking for the Builder name as an argument: $builder:ident.
Drafting Pattern:
macro_rules! make_builder {
($name:ident, $builder:ident { $($f:ident: $t:ty),* }) => { ... }
}
But structs have vis modifiers and commas. Let's refine the capture.
Refined Pattern:
macro_rules! builder {
// Extract visibility and name
(
$(#[$outer:meta])* // attributes
$vis:vis
struct $name:ident {
$(
$(#[$field_meta:meta])* // field attributes
$field_vis:vis $field_name:ident : $field_type:ty
),* $(,)?
}
) => {
// ... implementation ...
}
}
Implementing the Generation Logic:
pub struct $name {
$(pub $field_name: $field_type),*
}
pub struct $builder {
$(pub $field_name: Option<$field_type>),*
}
impl $builder {
pub fn new() -> Self {
Self {
$($field_name: None),*
}
}
}
impl $builder {
$(
pub fn $field_name(mut self, val: $field_type) -> Self {
self.$field_name = Some(val);
self
}
)*
}
impl $builder {
pub fn build(self) -> Result<$name, &'static str> {
// Check for None
$(
if self.$field_name.is_none() {
return Err(concat!("Missing field: ", stringify!($field_name)));
}
)*
Ok($name {
$($field_name: self.$field_name.unwrap()),*
})
}
}
Refining the Macro Pattern: I need to handle visibility and attributes carefully to make it production-ready-ish.
Pattern:
(
$(#[$struct_meta:meta])*
$struct_vis:vis struct $struct_name:ident {
$(
$(#[$field_meta:meta])*
$field_vis:vis $field_name:ident : $field_type:ty
),* $(,)?
}
)
Naming the Builder:
Since I cannot generate StructNameBuilder, I will define the Builder struct inside the macro expansion with a fixed name or ask for it.
Actually, a common pattern is to just name it $struct_name::Builder by putting the builder inside a module mod $struct_name.
Let's try that. It avoids passing two names.
Approach A (Module wrapper):
Input: builder!(struct MyStruct { ... })
Output:
mod MyStruct { // This hides the struct, which is annoying.
pub struct Data { ... }
pub struct Builder { ... }
}
This changes the API surface. User wants MyStruct, not MyStruct::Data.
Approach B (Explicit Builder Name):
This is the most reliable way for a standalone snippet.
Let's stick to:
builder!(StructName, BuilderName { fields... })
Wait, I can try to infer.
Actually, let's just provide the code that generates the Struct and the Impl. The Impl can be on the struct itself to return a generic Builder struct defined elsewhere?
No, the fields of the Builder must match the Struct.
Let's go with the most explicit, standard solution: Macro takes the Struct definition and the Builder name as arguments.
Wait, is there a trick to append 'Builder'?
No, macro_rules! is strictly textual substitution with variable matching. It cannot manipulate identifiers (like paste crate does).
Decision: I will write the macro taking the Struct Name and the Builder Name as separate identifiers, followed by the body. This is the standard limitation of declarative macros.
Drafting the Code:
macro_rules! define_builder {
(
// Struct visibility and name
$struct_vis:vis $struct_name:ident
// Builder name
as $builder_name:ident
// Fields
{
$(
$field_vis:vis $field_name:ident : $field_type:ty
),* $(,)?
}
) => {
// 1. Generate the Struct
$struct_vis struct $struct_name {
$(
$field_vis $field_name: $field_type
),*
}
// 2. Generate the Builder Struct
$struct_vis struct $builder_name {
$(
$field_name: Option<$field_type>
),*
}
// 3. Generate the Impl for the Builder
impl $builder_name {
pub fn new() -> Self {
Self {
$(
$field_name: None
),*
}
}
$(
pub fn $field_name(mut self, value: $field_type) -> Self {
self.$field_name = Some(value);
self
}
)*
pub fn build(self) -> Result<$struct_name, String> {
// Validation logic
$(
let $field_name = self.$field_name.ok_or(format!("Field '{}' is missing", stringify!($field_name)))?;
)*
Ok($struct_name {
$(
$field_name
),*
})
}
}
}
}
Refinement on Usage:
Using as $builder_name makes the syntax a bit specific.
Let's try to match a standard struct definition more closely.
macro_rules! builder {
($vis:vis struct $name:ident { $($fvis:vis $fname:ident: $fty:ty),* $(,)? } => $builder:ident) => {
// ...
}
}
Usage: builder!(pub struct User { pub name: String } => UserBuilder);
This is clear.
Handling Corner Cases:
$(...)* handles empty lists (0 matches).build() to succeed. If the user wants optional fields in the final struct, they should define them as Option in the input struct.Code Construction:
Let's write the final code.
#[macro_export]
macro_rules! make_builder {
(
$(#[$struct_meta:meta])*
$vis:vis struct $name:ident {
$(
$(#[$field_meta:meta])*
$field_vis:vis $field_name:ident : $field_type:ty
),* $(,)?
}
) => {
// Generate the original struct
$(#[$struct_meta])*
$vis struct $name {
$(
$(#[$field_meta])*
$field_vis $field_name : $field_type
),*
}
// We need a name for the builder.
// Since we can't concat identifiers, we will implement a trait or a separate struct?
// Let's stick to the problem statement: "generates a Builder pattern".
// The cleanest way without external crates is to define a `builder()` method on the struct
// that returns a generic Builder or a specific struct passed by the user.
// Let's use the most common pattern for declarative macros:
// Accept the builder name as an additional argument.
}
}
Pivot: The prompt is open-ended ("Construct a... macro"). I should provide the most useful version. The most useful version handles the naming.
I'll use the pattern: make_builder!(StructName, BuilderName { ... });
Let's refine the implementation details:
build() return type: Result<$name, Box<dyn Error>> or String or a custom error? Using String is easiest for a demo without dependencies.new(): standard.Let's construct the final response. I will provide the macro and an example of how to use it.
Structure of the explanation:
Since Rust's macro_rules! cannot automatically generate new identifiers (like appending Builder to a struct name) without external crates, this macro takes the name of the desired Builder struct as a second argument.
macro_rules! make_builder {
// Pattern matches:
// $name: The name of the target struct (e.g., MyStruct)
// $builder: The name of the builder struct to generate (e.g., MyStructBuilder)
// $fields: The list of fields (repeated vis name : type)
(
$(#[$struct_meta:meta])* // Optional struct attributes (like #[derive(Debug)])
$struct_vis:vis struct $name:ident as $builder:ident {
$(
$(#[$field_meta:meta])* // Optional field attributes
$field_vis:vis $field_name:ident : $field_type:ty
),* $(,)?
}
) => {
// 1. Generate the Original Struct
$(#[$struct_meta])*
$struct_vis struct $name {
$(
$(#[$field_meta])*
$field_vis $field_name : $field_type
),*
}
// 2. Generate the Builder Struct
// We make the fields public or accessible within the module,
// and wrap them in Option.
#[derive(Default)]
$struct_vis struct $builder {
$(
$field_name: Option<$field_type>
),*
}
// 3. Implement the Build Logic
impl $builder {
// Constructor
$struct_vis fn new() -> Self {
Self::default()
}
// Setter methods
$(
$struct_vis fn $field_name(mut self, value: $field_type) -> Self {
self.$field_name = Some(value);
self
}
)*
// Final build method
$struct_vis fn build(self) -> Result<$name, &'static str> {
// Check if all fields are set (Some)
$(
if self.$field_name.is_none() {
return Err(concat!("Missing field: ", stringify!($field_name)));
}
)*
Ok($name {
$(
$field_name: self.$field_name.unwrap()
),*
})
}
}
// 4. Helper to start building from the original struct (Optional convenience)
impl $name {
$struct_vis fn builder() -> $builder {
$builder::new()
}
}
};
}
Here is how you would use the macro in your code:
// Define the struct using the macro
make_builder! {
// Attributes work too
#[derive(Debug, Clone)]
pub struct User as UserBuilder {
pub id: u32,
pub username: String,
pub email: String,
// Optional field logic isn't built-in to the macro above
// (all fields are required), but this demonstrates the syntax.
pub active: bool
}
}
fn main() {
// 1. Create a builder instance
let user = User::builder()
.id(1)
.username("alice".to_string())
.email("alice@example.com".to_string())
.active(true)
.build(); // Returns Result<User, &str>
match user {
Ok(u) => println!("User created: {:?}", u),
Err(e) => println!("Error creating user: {}", e),
}
// 2. Example of a failed build (missing field)
let incomplete_user = UserBuilder::new()
.id(2)
.username("bob".to_string())
.build(); // Missing email and active
match incomplete_user {
Ok(_) => println!("This won't happen"),
Err(e) => println!("Failed as expected: {}", e),
}
}
$name), the desired builder name ($builder), and the list of fields ($($field_name : $field_type),*).$builder) where every field is wrapped in Option. We derive Default so all fields initialize to None.$(), it generates a method for every field. Each method takes self (consuming the builder), sets the value in Some(value), and returns self allowing for chaining.build method iterates through every field. If any is None, it returns an error message string indicating which field is missing. If all are present, it unwraps them and constructs the final struct.Problem: I still need a name for the builder struct. I cannot construct $name Builder in declarative macros.
Workaround: Use a generic name like Builder inside a module named after the struct, or require the user to pass it.
User requirement: "generates a Builder pattern for a given struct".
Let's stick to a specific output structure. I will generate the original struct and an impl block.
Wait, if I generate the struct, I can't easily change field types to Option in a separate struct without repeating the definition.
Actually, the standard "declarative macro builder" usually defines both the struct and the builder.
Let's assume the builder name is provided or just use Builder for simplicity? No, that causes collisions.
Let's try the approach where the user provides the struct definition inside the macro, and the macro generates the struct AND a Builder struct.
To solve the naming issue, let's just ask for the builder name explicitly in the macro input to keep it simple and standard for declarative macros (unless using paste, which isn't vanilla).
Revised Input:
builder!(MyStruct, MyStructBuilder { ... });
This is the most robust way without external crates.
macro_rules! definition.main function showing the macro in action.Self-Correction during coding:
Ensure the macro handles trailing commas $(,)?.
Ensure the build method handles the unwrap gracefully (converting Option to Result).
Final check on the build method:
$(
let $field_name = self.$field_name.ok_or(format!("Field '{}' not set", stringify!($field_name)))?;
)*
Ok($name { $($field_name),* })
This is a very clean way to do it inside the macro expansion.
Let's double check the macro pattern syntax.
$name:ident for the struct name.
$builder:ident for the builder name.
{ $($f:ident : $t:ty),* } for the fields.
And I should include visibility modifiers to be thorough.
Let's do:
($vis:vis struct $name:ident as $builder:ident { $($f_vis:vis $f:ident: $t:ty),* $(,)? })
This syntax is readable.
One neat trick:
Can I implement a builder() method on the original struct?
Yes.
impl $name {
pub fn builder() -> $builder {
$builder::new()
}
}
This makes the API nicer (MyStruct::builder() instead of MyStructBuilder::new()).
Final Plan:
macro_rules! make_builder.vis struct StructName as BuilderName { fields }.StructName struct.BuilderName struct (with Option fields).impl StructName (with builder() fn).impl BuilderName (with new(), setters, build()).This covers the full "Builder Pattern". Here is a complete implementation of a declarative macro in Rust that generates the Builder pattern for a struct.