derive_setters 0.1.9

Rust macro to automatically generates setter methods for a struct's fields.
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
//! This crate provides a macro for automatically generating setter methods for a struct's fields.
//! This can be used to add setters to a plain data struct, or to help in implementing builders.
//!
//! For detailed usage, see [`#[derive(Setters)]`](macro@Setters)
//!
//! # Example
//!
//! ```rust
//! use derive_setters::*;
//!
//! #[derive(Default, Setters, Debug, PartialEq, Eq)]
//! struct BasicStruct {
//!     #[setters(rename = "test")]
//!     a: u32,
//!     b: u32,
//!     c: u32,
//! }
//!
//! assert_eq!(
//!     BasicStruct::default().test(30).b(10).c(20),
//!     BasicStruct { a: 30, b: 10, c: 20 },
//! );
//! ```

#![cfg_attr(feature = "nightly", feature(proc_macro_diagnostic))]

extern crate proc_macro;

use darling::util::Flag;
use darling::*;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as SynTokenStream};
use quote::*;
use std::result::Result;
use syn::spanned::Spanned;
use syn::*;

#[cfg(feature = "nightly")]
fn error(span: Span, data: &str) -> SynTokenStream {
    span.unstable().error(data).emit();
    SynTokenStream::new()
}

#[cfg(not(feature = "nightly"))]
fn error(_: Span, data: &str) -> SynTokenStream {
    quote! { compile_error!(#data); }
}

fn parse_generics(input: String) -> Result<Generics, darling::Error> {
    parse_str(&input).map_err(|parse_err| {
        darling::Error::custom(format!("Could not parse provided generics: {}", parse_err))
    })
}

#[derive(Debug, Clone, FromMeta)]
struct ExternalDelegate {
    /// The type to generate a delegate for.
    ty: Path,
    /// The generics for the type to generate a delegate for, if any.
    #[darling(and_then = parse_generics, default)]
    generics: Generics,
    /// The field to delegate the methods to.
    #[darling(default)]
    field: Option<Ident>,
    /// The method to delegate the methods to.
    #[darling(default)]
    method: Option<Ident>,
    /// A prefix for the delegated setter methods.
    #[darling(default)]
    prefix: Option<String>,
}

#[derive(Debug, Clone, FromDeriveInput)]
#[darling(attributes(setters), supports(struct_named))]
struct ContainerAttrs {
    ident: Ident,
    generics: Generics,

    /// Use the core library rather than the std library.
    #[darling(default)]
    no_std: Flag,

    /// Whether to accept any field that converts via `Into` by default.
    #[darling(default)]
    into: bool,

    /// Whether to strip `Option<T>` into `T` in the parameters for the setter method by default.
    #[darling(default)]
    strip_option: bool,

    /// Whether to borrow or take ownership of `self` in the setter method by default.
    #[darling(default)]
    borrow_self: bool,

    /// Whether to generate a method that sets a boolean by default.
    #[darling(default)]
    bool: bool,

    /// Whether to generate setters for this struct's fields by default. If set to false,
    /// `generate_public` and `generate_private` are ignored.
    #[darling(default)]
    generate: Option<bool>,

    /// Whether to generate setters for this struct's public fields by default.
    #[darling(default)]
    generate_public: Option<bool>,

    /// Whether to generate setters for this struct's private fields by default.
    #[darling(default)]
    generate_private: Option<bool>,

    /// A prefix for the generated setter methods.
    #[darling(default)]
    prefix: Option<String>,

    /// Other types to generate delegates to this type for.
    #[darling(multiple)]
    generate_delegates: Vec<ExternalDelegate>,
}

#[derive(Debug, Clone, FromField)]
#[darling(attributes(setters), forward_attrs(doc))]
struct FieldAttrs {
    attrs: Vec<Attribute>,

    /// The name of the generated setter method.
    #[darling(default)]
    rename: Option<Ident>,

    /// Whether to accept any field that converts via `Into` to this field's type.
    #[darling(default)]
    into: Option<bool>,

    /// Whether to strip `Option<T>` into `T` in the parameters for the setter method.
    #[darling(default)]
    strip_option: Option<bool>,

    /// Whether to borrow or take ownership of `self` for the setter method.
    #[darling(default)]
    borrow_self: Option<bool>,

    /// Whether to generate a method that sets a boolean.
    #[darling(default)]
    bool: Option<bool>,

    /// Whether to generate a setter for this field regardless of global settings.
    #[darling(default)]
    generate: bool,

    /// Whether to skip this field regardless of global settings. Overwrites `generate`.
    #[darling(default)]
    skip: bool,

    /// The documentation used for this field's setter.
    #[darling(default)]
    doc: Option<String>,
}

struct ContainerDef {
    ty: Type,
    std: Ident,
    generics: Generics,

    prefix: String,
    uses_into: bool,
    strip_option: bool,
    borrow_self: bool,
    bool: bool,
    generate_public: bool,
    generate_private: bool,

    generate_delegates: Vec<ExternalDelegate>,
}

struct FieldDef {
    field_name: Ident,
    field_ty: Type,
    field_doc: SynTokenStream,
    setter_name: Ident,
    uses_into: bool,
    strip_option: bool,
    borrow_self: bool,
    must_use: bool,
    bool: bool,
}

fn init_container_def(input: &DeriveInput) -> Result<ContainerDef, SynTokenStream> {
    let darling_attrs: ContainerAttrs = match FromDeriveInput::from_derive_input(input) {
        Ok(v) => v,
        Err(e) => return Err(e.write_errors()),
    };

    let ident = &darling_attrs.ident;
    let (_, generics_ty, _) = darling_attrs.generics.split_for_impl();
    let ty = quote! { #ident #generics_ty };

    let generate = darling_attrs.generate.unwrap_or(true);
    Ok(ContainerDef {
        ty: parse2(ty).expect("Internal error: failed to parse internally generated type."),
        std: if darling_attrs.no_std.is_present() {
            Ident::new("core", Span::call_site())
        } else {
            Ident::new("std", Span::call_site())
        },
        borrow_self: darling_attrs.borrow_self,
        generics: darling_attrs.generics,
        prefix: darling_attrs.prefix.unwrap_or(String::new()),
        uses_into: darling_attrs.into,
        strip_option: darling_attrs.strip_option,
        bool: darling_attrs.bool,
        generate_public: generate && darling_attrs.generate_public.unwrap_or(true),
        generate_private: generate && darling_attrs.generate_private.unwrap_or(true),
        generate_delegates: darling_attrs.generate_delegates,
    })
}

fn init_field_def(
    container: &ContainerDef,
    field: &Field,
) -> Result<Option<FieldDef>, SynTokenStream> {
    // Decode the various attribute options.
    let darling_attrs: FieldAttrs = match FromField::from_field(field) {
        Ok(v) => v,
        Err(e) => return Err(e.write_errors()),
    };

    // Check whether this field should generate a setter.
    if darling_attrs.skip {
        return Ok(None);
    }
    let generates = match field.vis {
        Visibility::Public(_) => container.generate_public,
        _ => container.generate_private,
    };
    if !(darling_attrs.generate || generates) {
        return Ok(None);
    }

    // Returns a definition for this field.
    let ident = match &field.ident {
        Some(i) => i.clone(),
        None => panic!("Internal error: init_field_def on wrong item."),
    };
    Ok(Some(FieldDef {
        field_name: ident.clone(),
        field_ty: field.ty.clone(),
        field_doc: if let Visibility::Public(_) = field.vis {
            let doc_str =
                format!("Sets the [`{}`](#structfield.{}) field of this struct.", ident, ident);
            quote! { #[doc = #doc_str] }
        } else if let Some(x) = darling_attrs.doc {
            quote! { #[doc = #x] }
        } else {
            let attrs = darling_attrs.attrs;
            quote! { #( #attrs )* }
        },
        setter_name: darling_attrs
            .rename
            .unwrap_or_else(|| Ident::new(&format!("{}{}", container.prefix, ident), ident.span())),
        uses_into: darling_attrs.into.unwrap_or(container.uses_into),
        strip_option: darling_attrs.strip_option.unwrap_or(container.strip_option),
        borrow_self: darling_attrs.borrow_self.unwrap_or(container.borrow_self),
        must_use: false == darling_attrs.borrow_self.unwrap_or(container.borrow_self),
        bool: darling_attrs.bool.unwrap_or(container.bool),
    }))
}

fn generate_setter_method(
    container: &ContainerDef,
    def: FieldDef,
    additional_prefix: &Option<String>,
    delegate_toks: &Option<SynTokenStream>,
) -> Result<SynTokenStream, SynTokenStream> {
    let FieldDef { field_name, mut field_ty, field_doc, setter_name, .. } = def;
    let std = &container.std;
    let setter_name = if let Some(additional_prefix) = additional_prefix {
        Ident::new(&format!("{additional_prefix}{}", setter_name), setter_name.span())
    } else {
        setter_name
    };

    // Strips `Option<T>` into `T` if the `strip_option` property is set.
    let mut stripped_option = false;
    if def.strip_option {
        if let Type::Path(path) = &field_ty {
            let segment = path.path.segments.last().unwrap();
            if segment.ident.to_string() == "Option" {
                if let PathArguments::AngleBracketed(path) = &segment.arguments {
                    if let GenericArgument::Type(tp) = path.args.first().unwrap() {
                        field_ty = tp.clone();
                        stripped_option = true;
                    }
                }
            }
        }
    }

    // The type the setter accepts.
    let value_ty = if def.uses_into {
        quote! { impl ::#std::convert::Into<#field_ty> }
    } else {
        quote! { #field_ty }
    };

    // The expression actually stored into the field.
    let mut expr = quote! { value };
    if def.uses_into {
        expr = quote! { #expr.into() };
    }
    if def.bool {
        expr = quote! { true };
    }
    if stripped_option {
        expr = quote! { Some(#expr) };
    }

    // Handle the parameters when bool is enabled.
    let params = if def.bool {
        SynTokenStream::new()
    } else {
        quote! { value: #value_ty }
    };

    // Add extra attributes
    let field_attrs = if def.must_use {
        quote! { #[must_use] }
    } else {
        SynTokenStream::new()
    };

    // Generates the setter method itself.
    if let Some(delegate) = delegate_toks {
        let _self = if def.borrow_self {
            quote! { &mut self }
        } else {
            quote! { mut self }
        };

        let return_self = if def.borrow_self {
            quote! { &mut Self }
        } else {
            quote! { Self }
        };

        Ok(quote! {
            #field_doc
            #field_attrs
            pub fn #setter_name (#_self, #params) -> #return_self {
                self.#delegate.#field_name = #expr;
                self
            }
        })
    } else {
        if def.borrow_self {
            Ok(quote! {
                #field_doc
                #field_attrs
                pub fn #setter_name (&mut self, #params) -> &mut Self {
                    self.#field_name = #expr;
                    self
                }
            })
        } else {
            Ok(quote! {
                #field_doc
                #field_attrs
                pub fn #setter_name (mut self, #params) -> Self {
                    self.#field_name = #expr;
                    self
                }
            })
        }
    }
}

fn generate_setters_for(
    input: &DeriveInput,
    data: &DataStruct,
    generics: &Generics,
    ty: SynTokenStream,
    additional_prefix: Option<String>,
    delegate_toks: Option<SynTokenStream>,
) -> Result<SynTokenStream, SynTokenStream> {
    let container_def = init_container_def(&input)?;
    let mut toks = SynTokenStream::new();
    for field in &data.fields {
        if let Some(field_def) = init_field_def(&container_def, field)? {
            let method = generate_setter_method(
                &container_def,
                field_def,
                &additional_prefix,
                &delegate_toks,
            )?;
            toks.extend(method);
        }
    }

    let (generics_bound, _, generics_where) = generics.split_for_impl();
    Ok(quote! {
        impl #generics_bound #ty #generics_where {
            #toks
        }
    })
}

fn generate_setters(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream, TokenStream> {
    let container_def = init_container_def(&input)?;
    let mut toks = SynTokenStream::new();
    let container_ty = &container_def.ty;
    toks.extend(generate_setters_for(
        input,
        data,
        &container_def.generics,
        quote! { #container_ty },
        None,
        None,
    ));
    for delegate in container_def.generate_delegates {
        let delegate_ty = delegate.ty;
        toks.extend(generate_setters_for(
            input,
            data,
            &delegate.generics,
            quote! { #delegate_ty },
            delegate.prefix,
            if delegate.field.is_some() && delegate.method.is_some() {
                return Err(error(
                    input.span(),
                    "Cannot set both `method` and `field` on a delegate.",
                )
                .into());
            } else if let Some(field) = &delegate.field {
                Some(quote! { #field })
            } else if let Some(method) = &delegate.method {
                Some(quote! { #method() })
            } else {
                return Err(error(
                    input.span(),
                    "Must set either `method` or `field` on a delegate.",
                )
                .into());
            },
        ));
    }
    Ok(toks.into())
}

/// This macro can be used on a struct to generate setter methods for its fields.
///
/// By default, it generates a single method with the same name as each field, that takes self by
/// value and returns a new struct with the field modified.
///
/// The way these methods are generated can be additionally customized with the `#[setters(…)]`
/// attribute.
///
/// # Example
///
/// A basic usage example:
///
/// ```rust
/// # use derive_setters::*;
/// #[derive(Default, Setters, Debug, PartialEq, Eq)]
/// struct BasicStruct {
///     a: u32,
///     b: u32,
///     c: u32,
/// }
/// ```
///
/// This would generate the following implementations:
///
/// ```rust
/// # struct BasicStruct { a: u32, b: u32, c: u32 }
/// impl BasicStruct {
///     #[must_use]
///     pub fn a(mut self, value: u32) -> Self {
///         self.a = value;
///         self
///     }
///
///     #[must_use]
///     pub fn b(mut self, value: u32) -> Self {
///         self.b = value;
///         self
///     }
///
///     #[must_use]
///     pub fn c(mut self, value: u32) -> Self {
///         self.c = value;
///         self
///     }
/// }
/// ```
///
/// # Struct-level options
///
/// * The following options control which fields are actually generated:
///     * `#[setters(generate = false)]` causes setter methods to not be generated by default. This
///       can be overwritten with `#[setters(generate)]` on the fields you want setters for.
///     * `#[setters(generate_private = false)]` causes setter methods to not be generated by
///       default for private fields.
///     * `#[setters(generate_public = false)]` causes setter methods to not be generated by
///       default for public fields.
/// * `#[setters(no_std)]` causes the generated code to use `core` instead of `std`.
/// * `#[setters(prefix = "…")]` causes the setter method on all fields to be prefixed with the
///   given string.
///
/// # Field-level options
///
/// The following options can be set on a field.
///
/// * `#[setters(generate)]` causes a setter method to be generated, overriding struct-level
///   settings.
/// * `#[setters(skip)]` causes no setter method to be generated.
/// * `#[setters(rename = "…")]` causes the setter method to have a different name from the field.
///   When used, the `prefix` option is ignored.
///
/// # Common options
///
/// The following options can be set on either the entire struct, or on an individual field. You
/// can disable the features for a particular field with `#[setters(option = false)]`
///
/// * `#[setters(into)]` causes the setter method to accept any type that can be converted into the
///   field's type via the [`Into`] trait.
/// * `#[setters(strip_option)]` causes the setter method to accept `T` instead of `Option<T>`. If
///   applied to a field  that isn't wrapped in an `Option`, it does nothing.
/// * `#[setters(bool)]` causes the setter method to take no arguments, and to always set the value
///   of the field to `true`.
/// * `#[setters(borrow_self)]` causes the generated setter method to borrow `&mut self` instead of
///   taking `self`, and return `&mut Self` rather than `Self`.
///
/// # Delegation options
///
/// The following options allow additional setters to be generated for wrappers around the type
/// this macro is used on.
///
/// * `#[setters(generate_delegates(ty = "OtherTy", field = "some_field"))]` causes all setter
///   methods on this struct to be duplicated on the target struct, instead modifying
///   `self.some_field` instead of `self`.
/// * `#[setters(generate_delegates(ty = "OtherTy", method = "get_field"))]` does the same thing as
///   above, except calling `get_field` with no arguments instead of directly accessing a field.
/// * `#[setters(generate_delegates(ty = "OtherTy", field = "some_field", prefix = "set_"))]` adds
///   the prefix `set_` to all delegated fields.
/// * `#[setters(generate_delegates(ty = "OtherTy<T>", generics = "<T>", method = "get_field"))]`
///   does the same thing as above, but it supports generic types.

#[proc_macro_derive(Setters, attributes(setters))]
pub fn derive_setters(input: TokenStream) -> TokenStream {
    let input: DeriveInput = parse_macro_input!(input);
    if let Data::Struct(data) = &input.data {
        generate_setters(&input, data).unwrap_or_else(|toks| toks)
    } else {
        error(input.span(), "`#[derive(Setters)] may only be used on structs.").into()
    }
}