let ctxt = Ctxt::new(); let cont = match Container::from_ast(&ctxt, input, Derive::Deserialize) {
Some(cont) => cont,
None => return Err(ctxt.check().unwrap_err()),
};
precondition(&ctxt, &cont);
ctxt.check()?;
let ident = &cont.ident; let params = Parameters::new(&cont); let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms); let body = Stmts(deserialize_body(&cont, ¶ms)); let delife = params.borrowed.de_lifetime(); let serde = cont.attrs.serde_path();
let impl_block = iflet Some(remote) = cont.attrs.remote() { let vis = &input.vis; let used = pretend::pretend_used(&cont, params.is_packed);
quote! { #[automatically_derived] impl#de_impl_generics#ident#ty_generics#where_clause { #visfn deserialize<__D>(__deserializer: __D) -> #serde::__private::Result<#remote#ty_generics, __D::Error> where
__D: #serde::Deserializer<#delife>,
{ #used #body
}
}
}
} else { let fn_deserialize_in_place = deserialize_in_place_body(&cont, ¶ms);
fn precondition_no_de_lifetime(cx: &Ctxt, cont: &Container) { iflet BorrowedLifetimes::Borrowed(_) = borrowed_lifetimes(cont) { for param in cont.generics.lifetimes() { if param.lifetime.to_string() == "'de" {
cx.error_spanned_by(
¶m.lifetime, "cannot deserialize when there is a lifetime parameter called 'de",
); return;
}
}
}
}
struct Parameters { /// Name of the type the `derive` is on.
local: syn::Ident,
/// Path to the type the impl is for. Either a single `Ident` for local /// types (does not include generic parameters) or `some::remote::Path` for /// remote types.
this_type: syn::Path,
/// Same as `this_type` but using `::<T>` for generic parameters for use in /// expression position.
this_value: syn::Path,
/// Generics including any explicit and inferred bounds for the impl.
generics: syn::Generics,
/// Lifetimes borrowed from the deserializer. These will become bounds on /// the `'de` lifetime of the deserializer.
borrowed: BorrowedLifetimes,
/// At least one field has a serde(getter) attribute, implying that the /// remote type has a private field.
has_getter: bool,
/// Type has a repr(packed) attribute.
is_packed: bool,
}
impl Parameters { fn new(cont: &Container) -> Self { let local = cont.ident.clone(); let this_type = this::this_type(cont); let this_value = this::this_value(cont); let borrowed = borrowed_lifetimes(cont); let generics = build_generics(cont, &borrowed); let has_getter = cont.data.has_getter(); let is_packed = cont.attrs.is_packed();
/// Type name to use in error messages and `&'static str` arguments to /// various Deserializer methods. fn type_name(&self) -> String { self.this_type.segments.last().unwrap().ident.to_string()
}
}
// All the generics in the input, plus a bound `T: Deserialize` for each generic // field type that will be deserialized by us, plus a bound `T: Default` for // each generic field type that will be set to a default value. fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics { let generics = bound::without_defaults(cont.generics);
let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound);
let generics =
bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::de_bound);
match cont.attrs.de_bound() {
Some(predicates) => bound::with_where_predicates(&generics, predicates),
None => { let generics = match *cont.attrs.default() {
attr::Default::Default => bound::with_self_bound(
cont,
&generics,
&parse_quote!(_serde::__private::Default),
),
attr::Default::None | attr::Default::Path(_) => generics,
};
let delife = borrowed.de_lifetime(); let generics = bound::with_bound(
cont,
&generics,
needs_deserialize_bound,
&parse_quote!(_serde::Deserialize<#delife>),
);
// Fields with a `skip_deserializing` or `deserialize_with` attribute, or which // belong to a variant with a `skip_deserializing` or `deserialize_with` // attribute, are not deserialized by us so we do not generate a bound. Fields // with a `bound` attribute specify their own bound so we do not generate one. // All other fields may need a `T: Deserialize` bound where T is the type of the // field. fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool {
!field.skip_deserializing()
&& field.deserialize_with().is_none()
&& field.de_bound().is_none()
&& variant.map_or(true, |variant| {
!variant.skip_deserializing()
&& variant.deserialize_with().is_none()
&& variant.de_bound().is_none()
})
}
// Fields with a `default` attribute (not `default=...`), and fields with a // `skip_deserializing` attribute that do not also have `default=...`. fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool { iflet attr::Default::Default = *field.default() { true
} else { false
}
}
// The union of lifetimes borrowed by each field of the container. // // These turn into bounds on the `'de` lifetime of the Deserialize impl. If // lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is: // // impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c> // // If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant // and we use plain `'static` instead of `'de`. fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes { letmut lifetimes = BTreeSet::new(); for field in cont.data.all_fields() { if !field.attrs.skip_deserializing() {
lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());
}
} if lifetimes.iter().any(|b| b.to_string() == "'static") {
BorrowedLifetimes::Static
} else {
BorrowedLifetimes::Borrowed(lifetimes)
}
}
#[cfg(feature = "deserialize_in_place")] fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<Stmts> { // Only remote derives have getters, and we do not generate // deserialize_in_place for remote derives.
assert!(!params.has_getter);
fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment { let fields = match &cont.data {
Data::Struct(_, fields) => fields,
Data::Enum(_) => unreachable!(),
};
let this_value = ¶ms.this_value; let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap();
let path = match transparent_field.attrs.deserialize_with() {
Some(path) => quote!(#path),
None => { let span = transparent_field.original.span();
quote_spanned!(span=> _serde::Deserialize::deserialize)
}
};
let assign = fields.iter().map(|field| { let member = &field.member; if ptr::eq(field, transparent_field) {
quote!(#member: __transparent)
} else { let value = match field.attrs.default() {
attr::Default::Default => quote!(_serde::__private::Default::default()), // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(default = "...")] // ^^^^^
attr::Default::Path(path) => quote_spanned!(path.span()=> #path()),
attr::Default::None => quote!(_serde::__private::PhantomData),
};
quote!(#member: #value)
}
});
#[automatically_derived] impl#de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
enum TupleForm<'a> {
Tuple, /// Contains a variant name
ExternallyTagged(&'a syn::Ident), /// Contains a variant name and an intermediate deserializer from which actual /// deserialization will be performed
Untagged(&'a syn::Ident, TokenStream),
}
fn deserialize_tuple(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
form: TupleForm,
) -> Fragment {
assert!(
!has_flatten(fields), "tuples and tuple variants cannot have flatten fields"
);
let field_count = fields
.iter()
.filter(|field| !field.attrs.skip_deserializing())
.count();
let this_type = ¶ms.this_type; let this_value = ¶ms.this_value; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params); let delife = params.borrowed.de_lifetime();
// If there are getters (implying private fields), construct the local type // and use an `Into` conversion to get the remote type. If there are no // getters then construct the target type directly. let construct = if params.has_getter { let local = ¶ms.local;
quote!(#local)
} else {
quote!(#this_value)
};
let type_path = match form {
TupleForm::Tuple => construct,
TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => {
quote!(#construct::#variant_ident)
}
}; let expecting = match form {
TupleForm::Tuple => format!("tuple struct {}", params.type_name()),
TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => {
format!("tuple variant {}::{}", params.type_name(), variant_ident)
}
}; let expecting = cattrs.expecting().unwrap_or(&expecting);
let nfields = fields.len();
let visit_newtype_struct = match form {
TupleForm::Tuple if nfields == 1 => {
Some(deserialize_newtype_struct(&type_path, params, &fields[0]))
}
_ => None,
};
#[automatically_derived] impl#de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
#[cfg(feature = "deserialize_in_place")] fn deserialize_tuple_in_place(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
) -> Fragment {
assert!(
!has_flatten(fields), "tuples and tuple variants cannot have flatten fields"
);
let field_count = fields
.iter()
.filter(|field| !field.attrs.skip_deserializing())
.count();
let this_type = ¶ms.this_type; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params); let delife = params.borrowed.de_lifetime();
let expecting = format!("tuple struct {}", params.type_name()); let expecting = cattrs.expecting().unwrap_or(&expecting);
let nfields = fields.len();
let visit_newtype_struct = if nfields == 1 { // We do not generate deserialize_in_place if every field has a // deserialize_with.
assert!(fields[0].attrs.deserialize_with().is_none());
if params.has_getter { let this_type = ¶ms.this_type; let (_, ty_generics, _) = params.generics.split_for_impl();
result = quote! {
_serde::__private::Into::<#this_type#ty_generics>::into(#result)
};
}
let let_default = match cattrs.default() {
attr::Default::Default => Some(quote!( let __default: Self::Value = _serde::__private::Default::default();
)), // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(default = "...")] // ^^^^^
attr::Default::Path(path) => Some(quote_spanned!(path.span()=> let __default: Self::Value = #path();
)),
attr::Default::None => { // We don't need the default value, to prevent an unused variable warning // we'll leave the line empty.
None
}
};
let this_type = ¶ms.this_type; let (_, ty_generics, _) = params.generics.split_for_impl(); let let_default = match cattrs.default() {
attr::Default::Default => Some(quote!( let __default: #this_type#ty_generics = _serde::__private::Default::default();
)), // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(default = "...")] // ^^^^^
attr::Default::Path(path) => Some(quote_spanned!(path.span()=> let __default: #this_type#ty_generics = #path();
)),
attr::Default::None => { // We don't need the default value, to prevent an unused variable warning // we'll leave the line empty.
None
}
};
fn deserialize_newtype_struct(
type_path: &TokenStream,
params: &Parameters,
field: &Field,
) -> TokenStream { let delife = params.borrowed.de_lifetime(); let field_ty = field.ty; let deserializer_var = quote!(__e);
let value = match field.attrs.deserialize_with() {
None => { let span = field.original.span(); let func = quote_spanned!(span=> <#field_tyas _serde::Deserialize>::deserialize);
quote! { #func(#deserializer_var)?
}
}
Some(path) => { // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(with = "...")] // ^^^^^
quote_spanned! {path.span()=> #path(#deserializer_var)?
}
}
};
letmut result = quote!(#type_path(__field0)); if params.has_getter { let this_type = ¶ms.this_type; let (_, ty_generics, _) = params.generics.split_for_impl();
result = quote! {
_serde::__private::Into::<#this_type#ty_generics>::into(#result)
};
}
enum StructForm<'a> { Struct, /// Contains a variant name
ExternallyTagged(&'a syn::Ident), /// Contains a variant name and an intermediate deserializer from which actual /// deserialization will be performed
InternallyTagged(&'a syn::Ident, TokenStream), /// Contains a variant name and an intermediate deserializer from which actual /// deserialization will be performed
Untagged(&'a syn::Ident, TokenStream),
}
fn deserialize_struct(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
form: StructForm,
) -> Fragment { let this_type = ¶ms.this_type; let this_value = ¶ms.this_value; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params); let delife = params.borrowed.de_lifetime();
// If there are getters (implying private fields), construct the local type // and use an `Into` conversion to get the remote type. If there are no // getters then construct the target type directly. let construct = if params.has_getter { let local = ¶ms.local;
quote!(#local)
} else {
quote!(#this_value)
};
let type_path = match form {
StructForm::Struct => construct,
StructForm::ExternallyTagged(variant_ident)
| StructForm::InternallyTagged(variant_ident, _)
| StructForm::Untagged(variant_ident, _) => quote!(#construct::#variant_ident),
}; let expecting = match form {
StructForm::Struct => format!("struct {}", params.type_name()),
StructForm::ExternallyTagged(variant_ident)
| StructForm::InternallyTagged(variant_ident, _)
| StructForm::Untagged(variant_ident, _) => {
format!("struct variant {}::{}", params.type_name(), variant_ident)
}
}; let expecting = cattrs.expecting().unwrap_or(&expecting);
let deserialized_fields: Vec<_> = fields
.iter()
.enumerate() // Skip fields that shouldn't be deserialized or that were flattened, // so they don't appear in the storage in their literal form
.filter(|&(_, field)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
.map(|(i, field)| FieldWithAliases {
ident: field_i(i),
aliases: field.attrs.aliases(),
})
.collect();
let has_flatten = has_flatten(fields); let field_visitor = deserialize_field_identifier(&deserialized_fields, cattrs, has_flatten);
// untagged struct variants do not get a visit_seq method. The same applies to // structs that only have a map representation. let visit_seq = match form {
StructForm::Untagged(..) => None,
_ if has_flatten => None,
_ => { let mut_seq = if deserialized_fields.is_empty() {
quote!(_)
} else {
quote!(mut __seq)
};
let visitor_seed = match form {
StructForm::ExternallyTagged(..) if has_flatten => Some(quote! { #[automatically_derived] impl#de_impl_generics _serde::de::DeserializeSeed<#delife> for __Visitor #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
#[automatically_derived] impl#de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
#[cfg(feature = "deserialize_in_place")] fn deserialize_struct_in_place(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
) -> Option<Fragment> { // for now we do not support in_place deserialization for structs that // are represented as map. if has_flatten(fields) { return None;
}
let this_type = ¶ms.this_type; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params); let delife = params.borrowed.de_lifetime();
let expecting = format!("struct {}", params.type_name()); let expecting = cattrs.expecting().unwrap_or(&expecting);
fn deserialize_enum(
params: &Parameters,
variants: &[Variant],
cattrs: &attr::Container,
) -> Fragment { // The variants have already been checked (in ast.rs) that all untagged variants appear at the end match variants.iter().position(|var| var.attrs.untagged()) {
Some(variant_idx) => { let (tagged, untagged) = variants.split_at(variant_idx); let tagged_frag = Expr(deserialize_homogeneous_enum(params, tagged, cattrs));
deserialize_untagged_enum_after(params, untagged, cattrs, Some(tagged_frag))
}
None => deserialize_homogeneous_enum(params, variants, cattrs),
}
}
let variant_visitor = Stmts(deserialize_generated_identifier(
&deserialized_variants, false, // variant identifiers do not depend on the presence of flatten fields true,
None,
fallthrough,
));
(variants_stmt, variant_visitor)
}
fn deserialize_externally_tagged_enum(
params: &Parameters,
variants: &[Variant],
cattrs: &attr::Container,
) -> Fragment { let this_type = ¶ms.this_type; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params); let delife = params.borrowed.de_lifetime();
let type_name = cattrs.name().deserialize_name(); let expecting = format!("enum {}", params.type_name()); let expecting = cattrs.expecting().unwrap_or(&expecting);
let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants);
// Match arms to extract a variant from a string let variant_arms = variants
.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
.map(|(i, variant)| { let variant_name = field_i(i);
let block = Match(deserialize_externally_tagged_variant(
params, variant, cattrs,
));
let all_skipped = variants
.iter()
.all(|variant| variant.attrs.skip_deserializing()); let match_variant = if all_skipped { // This is an empty enum like `enum Impossible {}` or an enum in which // all variants have `#[serde(skip_deserializing)]`.
quote! { // FIXME: Once feature(exhaustive_patterns) is stable: // let _serde::__private::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data); // _serde::__private::Err(__err)
_serde::__private::Result::map(
_serde::de::EnumAccess::variant::<__Field>(__data),
|(__impossible, _)| match __impossible {})
}
} else {
quote! { match _serde::de::EnumAccess::variant(__data)? { #(#variant_arms)*
}
}
};
#[automatically_derived] impl#de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
fn deserialize_internally_tagged_enum(
params: &Parameters,
variants: &[Variant],
cattrs: &attr::Container,
tag: &str,
) -> Fragment { let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants);
// Match arms to extract a variant from a string let variant_arms = variants
.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
.map(|(i, variant)| { let variant_name = field_i(i);
let block = Match(deserialize_internally_tagged_variant(
params,
variant,
cattrs,
quote!(__deserializer),
));
quote! {
__Field::#variant_name => #block
}
});
let expecting = format!("internally tagged enum {}", params.type_name()); let expecting = cattrs.expecting().unwrap_or(&expecting);
quote_block! { #variant_visitor
#variants_stmt
let (__tag, __content) = _serde::Deserializer::deserialize_any(
__deserializer,
_serde::__private::de::TaggedContentVisitor::<__Field>::new(#tag, #expecting))?; let __deserializer = _serde::__private::de::ContentDeserializer::<__D::Error>::new(__content);
match __tag { #(#variant_arms)*
}
}
}
fn deserialize_adjacently_tagged_enum(
params: &Parameters,
variants: &[Variant],
cattrs: &attr::Container,
tag: &str,
content: &str,
) -> Fragment { let this_type = ¶ms.this_type; let this_value = ¶ms.this_value; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params); let delife = params.borrowed.de_lifetime();
let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants);
let variant_arms: &Vec<_> = &variants
.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
.map(|(i, variant)| { let variant_index = field_i(i);
let block = Match(deserialize_untagged_variant(
params,
variant,
cattrs,
quote!(__deserializer),
));
let rust_name = params.type_name(); let expecting = format!("adjacently tagged enum {}", rust_name); let expecting = cattrs.expecting().unwrap_or(&expecting); let type_name = cattrs.name().deserialize_name(); let deny_unknown_fields = cattrs.deny_unknown_fields();
// If unknown fields are allowed, we pick the visitor that can step over // those. Otherwise we pick the visitor that fails on unknown keys. let field_visitor_ty = if deny_unknown_fields {
quote! { _serde::__private::de::TagOrContentFieldVisitor }
} else {
quote! { _serde::__private::de::TagContentOtherFieldVisitor }
};
letmut missing_content = quote! {
_serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#content))
}; letmut missing_content_fallthrough = quote!(); let missing_content_arms = variants
.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
.filter_map(|(i, variant)| { let variant_index = field_i(i); let variant_ident = &variant.ident;
let arm = match variant.style {
Style::Unit => quote! {
_serde::__private::Ok(#this_value::#variant_ident)
},
Style::Newtype if variant.attrs.deserialize_with().is_none() => { let span = variant.original.span(); let func = quote_spanned!(span=> _serde::__private::de::missing_field);
quote! { #func(#content).map(#this_value::#variant_ident)
}
}
_ => {
missing_content_fallthrough = quote!(_ => #missing_content); return None;
}
};
Some(quote! {
__Field::#variant_index => #arm,
})
})
.collect::<Vec<_>>(); if !missing_content_arms.is_empty() {
missing_content = quote! { match __field { #(#missing_content_arms)* #missing_content_fallthrough
}
};
}
// Advance the map by one key, returning early in case of error. let next_key = quote! {
_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)?
};
let variant_from_map = quote! {
_serde::de::MapAccess::next_value_seed(&mut __map, #variant_seed)?
};
// When allowing unknown fields, we want to transparently step through keys // we don't care about until we find `tag`, `content`, or run out of keys. let next_relevant_key = if deny_unknown_fields {
next_key
} else {
quote!({ letmut __rk : _serde::__private::Option<_serde::__private::de::TagOrContentField> = _serde::__private::None; whilelet _serde::__private::Some(__k) = #next_key { match __k {
_serde::__private::de::TagContentOtherField::Other => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; continue;
},
_serde::__private::de::TagContentOtherField::Tag => {
__rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag); break;
}
_serde::__private::de::TagContentOtherField::Content => {
__rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Content); break;
}
}
}
__rk
})
};
// Step through remaining keys, looking for duplicates of previously-seen // keys. When unknown fields are denied, any key that isn't a duplicate will // at this point immediately produce an error. let visit_remaining_keys = quote! { match#next_relevant_key {
_serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => {
_serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag))
}
_serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => {
_serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content))
}
_serde::__private::None => _serde::__private::Ok(__ret),
}
};
let finish_content_then_tag = if variant_arms.is_empty() {
quote! { match#variant_from_map {}
}
} else {
quote! { let __ret = match#variant_from_map { // Deserialize the buffered content now that we know the variant. #(#variant_arms)*
}?; // Visit remaining keys, looking for duplicates. #visit_remaining_keys
}
};
#[automatically_derived] impl#de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
#[automatically_derived] impl#de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result<Self::Value, __A::Error> where
__A: _serde::de::MapAccess<#delife>,
{ // Visit the first relevant key. match#next_relevant_key { // First key is the tag.
_serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { // Parse the tag. let __field = #variant_from_map; // Visit the second key. match#next_relevant_key { // Second key is a duplicate of the tag.
_serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => {
_serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag))
} // Second key is the content.
_serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { let __ret = _serde::de::MapAccess::next_value_seed(&mut __map,
__Seed {
field: __field,
marker: _serde::__private::PhantomData,
lifetime: _serde::__private::PhantomData,
})?; // Visit remaining keys, looking for duplicates. #visit_remaining_keys
} // There is no second key; might be okay if the we have a unit variant.
_serde::__private::None => #missing_content
}
} // First key is the content.
_serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { // Buffer up the content. let __content = _serde::de::MapAccess::next_value::<_serde::__private::de::Content>(&pan style='color:red'>mut __map)?; // Visit the second key. match#next_relevant_key { // Second key is the tag.
_serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { let __deserializer = _serde::__private::de::ContentDeserializer::<__A::Error>::new(__content); #finish_content_then_tag
} // Second key is a duplicate of the content.
_serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => {
_serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content))
} // There is no second key.
_serde::__private::None => {
_serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag))
}
}
} // There is no first key.
_serde::__private::None => {
_serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag))
}
}
}
fn visit_seq<__A>(self, mut __seq: __A) -> _serde::__private::Result<Self::Value, __A::Error> where
__A: _serde::de::SeqAccess<#delife>,
{ // Visit the first element - the tag. match _serde::de::SeqAccess::next_element(&mut __seq)? {
_serde::__private::Some(__field) => { // Visit the second element - the content. match _serde::de::SeqAccess::next_element_seed(
&mut __seq,
__Seed {
field: __field,
marker: _serde::__private::PhantomData,
lifetime: _serde::__private::PhantomData,
},
)? {
_serde::__private::Some(__ret) => _serde::__private::Ok(__ret), // There is no second element.
_serde::__private::None => {
_serde::__private::Err(_serde::de::Error::invalid_length(1, &self))
}
}
} // There is no first element.
_serde::__private::None => {
_serde::__private::Err(_serde::de::Error::invalid_length(0, &self))
}
}
}
}
fn deserialize_untagged_enum_after(
params: &Parameters,
variants: &[Variant],
cattrs: &attr::Container,
first_attempt: Option<Expr>,
) -> Fragment { let attempts = variants
.iter()
.filter(|variant| !variant.attrs.skip_deserializing())
.map(|variant| {
Expr(deserialize_untagged_variant(
params,
variant,
cattrs,
quote!(__deserializer),
))
}); // TODO this message could be better by saving the errors from the failed // attempts. The heuristic used by TOML was to count the number of fields // processed before an error, and use the error that happened after the // largest number of fields. I'm not sure I like that. Maybe it would be // better to save all the errors and combine them into one message that // explains why none of the variants matched. let fallthrough_msg = format!( "data did not match any variant of untagged enum {}",
params.type_name()
); let fallthrough_msg = cattrs.expecting().unwrap_or(&fallthrough_msg);
// Ignore any error associated with non-untagged deserialization so that we // can fall through to the untagged variants. This may be infallible so we // need to provide the error type. let first_attempt = first_attempt.map(|expr| {
quote! { iflet _serde::__private::Result::<_, __D::Error>::Ok(__ok) = (|| #expr)() { return _serde::__private::Ok(__ok);
}
}
});
quote_block! { let __content = <_serde::__private::de::Content as _serde::Deserialize>::deserialize(__deserializer)?; let __deserializer = _serde::__private::de::ContentRefDeserializer::<__D::Error>::new(&__content);
// Generates significant part of the visit_seq and visit_map bodies of visitors // for the variants of internally tagged enum. fn deserialize_internally_tagged_variant(
params: &Parameters,
variant: &Variant,
cattrs: &attr::Container,
deserializer: TokenStream,
) -> Fragment { if variant.attrs.deserialize_with().is_some() { return deserialize_untagged_variant(params, variant, cattrs, deserializer);
}
let variant_ident = &variant.ident;
match effective_style(variant) {
Style::Unit => { let this_value = ¶ms.this_value; let type_name = params.type_name(); let variant_name = variant.ident.to_string(); let default = variant.fields.first().map(|field| { let default = Expr(expr_is_missing(field, cattrs));
quote!((#default))
});
quote_block! {
_serde::Deserializer::deserialize_any(#deserializer, _serde::__private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))?;
_serde::__private::Ok(#this_value::#variant_ident#default)
}
}
Style::Newtype => deserialize_untagged_newtype_variant(
variant_ident,
params,
&variant.fields[0],
&deserializer,
),
Style::Struct => deserialize_struct(
params,
&variant.fields,
cattrs,
StructForm::InternallyTagged(variant_ident, deserializer),
),
Style::Tuple => unreachable!("checked in serde_derive_internals"),
}
}
/// Generates enum and its `Deserialize` implementation that represents each /// non-skipped field of the struct fn deserialize_field_identifier(
deserialized_fields: &[FieldWithAliases],
cattrs: &attr::Container,
has_flatten: bool,
) -> Stmts { let (ignore_variant, fallthrough) = if has_flatten { let ignore_variant = quote!(__other(_serde::__private::de::Content<'de>),); let fallthrough = quote!(_serde::__private::Ok(__Field::__other(__value)));
(Some(ignore_variant), Some(fallthrough))
} elseif cattrs.deny_unknown_fields() {
(None, None)
} else { let ignore_variant = quote!(__ignore,); let fallthrough = quote!(_serde::__private::Ok(__Field::__ignore));
(Some(ignore_variant), Some(fallthrough))
};
#[automatically_derived] impl#de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics#where_clause { type Value = #this_type#ty_generics;
fn visit_unit<__E>(self) -> _serde::__private::Result<Self::Value, __E> where
__E: _serde::de::Error,
{
_serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Unit))
}
}
} else { let u64_mapping = deserialized_fields.iter().enumerate().map(|(i, field)| { let i = i as u64; let ident = &field.ident;
quote!(#i => _serde::__private::Ok(#this_value::#ident))
});
let u64_fallthrough_arm_tokens; let u64_fallthrough_arm = iflet Some(fallthrough) = &fallthrough {
fallthrough
} else { let index_expecting = if is_variant { "variant" } else { "field" }; let fallthrough_msg = format!( "{} index 0 <= i < {}",
index_expecting,
deserialized_fields.len(),
);
u64_fallthrough_arm_tokens = quote! {
_serde::__private::Err(_serde::de::Error::invalid_value(
_serde::de::Unexpected::Unsigned(__value),
&#fallthrough_msg,
))
};
&u64_fallthrough_arm_tokens
};
fn deserialize_map(
struct_path: &TokenStream,
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
has_flatten: bool,
) -> Fragment { // Create the field names for the fields. let fields_names: Vec<_> = fields
.iter()
.enumerate()
.map(|(i, field)| (field, field_i(i)))
.collect();
// Declare each field that will be deserialized. let let_values = fields_names
.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
.map(|(field, name)| { let field_ty = field.ty;
quote! { letmut#name: _serde::__private::Option<#field_ty> = _serde::__private::None;
}
});
// Collect contents for flatten fields into a buffer let let_collect = if has_flatten {
Some(quote! { letmut __collect = _serde::__private::Vec::<_serde::__private::Option<(
_serde::__private::de::Content,
_serde::__private::de::Content
)>>::new();
})
} else {
None
};
// Match arms to extract a value for a field. let value_arms = fields_names
.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
.map(|(field, name)| { let deser_name = field.attrs.name().deserialize_name();
let visit = match field.attrs.deserialize_with() {
None => { let field_ty = field.ty; let span = field.original.span(); let func =
quote_spanned!(span=> _serde::de::MapAccess::next_value::<#field_ty>);
quote! { #func(&mut __map)?
}
}
Some(path) => { let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);
quote!({ #wrapper match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) {
_serde::__private::Ok(__wrapper) => __wrapper.value,
_serde::__private::Err(__err) => { return _serde::__private::Err(__err);
}
}
})
}
};
quote! {
__Field::#name => { if _serde::__private::Option::is_some(&#name) { return _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name));
} #name = _serde::__private::Some(#visit);
}
}
});
// Visit ignored values to consume them let ignored_arm = if has_flatten {
Some(quote! {
__Field::__other(__name) => {
__collect.push(_serde::__private::Some((
__name,
_serde::de::MapAccess::next_value(&mut __map)?)));
}
})
} elseif cattrs.deny_unknown_fields() {
None
} else {
Some(quote! {
_ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; }
})
};
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); let match_keys = if cattrs.deny_unknown_fields() && all_skipped {
quote! { // FIXME: Once feature(exhaustive_patterns) is stable: // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?;
_serde::__private::Option::map(
_serde::de::MapAccess::next_key::<__Field>(&mut __map)?,
|__impossible| match __impossible {});
}
} else {
quote! { whilelet _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&<span style='color:red'>mut __map)? { match __key { #(#value_arms)* #ignored_arm
}
}
}
};
let extract_values = fields_names
.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
.map(|(field, name)| { let missing_expr = Match(expr_is_missing(field, cattrs));
let result = fields_names.iter().map(|(field, name)| { let member = &field.member; if field.attrs.skip_deserializing() { let value = Expr(expr_is_missing(field, cattrs));
quote!(#member: #value)
} else {
quote!(#member: #name)
}
});
let let_default = match cattrs.default() {
attr::Default::Default => Some(quote!( let __default: Self::Value = _serde::__private::Default::default();
)), // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(default = "...")] // ^^^^^
attr::Default::Path(path) => Some(quote_spanned!(path.span()=> let __default: Self::Value = #path();
)),
attr::Default::None => { // We don't need the default value, to prevent an unused variable warning // we'll leave the line empty.
None
}
};
letmut result = quote!(#struct_path { #(#result),* }); if params.has_getter { let this_type = ¶ms.this_type; let (_, ty_generics, _) = params.generics.split_for_impl();
result = quote! {
_serde::__private::Into::<#this_type#ty_generics>::into(#result)
};
}
quote_block! { #(#let_values)*
#let_collect
#match_keys
#let_default
#(#extract_values)*
#(#extract_collected)*
#collected_deny_unknown_fields
_serde::__private::Ok(#result)
}
}
#[cfg(feature = "deserialize_in_place")] fn deserialize_map_in_place(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
) -> Fragment {
assert!(
!has_flatten(fields), "inplace deserialization of maps does not support flatten fields"
);
// Create the field names for the fields. let fields_names: Vec<_> = fields
.iter()
.enumerate()
.map(|(i, field)| (field, field_i(i)))
.collect();
// For deserialize_in_place, declare booleans for each field that will be // deserialized. let let_flags = fields_names
.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|(_, name)| {
quote! { letmut#name: bool = false;
}
});
// Match arms to extract a value for a field. let value_arms_from = fields_names
.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|(field, name)| { let deser_name = field.attrs.name().deserialize_name(); let member = &field.member;
// Visit ignored values to consume them let ignored_arm = if cattrs.deny_unknown_fields() {
None
} else {
Some(quote! {
_ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; }
})
};
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
let match_keys = if cattrs.deny_unknown_fields() && all_skipped {
quote! { // FIXME: Once feature(exhaustive_patterns) is stable: // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?;
_serde::__private::Option::map(
_serde::de::MapAccess::next_key::<__Field>(&mut __map)?,
|__impossible| match __impossible {});
}
} else {
quote! { whilelet _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&<span style='color:red'>mut __map)? { match __key { #(#value_arms_from)* #ignored_arm
}
}
}
};
let check_flags = fields_names
.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|(field, name)| { let missing_expr = expr_is_missing(field, cattrs); // If missing_expr unconditionally returns an error, don't try // to assign its value to self.place. if field.attrs.default().is_none()
&& cattrs.default().is_none()
&& field.attrs.deserialize_with().is_some()
{ let missing_expr = Stmts(missing_expr);
quote! { if !#name { #missing_expr;
}
}
} else { let member = &field.member; let missing_expr = Expr(missing_expr);
quote! { if !#name { self.place.#member = #missing_expr;
};
}
}
});
let this_type = ¶ms.this_type; let (_, _, ty_generics, _) = split_with_de_lifetime(params);
let let_default = match cattrs.default() {
attr::Default::Default => Some(quote!( let __default: #this_type#ty_generics = _serde::__private::Default::default();
)), // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(default = "...")] // ^^^^^
attr::Default::Path(path) => Some(quote_spanned!(path.span()=> let __default: #this_type#ty_generics = #path();
)),
attr::Default::None => { // We don't need the default value, to prevent an unused variable warning // we'll leave the line empty.
None
}
};
/// This function wraps the expression in `#[serde(deserialize_with = "...")]` /// in a trait to prevent it from accessing the internal `Deserialize` state. fn wrap_deserialize_with(
params: &Parameters,
value_ty: &TokenStream,
deserialize_with: &syn::ExprPath,
) -> (TokenStream, TokenStream) { let this_type = ¶ms.this_type; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params); let delife = params.borrowed.de_lifetime(); let deserializer_var = quote!(__deserializer);
// If #deserialize_with returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(with = "...")] // ^^^^^ let value = quote_spanned! {deserialize_with.span()=> #deserialize_with(#deserializer_var)?
}; let wrapper = quote! { #[doc(hidden)] struct __DeserializeWith #de_impl_generics#where_clause {
value: #value_ty,
phantom: _serde::__private::PhantomData<#this_type#ty_generics>,
lifetime: _serde::__private::PhantomData<&#delife ()>,
}
let unwrap_fn = unwrap_to_variant_closure(params, variant, true);
(wrapper, wrapper_ty, unwrap_fn)
}
// Generates closure that converts single input parameter to the final value. fn unwrap_to_variant_closure(
params: &Parameters,
variant: &Variant,
with_wrapper: bool,
) -> TokenStream { let this_value = ¶ms.this_value; let variant_ident = &variant.ident;
fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { match field.attrs.default() {
attr::Default::Default => { let span = field.original.span(); let func = quote_spanned!(span=> _serde::__private::Default::default); return quote_expr!(#func());
}
attr::Default::Path(path) => { // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(default = "...")] // ^^^^^ return Fragment::Expr(quote_spanned!(path.span()=> #path()));
}
attr::Default::None => { /* below */ }
}
match *cattrs.default() {
attr::Default::Default | attr::Default::Path(_) => { let member = &field.member; return quote_expr!(__default.#member);
}
attr::Default::None => { /* below */ }
}
let name = field.attrs.name().deserialize_name(); match field.attrs.deserialize_with() {
None => { let span = field.original.span(); let func = quote_spanned!(span=> _serde::__private::de::missing_field);
quote_expr! { #func(#name)?
}
}
Some(_) => {
quote_expr! { return _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#name))
}
}
}
}
fn expr_is_missing_seq(
assign_to: Option<TokenStream>,
index: usize,
field: &Field,
cattrs: &attr::Container,
expecting: &str,
) -> TokenStream { match field.attrs.default() {
attr::Default::Default => { let span = field.original.span(); return quote_spanned!(span=> #assign_to _serde::__private::Default::default());
}
attr::Default::Path(path) => { // If #path returns wrong type, error will be reported here (^^^^^). // We attach span of the path to the function so it will be reported // on the #[serde(default = "...")] // ^^^^^ return quote_spanned!(path.span()=> #assign_to#path());
}
attr::Default::None => { /* below */ }
}
match *cattrs.default() {
attr::Default::Default | attr::Default::Path(_) => { let member = &field.member;
quote!(#assign_to __default.#member)
}
attr::Default::None => quote!( return _serde::__private::Err(_serde::de::Error::invalid_length(#index, &='color:turquoise'>#expecting))
),
}
}
fn effective_style(variant: &Variant) -> Style { match variant.style {
Style::Newtype if variant.fields[0].attrs.skip_deserializing() => Style::Unit,
other => other,
}
}
/// True if there is any field with a `#[serde(flatten)]` attribute, other than /// fields which are skipped. fn has_flatten(fields: &[Field]) -> bool {
fields
.iter()
.any(|field| field.attrs.flatten() && !field.attrs.skip_deserializing())
}
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.49Angebot
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 2026-06-18)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.