Skip to content

Commit

Permalink
Allow unquoted expressions in default = ...
Browse files Browse the repository at this point in the history
For backwards compatibility, strings are still interpreted as code inside a string.

Fixes #330
  • Loading branch information
TedDriggs committed Oct 2, 2024
1 parent fdc50aa commit cdc59b8
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
12 changes: 6 additions & 6 deletions derive_builder/tests/custom_default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ mod field_level {
required: String,
#[builder(default)]
explicit_default: String,
#[builder(default = "\"foo\".to_string()")]
#[builder(default = "foo".to_string())]
escaped_default: String,
#[builder(default = r#"format!("Hello {}!", "World")"#)]
#[builder(default = format!("Hello {}!", "World"))]
raw_default: String,
#[builder(default = r#"format!("{}-{}-{}-{}",
#[builder(default = {format!("{}-{}-{}-{}",
Clone::clone(self.required
.as_ref()
.ok_or_else(|| UninitializedFieldError::new("required"))?),
match self.explicit_default { Some(ref x) => x, None => "EMPTY" },
self.escaped_default.as_ref().map(|x| x.as_ref()).unwrap_or("EMPTY"),
if let Some(ref x) = self.raw_default { x } else { "EMPTY" })"#)]
if let Some(ref x) = self.raw_default { x } else { "EMPTY" })})]
computed_default: String,
}

Expand Down Expand Up @@ -72,9 +72,9 @@ mod field_level {

mod struct_level {
#[derive(Debug, Clone, PartialEq, Eq, Builder)]
#[builder(default = "explicit_default()")]
#[builder(default = explicit_default())]
struct Lorem {
#[builder(default = "true")]
#[builder(default = true)]
overwritten: bool,
not_type_default: Option<&'static str>,
}
Expand Down
2 changes: 1 addition & 1 deletion derive_builder/tests/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct Lorem {
my_effort: u8,

/// A percentile. Must be less than or equal to `Lorem::my_effort`.
#[builder(default = "40")]
#[builder(default = 40)]
their_effort: u8,

/// A percentile. Must be between 0 and 100.
Expand Down
10 changes: 10 additions & 0 deletions derive_builder_core/src/default_expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ impl darling::FromMeta for DefaultExpression {
Ok(DefaultExpression::Trait)
}

fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
if let syn::Expr::Lit(el) = expr {
if let syn::Lit::Str(_) = el.lit {
return Self::from_value(&el.lit);
}
}

Ok(Self::Explicit(expr.clone().into()))
}

fn from_value(value: &syn::Lit) -> darling::Result<Self> {
Ok(Self::Explicit(BlockContents::from_value(value)?))
}
Expand Down

0 comments on commit cdc59b8

Please sign in to comment.