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
#![cfg_attr(feature = "cargo-clippy", allow(useless_let_if_seq))]
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, TokenStreamExt};
use syn;

use Bindings;
use BuilderPattern;
use DeprecationNotes;

/// Setter for the struct fields in the build method, implementing
/// `quote::ToTokens`.
///
/// # Examples
///
/// Will expand to something like the following (depending on settings):
///
/// ```rust
/// # extern crate proc_macro2;
/// # #[macro_use]
/// # extern crate quote;
/// # extern crate syn;
/// # #[macro_use]
/// # extern crate derive_builder_core;
/// # use derive_builder_core::{Setter, BuilderPattern};
/// # fn main() {
/// #     let mut setter = default_setter!();
/// #     setter.pattern = BuilderPattern::Mutable;
/// #
/// #     assert_eq!(quote!(#setter).to_string(), quote!(
/// # #[allow(unused_mut)]
/// pub fn foo(&mut self, value: Foo) -> &mut Self {
///     let mut new = self;
///     new.foo = ::std::option::Option::Some(value);
///     new
/// }
/// #     ).to_string());
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Setter<'a> {
    /// Enables code generation for this setter fn.
    pub enabled: bool,
    /// Enables code generation for the `try_` variant of this setter fn.
    pub try_setter: bool,
    /// Visibility of the setter, e.g. `syn::Visibility::Public`.
    pub visibility: syn::Visibility,
    /// How the setter method takes and returns `self` (e.g. mutably).
    pub pattern: BuilderPattern,
    /// Attributes which will be attached to this setter fn.
    pub attrs: &'a [syn::Attribute],
    /// Name of this setter fn.
    pub ident: syn::Ident,
    /// Name of the target field.
    pub field_ident: &'a syn::Ident,
    /// Type of the target field.
    ///
    /// The corresonding builder field will be `Option<field_type>`.
    pub field_type: &'a syn::Type,
    /// Make the setter generic over `Into<T>`, where `T` is the field type.
    pub generic_into: bool,
    /// Make the setter remove the Option wrapper from the setter, remove the need to call Some(...).
    /// when combined with into, the into is used on the content Type of the Option.
    pub strip_option: bool,
    /// Emit deprecation notes to the user.
    pub deprecation_notes: &'a DeprecationNotes,
    /// Bindings to libstd or libcore.
    pub bindings: Bindings,
}

