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
#![deny(missing_docs)]

//! This crate contains a `builder!` macro to declare a struct and a corresponding builder.
//!
//! The macro is inspired from [jadpole/builder-macro][1], and is designed to remove duplication of field declaration,
//! as well as generating appropriate setter methods.
//!
//! Specify the dependency in your crate's `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! builder_macro = "0.1.1" # check https://crates.io/crates/builder_macro for the latest version
//! ```
//!
//! Include the macro inside your crate's `lib.rs` or `main.rs`.
//!
//! ```rust
//! #[macro_use]
//! extern crate builder_macro;
//! #
//! # fn main() {} // necessary to allow doc test to pass
//! ```
//!
//! # Examples
//!
//! ## Non-consuming Builder
//!
//! The simplest usage of the builder macro to generate a [non-consuming builder][2] is:
//!
//! ```rust,ignore
//! builder!(BuilderName -> StructName {
//!     fieldname: Type = Some(default_value), // or None if there is no sensible default
//! });
//! ```
//!
//! The above will generate a module private struct and a non-consuming builder with a single private field.
//!
//! For example, given the following declaration:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate builder_macro;
//! #
//! # fn main() {
//! builder!(BuilderName -> StructName {
//!     value: i32 = Some(1),
//! });
//! # }
//! ```
//!
//! The generated code will function as follows:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate builder_macro;
//! #
//! # fn main() {
//! struct StructName {
//!     value: i32,
//! }
//!
//! /// Auto-generated builder
//! struct BuilderName {
//!     value: Option<i32>,
//! }
//!
//! impl BuilderName {
//!     /// Construct the builder
//!     pub fn new() -> BuilderName { BuilderName { value: Some(1), } }
//!
//!     /// Build the struct
//!     pub fn build(&self) -> StructName {
//!         let value = self.value.clone().unwrap();
//!         StructName{value: value,}
//!     }
//!
//!     #[allow(dead_code)]
//!     /// Auto-generated setter
//!     pub fn value(&mut self, value: i32) -> &mut Self {
//!         self.value = Some(value);
//!         self
//!     }
//! }
//! # }
//! ```
//!
//! To generate public structs and builders, see [visbility](#visibility).
//!
//! ## Consuming Builder
//!
//! To generate a [consuming builder][3], instead of using `->`, use `=>` between the builder name and the target struct
//! name.
//!
//! ```rust
//! # #[macro_use]
//! # extern crate builder_macro;
//! #
//! # fn main() {
//! trait Magic {
//!     fn abracadabra(&mut self) -> i32;
//! }
//! struct Dust {
//!     value: i32,
//! }
//! impl Magic for Dust {
//!     fn abracadabra(&mut self) -> i32 {
//!         self.value
//!     }
//! }
//!
//! // Note: we use => instead of -> for the consuming variant of the builder
//! builder!(MyStructBuilder => MyStruct {
//!     field_trait: Box<Magic> = Some(Box::new(Dust { value: 1 })),
//!     field_vec: Vec<Box<Magic>> = Some(vec![Box::new(Dust { value: 2 })]),
//! });
//!
//! let mut my_struct = MyStructBuilder::new().build();
//!
//! assert_eq!(my_struct.field_trait.abracadabra(), 1);
//! assert_eq!(my_struct.field_vec[0].abracadabra(), 2);
//! # }
//! ```
//!
//! ## Visibility
//!
//! Generate a builder and struct with module private visibility:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate builder_macro;
//! #
//! # fn main() {
//! builder!(MyStructBuilder -> MyStruct {
//!     field_i32: i32 = Some(123),
//!     field_str: &'static str = Some("abc"),
//! });
//!
//! let my_struct = MyStructBuilder::new()
//!     .field_i32(456)
//!     .build();
//! assert_eq!(my_struct.field_i32, 456);
//! assert_eq!(my_struct.field_str, "abc"); // uses default
//! # }
//! ```
//!
//! Generate a builder and struct with public visibility:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate builder_macro;
//! #
//! # fn main() {
//! mod inner {
//!     builder!(pub MyStructBuilder -> MyStruct {
//!         pub field_i32: i32 = Some(123),
//!         field_str: &'static str = Some("abc"),
//!     });
//! }
//!
//! let my_struct = inner::MyStructBuilder::new()
//!     .field_i32(456)
//!     .build();
//! assert_eq!(my_struct.field_i32, 456);
//!
//! // The next line will fail compilation if uncommented as field_str is private
//! // assert_eq!(my_struct.field_str, "abc");
//! # }
//! ```
//!
//! ## Full Usage Format
//!
//! The full macro usage format is:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate builder_macro;
//! #
//! # fn main() {
//! // We declare the builder insider a module simply to demonstrate scope
//! mod inner {
//!     builder! {
//!         /// StructName is an example struct.
//!         /// These docs are copied over to the generated struct.
//!         pub BuilderName -> StructName {
//!             /// a_field is an i32 which must be between 0 and 100 inclusive
//!             // the trailing comma is mandatory due to how the macro is parsed
//!             pub a_field: i32 = Some(50),
//!
//!             // None means no default value, a value must be specified when building
//!             // meta attributes are copied over to the struct's fields
//!             #[allow(dead_code)]
//!             a_private_field: &'static str = None,
//!         }, assertions: {
//!             assert!(a_field >= 0);
//!             assert!(a_field <= 100);
//!             // Yes you can assert on private fields
//!             assert!(!a_private_field.is_empty());
//!         }
//!     }
//! }
//!
//! let my_struct = inner::BuilderName::new()
//!                     .a_private_field("I must set this to a non-empty string")
//!                     .build();
//!
//! assert_eq!(50, my_struct.a_field);
//! # }
//! ```
//!
//! The above will be similar to writing the following:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate builder_macro;
//! #
//! # fn main() {
//! mod inner {
//!     /// StructName is an example struct.
//!     /// These docs are copied over to the generated struct.
//!     pub struct StructName {
//!         /// a_field is an i32 which must be between 0 and 100 inclusive
//!         pub a_field: i32,
//!         #[allow(dead_code)]
//!         a_private_field: &'static str,
//!     }
//!
//!     /// Auto-generated builder
//!     pub struct BuilderName {
//!         /// a_field is an i32 which must be between 0 and 100 inclusive
//!         a_field: Option<i32>,
//!         #[allow(dead_code)]
//!         a_private_field: Option<&'static str>,
//!     }
//!
//!     impl BuilderName {
//!         /// Construct the builder
//!         pub fn new() -> BuilderName {
//!             BuilderName{a_field: Some(50), a_private_field: None,}
//!         }
//!
//!         /// Build the struct
//!         pub fn build(&self) -> StructName {
//!             let a_field = self.a_field.clone().unwrap();
//!             let a_private_field = self.a_private_field.clone().unwrap();
//!
//!             assert!(a_field >= 0);
//!             assert!(a_field <= 100);
//!             assert!(!a_private_field.is_empty());
//!
//!             StructName {
//!                 a_field: a_field,
//!                 a_private_field: a_private_field,
//!             }
//!         }
//!
//!         #[allow(dead_code)]
//!         /// Auto-generated setter
//!         pub fn a_field(&mut self, value: i32) -> &mut Self {
//!             self.a_field = Some(value);
//!             self
//!         }
//!
//!         #[allow(dead_code)]
//!         /// Auto-generated setter
//!         pub fn a_private_field(&mut self, value: &'static str)
//!          -> &mut Self {
//!             self.a_private_field = Some(value);
//!             self
//!         }
//!     }
//! }
//!
//! let my_struct = inner::BuilderName::new()
//!     .a_private_field("I must set this to a non-empty string")
//!     .build();
//!
//! assert_eq!(50, my_struct.a_field);
//! # }
//! ```
//!
//! [1]: http://jadpole.github.io/rust/builder-macro
//! [2]: https://doc.rust-lang.org/style/ownership/builders.html#non-consuming-builders-preferred
//! [3]: https://doc.rust-lang.org/style/ownership/builders.html#consuming-builders
//!

