Skip to content

Commit

Permalink
Refactor: Shorten FieldLevelSetter parsing code
Browse files Browse the repository at this point in the history
  • Loading branch information
TedDriggs committed Mar 4, 2022
1 parent 7ba027d commit 8697e8f
Showing 1 changed file with 11 additions and 34 deletions.
45 changes: 11 additions & 34 deletions derive_builder_core/src/macro_options/darling_opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,39 +193,16 @@ impl FieldLevelSetter {

/// `derive_builder` allows the calling code to use `setter` as a word to enable
/// setters when they've been disabled at the struct level.
/// `darling` doesn't provide that out of the box, so we read the user input
/// into this enum then convert it into the `FieldLevelSetter`.
#[derive(Debug, Clone)]
enum FieldSetterMeta {
/// The keyword in isolation.
/// This is equivalent to `setter(skip = false)`.
Shorthand,
Longhand(FieldLevelSetter),
}

impl From<FieldSetterMeta> for FieldLevelSetter {
fn from(v: FieldSetterMeta) -> Self {
match v {
FieldSetterMeta::Shorthand => FieldLevelSetter {
skip: Some(false),
..Default::default()
},
FieldSetterMeta::Longhand(val) => val,
}
}
}

impl FromMeta for FieldSetterMeta {
fn from_word() -> darling::Result<Self> {
Ok(FieldSetterMeta::Shorthand)
}

fn from_meta(value: &syn::Meta) -> darling::Result<Self> {
if let syn::Meta::Path(_) = *value {
FieldSetterMeta::from_word()
} else {
FieldLevelSetter::from_meta(value).map(FieldSetterMeta::Longhand)
}
fn field_setter(meta: &Meta) -> darling::Result<FieldLevelSetter> {
// it doesn't matter what the path is; the fact that this function
// has been called means that a valueless path is the shorthand case.
if let Meta::Path(_) = meta {
Ok(FieldLevelSetter {
skip: Some(false),
..Default::default()
})
} else {
FieldLevelSetter::from_meta(meta)
}
}

Expand All @@ -246,7 +223,7 @@ pub struct Field {
private: Flag,
// See the documentation for `FieldSetterMeta` to understand how `darling`
// is interpreting this field.
#[darling(default, map = "FieldSetterMeta::into")]
#[darling(default, with = "field_setter")]
setter: FieldLevelSetter,
/// The value for this field if the setter is never invoked.
///
Expand Down

0 comments on commit 8697e8f

Please sign in to comment.