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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! 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 TokenStream;
use TokenStream as TokenStream2;
use ;
use ;
use crate::;
/// 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>,
/// }
/// ```
///
/// ## Errors
///
/// When a builder can fail, the `.build` function will return an `Result` that contains the built
/// value or a descriptive error.
///
/// If any of these cases are true, the `.build` function will return a `Result`:
///
/// **A field is required**
/// By default all fields are required, barring some exceptions (field is `Option`, field has a
/// default value, field is `repeat`, etc)
///
/// **`repeat_n` is set**
/// If `repeat_n` is set for any field, then `.build` will return an error if the range is not
/// satisfied.
///
/// **Other Cases**
/// There are other cases where `.build` can fail, this list is non-exhaustive.
///
/// ### Type-State Builder
///
/// If `kind` is set to `"type-state"`, then the builder will _not_ return a Result, as all build
/// conditions are validated at compile-time.
///
/// ## Builder Attributes
///
/// ### **`kind`**
///
/// #### Possible Values
///
/// **`"owned"`**
/// The builder functions consume and generate owned values
///
/// ```
/// # use bauer::Builder;
/// #[derive(Builder)]
/// #[builder(kind = "owned")]
/// pub struct Foo {
/// a: u32,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let foo: Foo = Foo::builder()
/// .a(42)
/// .build()?;
/// # Ok(()) }
/// ```
///
/// **`"borrowed"`**
/// The builder functions operate on mutable references to the builder
///
/// _Note: After calling `.build()`, the builder is reset_
///
/// ```
/// # use bauer::Builder;
/// #[derive(Builder)]
/// #[builder(kind = "borrowed")]
/// pub struct Foo {
/// a: u32,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut builder = Foo::builder();
/// builder.a(42);
/// let foo: Foo = builder.build()?;
/// assert_eq!(foo.a, 42);
/// # Ok(()) }
/// ```
///
/// **`"type-state"`**
/// The builder and its functions are generated in a way that uses the type-state pattern. This
/// means that things like required fields can be enforced at compile-time. Due to the constraints
/// with type-state builders, some attributes may be limited. All limitations are documented with
/// the attributes.
///
/// The `.build` function will never return an error, as it is only possible to call when building
/// the final structure is infallible.
///
/// ```compile_fail
/// # use bauer::Builder;
/// #[derive(Builder)]
/// #[builder(kind = "type-state")]
/// pub struct Foo {
/// a: u32,
/// }
///
/// let foo: Foo = Foo::builder().build(); // fails to compile
/// ```
///
/// Default: `"owned"`
///
/// ### **`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 });
/// ```
///
/// ### **`repeat`**
///
/// Make the method accept only a single item and build a list from it
///
/// When using a data structure that does not have the inner type as its singular generic, the type
/// can be specified using `repeat = <type>`.
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// pub struct Foo {
/// #[builder(repeat)]
/// items: Vec<u32>,
/// #[builder(repeat = char)]
/// chars: String,
/// }
///
/// let foo = Foo::builder()
/// .items(0)
/// .items(1)
/// .items(2)
/// .chars('a')
/// .chars('b')
/// .chars('c')
/// .build();
/// assert_eq!(
/// foo,
/// Foo {
/// items: vec![0, 1, 2],
/// chars: String::from("abc"),
/// },
/// );
/// ```
///
/// ### **`repeat_n`**
///
/// Attribute `repeat` must also be specified.
///
/// Ensure that the length of items supplied via repeat is within a certain range. The range can
/// be any pattern that may be used in a `match` statement. If this range is not met, an error
/// will be returned.
///
/// #### Type-state Builder
///
/// When using the type-state kind, the value used is limited to the following (where `N` and `M`
/// are integer literals)
///
/// - Integer Literals (`N`)
/// - Closed Ranges (`N..M` or `N..=M`)
/// - Minimum Ranges (`N..`)
///
/// Note: The length of the range is limited to 64, because big ranges slow compile-time. If you
/// require a larger range and the compile-time sacrifice is worth it, you can enable the
/// `unlimited_range` feature.
///
/// ```
/// # 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] });
/// ```
///
/// ### **`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") });
/// ```
///
/// ### **`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();
/// ```
///
/// ### **`adapter`**
///
/// Create a custom implementation for the generated function. The adapter uses the closure syntax
/// with types specified and will generate the method accordingly.
///
/// Any number of arguments are allowed and will be used in the generated function.
///
/// Conflicts with `into` and `tuple`.
///
/// ```
/// # use bauer::Builder;
/// # const _: &str = stringify!(
/// #[derive(Builder)]
/// # );
/// # #[derive(Builder, PartialEq, Debug)]
/// pub struct Foo {
/// #[builder(adapter = |x: u32, y: u32| format!("{}/{}", x, y))]
/// field: String,
/// }
///
/// let foo = Foo::builder()
/// .field(5, 23)
/// .build()
/// .unwrap();
/// assert_eq!(foo, Foo { field: String::from("5/23") });
/// ```