#[macro_use]
mod declare_struct_and_builder;
#[macro_use]
mod parse_struct;

#[macro_export]
/// Macro to declare a struct and a corresponding builder. See [the module documentation](index.html) for more.
macro_rules! builder {
    ( $( $SPEC:tt )* )
    =>
    {
        parse_struct! {
            meta: [],
            spec: $( $SPEC )*
        }
    };
}

#[cfg(test)]
mod test {
    #[test]
    fn generates_struct_and_builder_with_defaults() {
        builder!(MyStructBuilder -> MyStruct {
            field_i32: i32 = Some(123),
            field_str: &'static str = Some("abc"),
        });

        let my_struct = MyStructBuilder::new().build();
        assert_eq!(my_struct.field_i32, 123);
        assert_eq!(my_struct.field_str, "abc");
    }

    #[test]
    fn generates_struct_and_builder_with_parameters() {
        builder!(MyStructBuilder -> MyStruct {
            field_i32: i32 = Some(123),
            field_str: &'static str = Some("abc"),
        });

        let my_struct = MyStructBuilder::new()
            .field_i32(456)
            .field_str("str")
            .build();
        assert_eq!(my_struct.field_i32, 456);
        assert_eq!(my_struct.field_str, "str");
    }

    #[test]
    fn generates_struct_and_builder_with_generic_types() {
        builder!(MyStructBuilder -> MyStruct {
            field_vec: Vec<i32> = Some(vec![123]),
        });

        let my_struct = MyStructBuilder::new().build();
        let my_struct_2 = MyStructBuilder::new().field_vec(vec![234, 456]).build();

        assert_eq!(my_struct.field_vec, vec![123]);
        assert_eq!(my_struct_2.field_vec, vec![234, 456]);
    }

