bauer 0.2.0

A derive macro for automatically generating the builder pattern
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! A derive macro for automatically generating the builder pattern
//!
//! ```rust
//! use bauer::Builder;
//!
//! # const _: &str = stringify!(
//! #[derive(Builder)]
//! # );
//! # #[derive(Builder, PartialEq, Debug)]
//! pub struct Foo {
//!     bar: u32,
//! }
//!
//! let foo: Foo = Foo::builder()
//!     .bar(42)
//!     .build()
//!     .unwrap();
//!
//! assert_eq!(foo, Foo { bar: 42, });
//! ```

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, format_ident, quote, quote_spanned};
use std::fmt::Write;
use syn::{DeriveInput, Ident, Type, parse::ParseStream, parse_macro_input, spanned::Spanned};

use crate::{
    builder::{BuilderAttr, Kind},
    field::{BuilderField, Repeat},
};

mod builder;
mod field;

pub(crate) fn get_single_generic<'a>(ty: &'a Type, name: Option<&str>) -> Option<&'a Type> {
    match ty {
        Type::Path(path)
            if path
                .path
                .segments
                .last()
                .is_some_and(|s| name.is_none_or(|name| s.ident == name))
                && path.path.segments.len() == 1 =>
        {
            let option = path
                .path
                .segments
                .last()
                .expect("checked in guard condition");

            let arg = match option.arguments {
                syn::PathArguments::AngleBracketed(ref args) if args.args.len() == 1 => {
                    let Some(syn::GenericArgument::Type(arg)) = args.args.first() else {
                        return None;
                    };
                    arg
                }
                _ => return None,
            };
            Some(arg)
        }
        Type::Array(arr) if name.is_none() => Some(&arr.elem),
        Type::Slice(slice) if name.is_none() => Some(&slice.elem),
        Type::Reference(r) => get_single_generic(&r.elem, name),
        _ => None,
    }
}