impl<'a> ToTokens for Setter<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        if self.enabled {
            trace!("Deriving setter for `{}`.", self.field_ident);
            let field_type = self.field_type;
            let pattern = self.pattern;
            let vis = &self.visibility;
            let field_ident = self.field_ident;
            let ident = &self.ident;
            let attrs = self.attrs;
            let deprecation_notes = self.deprecation_notes;
            let clone = self.bindings.clone_trait();
            let option = self.bindings.option_ty();
            let into = self.bindings.into_trait();
            let (ty, stripped_option) = match self.strip_option {
                false => (field_type, false),
                true => match extract_type_from_option(field_type) {
                    None => (field_type, false),
                    Some(ty) => (ty, true),
                },
            };

            let self_param: TokenStream;
            let return_ty: TokenStream;
            let self_into_return_ty: TokenStream;

            match pattern {
                BuilderPattern::Owned => {
                    self_param = quote!(self);
                    return_ty = quote!(Self);
                    self_into_return_ty = quote!(self);
                }
                BuilderPattern::Mutable => {
                    self_param = quote!(&mut self);
                    return_ty = quote!(&mut Self);
                    self_into_return_ty = quote!(self);
                }
                BuilderPattern::Immutable => {
                    self_param = quote!(&self);
                    return_ty = quote!(Self);
                    self_into_return_ty = quote!(#clone::clone(self));
                }
            };

            let ty_params: TokenStream;
            let param_ty: TokenStream;
            let mut into_value: TokenStream;

            if self.generic_into {
                ty_params = quote!(<VALUE: #into<#ty>>);
                param_ty = quote!(VALUE);
                into_value = quote!(value.into());
            } else {
                ty_params = quote!();
                param_ty = quote!(#ty);
                into_value = quote!(value);
            }
            if stripped_option {
                into_value = quote!(#option::Some(#into_value));
            }
            tokens.append_all(quote!(
                #(#attrs)*
                #[allow(unused_mut)]
                #vis fn #ident #ty_params (#self_param, value: #param_ty)
                    -> #return_ty
                {
                    #deprecation_notes
                    let mut new = #self_into_return_ty;
                    new.#field_ident = #option::Some(#into_value);
                    new
            }));

            if self.try_setter {
                let try_into = self.bindings.try_into_trait();
                let try_ty_params = quote!(<VALUE: #try_into<#ty>>);
                let try_ident = syn::Ident::new(&format!("try_{}", ident), Span::call_site());
                let result = self.bindings.result_ty();

                tokens.append_all(quote!(
                    #(#attrs)*
                    #vis fn #try_ident #try_ty_params (#self_param, value: VALUE)
                        -> #result<#return_ty, VALUE::Error>
                    {
                        let converted : #ty = value.try_into()?;
                        let mut new = #self_into_return_ty;
                        new.#field_ident = #option::Some(converted);
                        Ok(new)
                }));
            } else {
                trace!("Skipping try_setter for `{}`.", self.field_ident);
            }
        } else {
            trace!("Skipping setter for `{}`.", self.field_ident);
        }
    }
}

// adapted from https://stackoverflow.com/a/55277337/469066
// Note that since syn is a parser, it works with tokens.
// We cannot know for sure that this is an Option.
// The user could, for example, `type MaybeString = std::option::Option<String>`
// We cannot handle those arbitrary names.
fn extract_type_from_option(ty: &syn::Type) -> Option<&syn::Type> {
    use syn::punctuated::Pair;
    use syn::token::Colon2;
    use syn::{GenericArgument, Path, PathArguments, PathSegment};

    fn extract_type_path(ty: &syn::Type) -> Option<&Path> {
        match *ty {
            syn::Type::Path(ref typepath) if typepath.qself.is_none() => Some(&typepath.path),
            _ => None,
        }
    }

    // TODO store (with lazy static) precomputed parsing of Option when support of rust 1.18 will be removed (incompatible with lazy_static)
    // TODO maybe optimization, reverse the order of segments
    fn extract_option_segment(path: &Path) -> Option<Pair<&PathSegment, &Colon2>> {
        let idents_of_path = path
            .segments
            .iter()
            .into_iter()
            .fold(String::new(), |mut acc, v| {
                acc.push_str(&v.ident.to_string());
                acc.push('|');
                acc
            });
        vec![
            "Option|",
            "std|option|Option|",
            "core|option|Option|",
        ]
        .into_iter()
        .find(|s| &idents_of_path == *s)
        .and_then(|_| path.segments.last())
    }

    extract_type_path(ty)
        .and_then(|path| extract_option_segment(path))
        .and_then(|pair_path_segment| {
            let type_params = &pair_path_segment.into_value().arguments;
            // It should have only on angle-bracketed param ("<String>"):
            match *type_params {
                PathArguments::AngleBracketed(ref params) => params.args.first(),
                _ => None,
            }
        })
        .and_then(|generic_arg| match *generic_arg.into_value() {
            GenericArgument::Type(ref ty) => Some(ty),
            _ => None,
        })
}

/// Helper macro for unit tests. This is _only_ public in order to be accessible
/// from doc-tests too.
#[doc(hidden)]
#[macro_export]
macro_rules! default_setter {
    () => {
        Setter {
            enabled: true,
            try_setter: false,
            visibility: syn::parse_str("pub").unwrap(),
            pattern: BuilderPattern::Mutable,
            attrs: &vec![],
            ident: syn::Ident::new("foo", ::proc_macro2::Span::call_site()),
            field_ident: &syn::Ident::new("foo", ::proc_macro2::Span::call_site()),
            field_type: &syn::parse_str("Foo").unwrap(),
            generic_into: false,
            strip_option: false,
            deprecation_notes: &Default::default(),
            bindings: Default::default(),
        };
    };
}

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use super::*;

    #[test]
    fn immutable() {
        let mut setter = default_setter!();
        setter.pattern = BuilderPattern::Immutable;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                pub fn foo(&self, value: Foo) -> Self {
                    let mut new = ::std::clone::Clone::clone(self);
                    new.foo = ::std::option::Option::Some(value);
                    new
                }
            )
            .to_string()
        );
    }

    #[test]
    fn mutable() {
        let mut setter = default_setter!();
        setter.pattern = BuilderPattern::Mutable;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                pub fn foo(&mut self, value: Foo) -> &mut Self {
                    let mut new = self;
                    new.foo = ::std::option::Option::Some(value);
                    new
                }
            )
            .to_string()
        );
    }

    #[test]
    fn owned() {
        let mut setter = default_setter!();
        setter.pattern = BuilderPattern::Owned;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                pub fn foo(self, value: Foo) -> Self {
                    let mut new = self;
                    new.foo = ::std::option::Option::Some(value);
                    new
                }
            )
            .to_string()
        );
    }

    #[test]
    fn private() {
        let vis = syn::Visibility::Inherited;

        let mut setter = default_setter!();
        setter.visibility = vis;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                fn foo(&mut self, value: Foo) -> &mut Self {
                    let mut new = self;
                    new.foo = ::std::option::Option::Some(value);
                    new
                }
            )
            .to_string()
        );
    }

    #[test]
    fn generic() {
        let mut setter = default_setter!();
        setter.generic_into = true;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
            #[allow(unused_mut)]
            pub fn foo <VALUE: ::std::convert::Into<Foo>>(&mut self, value: VALUE) -> &mut Self {
                let mut new = self;
                new.foo = ::std::option::Option::Some(value.into());
                new
            }
        ).to_string()
        );
    }

    #[test]
    fn strip_option() {
        let ty = syn::parse_str("Option<Foo>").unwrap();
        let mut setter = default_setter!();
        setter.strip_option = true;
        setter.field_type = &ty;
        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                pub fn foo(&mut self, value: Foo) -> &mut Self {
                    let mut new = self;
                    new.foo = ::std::option::Option::Some(::std::option::Option::Some(value));
                    new
                }
            )
            .to_string()
        );
    }

    #[test]
    fn strip_option_into() {
        let ty = syn::parse_str("Option<Foo>").unwrap();
        let mut setter = default_setter!();
        setter.strip_option = true;
        setter.generic_into = true;
        setter.field_type = &ty;
        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                pub fn foo<VALUE: ::std::convert::Into<Foo>>(&mut self, value: VALUE) -> &mut Self {
                    let mut new = self;
                    new.foo = ::std::option::Option::Some(::std::option::Option::Some(value.into()));
                    new
                }
            )
            .to_string()
        );
    }

    // including try_setter
    #[test]
    fn full() {
        //named!(outer_attrs -> Vec<syn::Attribute>, many0!(syn::Attribute::parse_outer));
        //let attrs = outer_attrs.parse_str("#[some_attr]").unwrap();
        let attrs: Vec<syn::Attribute> = vec![parse_quote!(#[some_attr])];

        let mut deprecated = DeprecationNotes::default();
        deprecated.push("Some example.".to_string());

        let mut setter = default_setter!();
        setter.attrs = attrs.as_slice();
        setter.generic_into = true;
        setter.deprecation_notes = &deprecated;
        setter.try_setter = true;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
            #[some_attr]
            #[allow(unused_mut)]
            pub fn foo <VALUE: ::std::convert::Into<Foo>>(&mut self, value: VALUE) -> &mut Self {
                #deprecated
                let mut new = self;
                new.foo = ::std::option::Option::Some(value.into());
                new
            }

            #[some_attr]
            pub fn try_foo<VALUE: ::std::convert::TryInto<Foo>>(&mut self, value: VALUE)
                -> ::std::result::Result<&mut Self, VALUE::Error> {
                let converted : Foo = value.try_into()?;
                let mut new = self;
                new.foo = ::std::option::Option::Some(converted);
                Ok(new)
            }
        ).to_string()
        );
    }

    #[test]
    fn no_std() {
        let mut setter = default_setter!();
        setter.bindings.no_std = true;
        setter.pattern = BuilderPattern::Immutable;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                pub fn foo(&self, value: Foo) -> Self {
                    let mut new = ::core::clone::Clone::clone(self);
                    new.foo = ::core::option::Option::Some(value);
                    new
                }
            )
            .to_string()
        );
    }

    #[test]
    fn no_std_generic() {
        let mut setter = default_setter!();
        setter.bindings.no_std = true;
        setter.generic_into = true;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
            #[allow(unused_mut)]
            pub fn foo <VALUE: ::core::convert::Into<Foo>>(&mut self, value: VALUE) -> &mut Self {
                let mut new = self;
                new.foo = ::core::option::Option::Some(value.into());
                new
            }
        ).to_string()
        );
    }

    #[test]
    fn setter_disabled() {
        let mut setter = default_setter!();
        setter.enabled = false;

        assert_eq!(quote!(#setter).to_string(), quote!().to_string());
    }

    #[test]
    fn try_setter() {
        let mut setter: Setter = default_setter!();
        setter.pattern = BuilderPattern::Mutable;
        setter.try_setter = true;

        assert_eq!(
            quote!(#setter).to_string(),
            quote!(
                #[allow(unused_mut)]
                pub fn foo(&mut self, value: Foo) -> &mut Self {
                    let mut new = self;
                    new.foo = ::std::option::Option::Some(value);
                    new
                }

                pub fn try_foo<VALUE: ::std::convert::TryInto<Foo>>(&mut self, value: VALUE)
                    -> ::std::result::Result<&mut Self, VALUE::Error> {
                    let converted : Foo = value.try_into()?;
                    let mut new = self;
                    new.foo = ::std::option::Option::Some(converted);
                    Ok(new)
                }
            )
            .to_string()
        );
    }

    #[test]
    fn extract_type_from_option_on_simple_type() {
        let ty_foo = syn::parse_str("Foo").unwrap();
        assert_eq!(extract_type_from_option(&ty_foo), None);

        for s in vec![
            "Option<Foo>",
            "std::option::Option<Foo>",
            "::std::option::Option<Foo>",
            "core::option::Option<Foo>",
            "::core::option::Option<Foo>",
        ] {
            let ty_foo_opt = syn::parse_str(s).unwrap();
            assert_eq!(extract_type_from_option(&ty_foo_opt), Some(&ty_foo));
        }
    }
}