    #[test]
    fn generates_struct_and_builder_with_traits_using_default_values() {
        trait Magic {
            fn abracadabra(&mut self) -> i32;
        }
        struct Dust {
            value: i32,
        };
        impl Magic for Dust {
            fn abracadabra(&mut self) -> i32 {
                self.value
            }
        }

        // Note: we use => instead of -> for the consuming variant of the builder
        builder!(MyStructBuilder => MyStruct {
            field_trait: Box<Magic> = Some(Box::new(Dust { value: 1 })),
            field_vec: Vec<Box<Magic>> = Some(vec![Box::new(Dust { value: 2 })]),
        });

        let mut my_struct = MyStructBuilder::new().build();

        assert_eq!(my_struct.field_trait.abracadabra(), 1);
        assert_eq!(my_struct.field_vec[0].abracadabra(), 2);
    }

    #[test]
    fn generates_struct_and_builder_with_traits_specifying_parameters() {
        trait Magic {
            fn abracadabra(&mut self) -> i32;
        }
        struct Dust {
            value: i32,
        };
        impl Magic for Dust {
            fn abracadabra(&mut self) -> i32 {
                self.value
            }
        }

        // Note: we use => instead of -> for the consuming variant of the builder
        builder!(MyStructBuilder => MyStruct {
            field_trait: Box<Magic> = None,
            field_vec: Vec<Box<Magic>> = None,
        });

        let mut my_struct = MyStructBuilder::new()
            .field_trait(Box::new(Dust { value: 1 }))
            .field_vec(vec![Box::new(Dust { value: 2 })])
            .build();

        assert_eq!(my_struct.field_trait.abracadabra(), 1);
        assert_eq!(my_struct.field_vec[0].abracadabra(), 2);
    }

    #[test]
    #[should_panic(expected = "assertion failed")]
    fn generated_build_method_uses_assertions() {
        builder!(MyStructBuilder -> MyStruct {
            field_i32: i32 = Some(123),
        },
        assertions: {
            assert!(field_i32 > 0);
        });

        let my_struct = MyStructBuilder::new()
            .field_i32(-1)
            .build();
        assert_eq!(my_struct.field_i32, -1);
    }

    mod visibility_test {
        builder!(OuterStructBuilder -> OuterStruct { field_i32: i32 = Some(1), });

        mod inner {
            builder!(MyStructBuilder -> MyStruct { field_i32: i32 = Some(1), });
            builder!(pub InnerStructBuilder -> InnerStruct { pub field_i32: i32 = Some(1), });

            #[test]
            fn can_access_private_struct_from_within_module() {
                let my_struct = MyStructBuilder::new().build();
                assert_eq!(my_struct.field_i32, 1);
            }

            #[test]
            fn can_access_private_outer_struct_from_inner_module() {
                let outer_struct = super::OuterStructBuilder::new().build();
                assert_eq!(outer_struct.field_i32, 1);
            }
        }

        #[test]
        fn can_access_public_struct_from_outside_module() {
            let inner_struct = inner::InnerStructBuilder::new().build();
            assert_eq!(inner_struct.field_i32, 1);
        }

        // The following causes a compilation failure if uncommented
        // #[test]
        // fn cannot_access_private_struct() {
        //     let my_struct = inner::MyStructBuilder::new().build();
        //     assert_eq!(my_struct.field_i32, 0);
        // }
    }
}