Skip to content

Commit

Permalink
Fix calling the specified default fn
Browse files Browse the repository at this point in the history
  • Loading branch information
XAMPPRocky committed Feb 18, 2024
1 parent 964d286 commit fb6e682
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
18 changes: 10 additions & 8 deletions macros/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -806,10 +806,7 @@ impl<'a> FieldConfig<'a> {
let mut ty = self.field.ty.clone();
let crate_root = &self.container_config.crate_root;
ty.strip_lifetimes();
let default_fn = self.default.as_ref().map(|default_fn| match default_fn {
Some(path) => quote!(#path),
None => quote!(<#ty>::default),
});
let default_fn = self.default_fn();

let encode = if self.tag.is_some() || self.container_config.automatic_tags {
if self.tag.as_ref().map_or(false, |tag| tag.is_explicit()) {
Expand Down Expand Up @@ -939,10 +936,7 @@ impl<'a> FieldConfig<'a> {
);

let or_else = quote!(.map_err(|error| #crate_root::de::Error::field_error(#ident, error.into(), decoder.codec()))?);
let default_fn = self.default.as_ref().map(|default_fn| match default_fn {
Some(path) => quote!(#path),
None => quote!(<#ty>::default),
});
let default_fn = self.default_fn();

let tag = self.tag(context);
let constraints = self.constraints.const_expr(crate_root);
Expand Down Expand Up @@ -1071,6 +1065,14 @@ impl<'a> FieldConfig<'a> {
}
}

pub fn default_fn(&self) -> Option<proc_macro2::TokenStream> {
let ty = &self.field.ty;
self.default.as_ref().map(|default_fn| match default_fn {
Some(path) => quote!(#path),
None => quote!(<#ty>::default),
})
}

pub fn tag_derive(&self, context: usize) -> proc_macro2::TokenStream {
if let Some(tag) = &self.tag {
if self.container_config.automatic_tags {
Expand Down
16 changes: 10 additions & 6 deletions macros/src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,15 +187,19 @@ pub fn derive_struct_impl(
let initializer_fn = if all_fields_optional_or_default {
let fields = match container.fields {
Fields::Named(_) => {
let init_fields = container
.fields
.iter()
.map(|field| field.ident.clone())
.map(|name| quote!(#name : <_>::default()));
let init_fields = container.fields.iter().map(|field| {
let default_fn = FieldConfig::new(field, config).default_fn().unwrap_or(quote!(<_>::default));
let name = &field.ident;
quote!(#name : #default_fn ())
});

quote!({ #(#init_fields),* })
}
Fields::Unnamed(_) => {
let init_fields = container.fields.iter().map(|_| quote!(<_>::default()));
let init_fields = container.fields.iter().map(|field| {
let default_fn = FieldConfig::new(field, config).default_fn().unwrap_or(quote!(<_>::default));
quote!(#default_fn ())
});
quote!(( #(#init_fields),* ))
}
Fields::Unit => quote!(),
Expand Down

0 comments on commit fb6e682

Please sign in to comment.