/// The main macro.
///
/// The return type of `.build()` on the builder is a Result if the build can fail due to missing
/// fields, invalid number of repeat arguments (`repeat_n`), etc.  If a call to `.build()` can
/// _not_ fail, it will return the built struct directly.
///
/// ## Usage
///
/// ```
/// use bauer::Builder;
///
/// #[derive(Builder)]
/// pub struct Foo {
///     #[builder(default = "42")]
///     pub field_a: u32,
///     pub field_b: bool,
///     #[builder(into)]
///     pub field_c: String,
///     #[builder(repeat, repeat_n = 1..=3)]
///     pub field_d: Vec<f64>,
/// }
/// ```
///
/// ## Builder Attributes
///
/// ### **`kind`**
///
/// Possible values: `"owned"`, `"borrowed"`  
/// Default: `"owned"`
///
/// Whether the builder should be passed around as an owned value or a mutable reference.
///
/// ```
/// # use bauer::Builder;
/// #[derive(Builder)]
/// #[builder(kind = "borrowed")]
/// pub struct Foo {
///     a: u32,
/// }
/// ```
///
/// ### **`prefix`**/**`suffix`**
///
/// Default: `prefix = "", suffix = ""`
///
/// Set the prefix or suffix for the generated builder functions
///
/// ```
/// # use bauer::Builder;
/// #[derive(Builder)]
/// #[builder(prefix = "set_")]
/// pub struct Foo {
///     a: u32,
/// }
///
/// let f = Foo::builder()
///     .set_a(42)
///     .build()
///     .unwrap();
/// ```
///
/// ### **`visibility`**
///
/// Default: visibility of the struct
///
/// Set the visibilty for the created builder
///
/// The visibility can be set to `pub(self)` in order to make the builder private to the current
/// module.
///
/// ```
/// # use bauer::Builder;
/// #[derive(Builder)]
/// #[builder(visibility = pub(crate))]
/// pub struct Foo {
///     a: u32,
/// }
/// ```
///
/// ## Fields Attributes
///
/// ### **`default`**
///
/// Argument: Optional String
///
/// If provided, the field does not need to be specified, and will default to the value provided.
/// If not value is provided to the `default` attribute, then [`Default::default`] will be used.
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// pub struct Foo {
///     #[builder(default)]
///     a: u32, // defaults to 0
///     #[builder(default = "std::f32::consts::PI")]
///     b: f32, // defaults to PI
/// }
///
/// let foo = Foo::builder().build();
/// assert_eq!(foo, Foo { a: 0, b: std::f32::consts::PI });
///
/// let foo = Foo::builder()
///     .a(42)
///     .build();
/// assert_eq!(foo, Foo { a: 42, b: std::f32::consts::PI });
/// ```
///
/// ### **`into`**
///
/// Make the method accept anything can be turned into the field.
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// pub struct Foo {
///     #[builder(into)]
///     a: String,
/// }
///
/// let foo = Foo::builder()
///     .a("hello")
///     .build()
///     .unwrap();
/// assert_eq!(foo, Foo { a: String::from("hello") });
/// ```
///
/// ### **`repeat`**
///
/// Make the method accept only a single item and build a list from it
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// pub struct Foo {
///     #[builder(repeat)]
///     items: Vec<u32>,
/// }
///
/// let foo = Foo::builder()
///     .items(0)
///     .items(1)
///     .items(2)
///     .build();
/// assert_eq!(foo, Foo { items: vec![0, 1, 2] });
/// ```
///
/// ### **`repeat_n`**
///
/// Attribute `repeat` must also be specified.
///
/// Ensure that the length of items supplied via repeat is within a certain range.  If this range
/// is not met, an error will be returned.
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// pub struct Foo {
///     #[builder(repeat, repeat_n = 2..=3)]
///     items: Vec<u32>,
/// }
///
/// let foo = Foo::builder()
///     .items(0)
///     .items(1)
///     .items(2)
///     .build()
///     .unwrap();
/// assert_eq!(foo, Foo { items: vec![0, 1, 2] });
///
/// let foo = Foo::builder()
///     .items(0)
///     .build()
///     .unwrap_err();
/// assert_eq!(foo, FooBuildError::RangeItems(1));
/// ```
///
/// ### **`rename`**
///
/// Make the function that is generated use a different name from field itself.
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// pub struct Foo {
///     #[builder(repeat, rename = "item")]
///     items: Vec<u32>,
/// }
///
/// let foo = Foo::builder()
///     .item(0)
///     .item(1)
///     .build();
/// assert_eq!(foo, Foo { items: vec![0, 1] });
/// ```
///
/// ### **`skip_prefix`**/**`skip_suffix`**
///
/// If a prefix or a suffix is specified in the builder attributes, skip applying those to the name
/// of this function.  This is epecially useful with `rename`.
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// #[builder(prefix = "set_")]
/// pub struct Foo {
///     #[builder(repeat, rename = "item", skip_prefix)]
///     items: Vec<u32>,
/// }
///
/// let foo = Foo::builder()
///     .item(0)
///     .item(1)
///     .build();
/// assert_eq!(foo, Foo { items: vec![0, 1] });
/// ```
///
/// ### **`tuple`**
///
/// Rather than accepting a field that is a tuple by value, accept each element of the tuple as a
/// separate parameters to the setter function.
///
/// If names are specified using `tuple(name1, name2, ...)`, they will be used for the names of the
/// parameters to the function (see example).
///
/// Note: If used with `repeat`, `repeat` must come before `tuple`.
///
/// ```
/// # use bauer::Builder;
/// #[derive(Builder)]
/// pub struct Foo {
///     #[builder(tuple)]
///     tuple: (i32, i32),
///     #[builder(tuple(a, b))]
///     tuple_names: (i32, i32),
///     #[builder(into, tuple(a, b))]
///     tuple_into: (String, f64),
///     #[builder(repeat, tuple(foo, bar))]
///     tuples: Vec<(i32, i32)>,
/// }
///
/// let foo = Foo::builder()
///     .tuple(0, 1)
///     .tuple_names(2, 3)
///     .tuple_into("pi", 3.14)
///     .tuples(4, 5)
///     .tuples(6, 7)
///     .build();
/// ```
#[proc_macro_derive(Builder, attributes(builder))]
pub fn builder(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let ident = &input.ident;
    let vis = &input.vis;

    let attr = input.attrs.iter().find(|a| a.path().is_ident("builder"));
    let attr: BuilderAttr = if let Some(attr) = attr {
        match attr.parse_args_with(|ps: ParseStream| BuilderAttr::parse(ps, vis.clone())) {
            Ok(a) => a,
            Err(e) => return e.to_compile_error().into(),
        }
    } else {
        BuilderAttr::new(vis.clone())
    };

    let data_struct = match input.data {
        syn::Data::Struct(ref data_struct) => data_struct,
        syn::Data::Enum(data_enum) => {
            return syn::Error::new(data_enum.enum_token.span(), "Enums are not supported.")
                .to_compile_error()
                .into();
        }
        syn::Data::Union(data_union) => {
            return syn::Error::new(data_union.union_token.span(), "Unions are not supported.")
                .to_compile_error()
                .into();
        }
    };

    let (prefix, ret) = match attr.kind {
        Kind::Owned => (quote! { mut }, quote! { Self }),
        Kind::Borrowed => (quote! { &mut }, quote! { &mut Self }),
    };
    let builder_vis = attr.vis;

    let builder = format_ident!("{}Builder", ident);
    let build_err = format_ident!("{}BuildError", ident);
    let fields_named: Vec<_> = match data_struct.fields {
        syn::Fields::Named(ref fields_named) => match fields_named
            .named
            .iter()
            .map(BuilderField::try_from)
            .collect::<Result<_, _>>()
        {
            Ok(v) => v,
            Err(e) => return e.to_compile_error().into(),
        },
        syn::Fields::Unnamed(_) => {
            return syn::Error::new(ident.span(), "Unnamed fields are not supported.")
                .to_compile_error()
                .into();
        }
        syn::Fields::Unit => {
            return syn::Error::new(ident.span(), "Unit structs are not supported.")
                .to_compile_error()
                .into();
        }
    };

    let fields: TokenStream2 = fields_named
        .iter()
        .map(|f| {
            let ident = &f.ident;
            if let Some(Repeat { inner_ty, .. }) = &f.attr.repeat {
                quote! {
                    #ident: ::std::vec::Vec<#inner_ty>,
                }
            } else {
                let ty = &f.ty;
                quote! {
                    #ident: ::core::option::Option<#ty>,
                }
            }
        })
        .collect();

    let functions: TokenStream2 = fields_named
        .iter()
        .map(|f| {
            let field_name = &f.ident;
            let ident = f.attr.rename.as_ref().unwrap_or(&f.ident);
            let ty = f.attr.repeat.as_ref().map(|r| &r.inner_ty).unwrap_or(&f.ty);

            let mut fn_ident = String::with_capacity(attr.prefix.len() + attr.suffix.len());
            if !f.attr.skip_prefix {
                fn_ident.push_str(&attr.prefix);
            }
            write!(fn_ident, "{}", ident).expect("Inserting into string will never fail");
            if !f.attr.skip_suffix {
                fn_ident.push_str(&attr.suffix);
            }
            let fn_ident = Ident::new(&fn_ident, ident.span());

            let (args, value) = match (ty, &f.attr.tuple) {
                (Type::Tuple(tuple), Some(t)) => {
                    let names = t.clone().unwrap_or_else(|| {
                        (0..tuple.elems.len())
                            .map(|n| format_ident!("{}_{}", field_name, n))
                            .collect()
                    });

                    let types = tuple.elems.iter();

                    if f.attr.into {
                        (
                            quote! {
                                #(#names: impl ::core::convert::Into<#types>),*
                            },
                            quote! { (#(::core::convert::Into::into(#names)),*) },
                        )
                    } else {
                        (
                            quote! {
                                #(#names: #types),*
                            },
                            quote! { (#(#names),*) },
                        )
                    }
                }
                _ => {
                    let (source, value) = if f.attr.into {
                        (
                            quote! { impl ::core::convert::Into<#ty> },
                            quote! { ::core::convert::Into::into(#field_name) },
                        )
                    } else {
                        (ty.to_token_stream(), field_name.to_token_stream())
                    };

                    (quote! { #field_name: #source }, value)
                }
            };

            let doc = &f.doc;

            if f.attr.repeat.is_some() {
                let vec = &f.ident;
                quote! {
                    #(#doc)*
                    #builder_vis fn #fn_ident(#prefix self, #args) -> #ret {
                        self.#vec.push(#value);
                        self
                    }
                }
            } else {
                quote! {
                    #(#doc)*
                    #builder_vis fn #fn_ident(#prefix self, #args) -> #ret {
                        self.#ident = Some(#value);
                        self
                    }
                }
            }
        })
        .collect();

    let build_err_variants: Vec<_> = fields_named
        .iter()
        .flat_map(|f| {
            let mut variants = Vec::new();
            if let Some(err) = &f.missing_err {
                variants.push(err.to_token_stream());
            }
            if let Some(Repeat {
                len: Some((_, err)),
                ..
            }) = &f.attr.repeat
            {
                variants.push(quote! {
                    #err(usize)
                });
            }
            variants.into_iter()
        })
        .collect();

    let field_names: Vec<_> = fields_named.iter().map(|f| &f.ident).collect();

    let build_fields = fields_named.iter().map(|field| {
        let name = &field.ident;

        if let Some(Repeat { len, .. }) = &field.attr.repeat {
            if let Some((range, err)) = len {
                quote! {
                    #name: match self.#name.len() {
                        #range => self.#name.drain(..).collect(),
                        len => return Err(#build_err::#err(len)),
                    }
                }
            } else {
                quote! {
                    #name: self.#name.drain(..).collect()
                }
            }
        } else if field.wrapped_option {
            quote! {
                #name: self.#name
            }
        } else if let Some(default) = &field.attr.default {
            if let Some(default) = default {
                if field.attr.into {
                    quote! {
                        #name: self.#name.take().unwrap_or_else(|| #default.into())
                    }
                } else {
                    quote! {
                        #name: self.#name.take().unwrap_or_else(|| #default)
                    }
                }
            } else {
                quote_spanned! {
                    field.ty.span() =>
                    #name: self.#name.take().unwrap_or_default()
                }
            }
        } else {
            let err = field
                .missing_err
                .as_ref()
                .expect("missing_err is set when default is none");
            quote! {
                #name: self.#name.take().ok_or(#build_err::#err)?
            }
        }
    });

    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let build_fn = if build_err_variants.is_empty() {
        quote! {
            #builder_vis fn build(#prefix self) -> #ident #ty_generics {
                #ident {
                    #(#build_fields),*
                }
            }
        }
    } else {
        quote! {
            #builder_vis fn build(#prefix self) -> ::core::result::Result<#ident #ty_generics, #build_err> {
                Ok(#ident {
                    #(#build_fields),*
                })
            }
        }
    };

    let build_err_enum = if build_err_variants.is_empty() {
        quote! {}
    } else {
        quote! {
            #[derive(::std::fmt::Debug, ::std::cmp::PartialEq, ::std::cmp::Eq)]
            #builder_vis enum #build_err {
                #(#build_err_variants),*
            }
        }
    };

    quote! {
        #build_err_enum

        #builder_vis struct #builder #ty_generics {
            #fields
        }

        impl #impl_generics #builder #ty_generics #where_clause {
            #functions

            #build_fn
        }

        impl #impl_generics ::core::default::Default for #builder #ty_generics #where_clause {
            fn default() -> Self {
                Self {
                    #(#field_names: ::core::default::Default::default()),*
                }
            }
        }

        impl #impl_generics #ident #ty_generics #where_clause {
            #builder_vis fn builder() -> #builder #ty_generics {
                ::core::default::Default::default()
            }
        }
    }
    .into()
}