Skip to content
Myr

de.rs

This file

Path

serde_derive/src/de.rs

976 lines · 33.2 KiB · Rust

Last changed by

Merge pull request #3038 from dishmaker/dishmaker/serde_derive_field_iDavid Tolnaybefore adoptione65b3e7

History of this file

Take it

1use crate::deprecated::allow_deprecated;2use crate::fragment::{Expr, Fragment, Stmts};3use crate::internals::ast::{Container, Data, Field, Style, Variant};4use crate::internals::name::Name;5use crate::internals::{attr, replace_receiver, ungroup, Ctxt, Derive};6use crate::{bound, dummy, pretend, private, this};7use proc_macro2::{Span, TokenStream};8use quote::{quote, quote_spanned, ToTokens};9use std::collections::BTreeSet;10use std::ptr;11use syn::punctuated::Punctuated;12use syn::spanned::Spanned;13use syn::{parse_quote, Ident, Index, Member};1415mod enum_;16mod enum_adjacently;17mod enum_externally;18mod enum_internally;19mod enum_untagged;20mod identifier;21mod struct_;22mod tuple;23mod unit;2425pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result<TokenStream> {26    replace_receiver(input);2728    let ctxt = Ctxt::new();29    let Some(cont) = Container::from_ast(&ctxt, input, Derive::Deserialize, &private.ident())30    else {31        return Err(ctxt.check().unwrap_err());32    };33    precondition(&ctxt, &cont);34    ctxt.check()?;3536    let ident = &cont.ident;37    let params = Parameters::new(&cont);38    let (de_impl_generics, _, ty_generics, where_clause) = params.generics_with_de_lifetime();39    let body = Stmts(deserialize_body(&cont, &params));40    let delife = params.borrowed.de_lifetime();41    let allow_deprecated = allow_deprecated(input);4243    let impl_block = if let Some(remote) = cont.attrs.remote() {44        let vis = &input.vis;45        let used = pretend::pretend_used(&cont, params.is_packed);46        quote! {47            #[automatically_derived]48            #allow_deprecated49            impl #de_impl_generics #ident #ty_generics #where_clause {50                #vis fn deserialize<__D>(__deserializer: __D) -> _serde::#private::Result<#remote #ty_generics, __D::Error>51                where52                    __D: _serde::Deserializer<#delife>,53                {54                    #used55                    #body56                }57            }58        }59    } else {60        let fn_deserialize_in_place = deserialize_in_place_body(&cont, &params);6162        quote! {63            #[automatically_derived]64            #allow_deprecated65            impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause {66                fn deserialize<__D>(__deserializer: __D) -> _serde::#private::Result<Self, __D::Error>67                where68                    __D: _serde::Deserializer<#delife>,69                {70                    #body71                }7273                #fn_deserialize_in_place74            }75        }76    };7778    Ok(dummy::wrap_in_const(79        cont.attrs.custom_serde_path(),80        impl_block,81    ))82}8384fn precondition(cx: &Ctxt, cont: &Container) {85    precondition_sized(cx, cont);86    precondition_no_de_lifetime(cx, cont);87}8889fn precondition_sized(cx: &Ctxt, cont: &Container) {90    if let Data::Struct(_, fields) = &cont.data {91        if let Some(last) = fields.last() {92            if let syn::Type::Slice(_) = ungroup(last.ty) {93                cx.error_spanned_by(94                    cont.original,95                    "cannot deserialize a dynamically sized struct",96                );97            }98        }99    }100}101102fn precondition_no_de_lifetime(cx: &Ctxt, cont: &Container) {103    if let BorrowedLifetimes::Borrowed(_) = borrowed_lifetimes(cont) {104        for param in cont.generics.lifetimes() {105            if param.lifetime.to_string() == "'de" {106                cx.error_spanned_by(107                    &param.lifetime,108                    "cannot deserialize when there is a lifetime parameter called 'de",109                );110                return;111            }112        }113    }114}115116struct Parameters {117    /// Name of the type the `derive` is on.118    local: syn::Ident,119120    /// Path to the type the impl is for. Either a single `Ident` for local121    /// types (does not include generic parameters) or `some::remote::Path` for122    /// remote types.123    this_type: syn::Path,124125    /// Same as `this_type` but using `::<T>` for generic parameters for use in126    /// expression position.127    this_value: syn::Path,128129    /// Generics including any explicit and inferred bounds for the impl.130    generics: syn::Generics,131132    /// Lifetimes borrowed from the deserializer. These will become bounds on133    /// the `'de` lifetime of the deserializer.134    borrowed: BorrowedLifetimes,135136    /// At least one field has a serde(getter) attribute, implying that the137    /// remote type has a private field.138    has_getter: bool,139140    /// Type has a repr(packed) attribute.141    is_packed: bool,142}143144impl Parameters {145    fn new(cont: &Container) -> Self {146        let local = cont.ident.clone();147        let this_type = this::this_type(cont);148        let this_value = this::this_value(cont);149        let borrowed = borrowed_lifetimes(cont);150        let generics = build_generics(cont, &borrowed);151        let has_getter = cont.data.has_getter();152        let is_packed = cont.attrs.is_packed();153154        Parameters {155            local,156            this_type,157            this_value,158            generics,159            borrowed,160            has_getter,161            is_packed,162        }163    }164165    /// Type name to use in error messages and `&'static str` arguments to166    /// various Deserializer methods.167    fn type_name(&self) -> String {168        self.this_type.segments.last().unwrap().ident.to_string()169    }170171    /// Split the data structure's generics into the pieces to use for its172    /// `Deserialize` impl, augmented with an additional `'de` lifetime for use173    /// as the `Deserialize` trait's lifetime.174    fn generics_with_de_lifetime(175        &self,176    ) -> (177        DeImplGenerics,178        DeTypeGenerics,179        syn::TypeGenerics,180        Option<&syn::WhereClause>,181    ) {182        let de_impl_generics = DeImplGenerics(self);183        let de_ty_generics = DeTypeGenerics(self);184        let (_, ty_generics, where_clause) = self.generics.split_for_impl();185        (de_impl_generics, de_ty_generics, ty_generics, where_clause)186    }187}188189// All the generics in the input, plus a bound `T: Deserialize` for each generic190// field type that will be deserialized by us, plus a bound `T: Default` for191// each generic field type that will be set to a default value.192fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics {193    let generics = bound::without_defaults(cont.generics);194195    let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound);196197    let generics =198        bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::de_bound);199200    match cont.attrs.de_bound() {201        Some(predicates) => bound::with_where_predicates(&generics, predicates),202        None => {203            let generics = match *cont.attrs.default() {204                attr::Default::Default => bound::with_self_bound(205                    cont,206                    &generics,207                    &parse_quote!(_serde::#private::Default),208                ),209                attr::Default::None | attr::Default::Path(_) => generics,210            };211212            let delife = borrowed.de_lifetime();213            let generics = bound::with_bound(214                cont,215                &generics,216                needs_deserialize_bound,217                &parse_quote!(_serde::Deserialize<#delife>),218            );219220            bound::with_bound(221                cont,222                &generics,223                requires_default,224                &parse_quote!(_serde::#private::Default),225            )226        }227    }228}229230// Fields with a `skip_deserializing` or `deserialize_with` attribute, or which231// belong to a variant with a `skip_deserializing` or `deserialize_with`232// attribute, are not deserialized by us so we do not generate a bound. Fields233// with a `bound` attribute specify their own bound so we do not generate one.234// All other fields may need a `T: Deserialize` bound where T is the type of the235// field.236fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool {237    !field.skip_deserializing()238        && field.deserialize_with().is_none()239        && field.de_bound().is_none()240        && variant.map_or(true, |variant| {241            !variant.skip_deserializing()242                && variant.deserialize_with().is_none()243                && variant.de_bound().is_none()244        })245}246247// Fields with a `default` attribute (not `default=...`), and fields with a248// `skip_deserializing` attribute that do not also have `default=...`.249fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool {250    if let attr::Default::Default = *field.default() {251        true252    } else {253        false254    }255}256257enum BorrowedLifetimes {258    Borrowed(BTreeSet<syn::Lifetime>),259    Static,260}261262impl BorrowedLifetimes {263    fn de_lifetime(&self) -> syn::Lifetime {264        match *self {265            BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de", Span::call_site()),266            BorrowedLifetimes::Static => syn::Lifetime::new("'static", Span::call_site()),267        }268    }269270    fn de_lifetime_param(&self) -> Option<syn::LifetimeParam> {271        match self {272            BorrowedLifetimes::Borrowed(bounds) => Some(syn::LifetimeParam {273                attrs: Vec::new(),274                lifetime: syn::Lifetime::new("'de", Span::call_site()),275                colon_token: None,276                bounds: bounds.iter().cloned().collect(),277            }),278            BorrowedLifetimes::Static => None,279        }280    }281}282283// The union of lifetimes borrowed by each field of the container.284//285// These turn into bounds on the `'de` lifetime of the Deserialize impl. If286// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is:287//288//     impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c>289//290// If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant291// and we use plain `'static` instead of `'de`.292fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes {293    let mut lifetimes = BTreeSet::new();294    for field in cont.data.all_fields() {295        if !field.attrs.skip_deserializing() {296            lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());297        }298    }299    if lifetimes.iter().any(|b| b.to_string() == "'static") {300        BorrowedLifetimes::Static301    } else {302        BorrowedLifetimes::Borrowed(lifetimes)303    }304}305306fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment {307    if cont.attrs.transparent() {308        deserialize_transparent(cont, params)309    } else if let Some(type_from) = cont.attrs.type_from() {310        deserialize_from(type_from)311    } else if let Some(type_try_from) = cont.attrs.type_try_from() {312        deserialize_try_from(type_try_from)313    } else if let attr::Identifier::No = cont.attrs.identifier() {314        match &cont.data {315            Data::Enum(variants) => enum_::deserialize(params, variants, &cont.attrs),316            Data::Struct(Style::Struct, fields) => {317                struct_::deserialize(params, fields, &cont.attrs, StructForm::Struct)318            }319            Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => {320                tuple::deserialize(params, fields, &cont.attrs, TupleForm::Tuple)321            }322            Data::Struct(Style::Unit, _) => unit::deserialize(params, &cont.attrs),323        }324    } else {325        match &cont.data {326            Data::Enum(variants) => identifier::deserialize_custom(params, variants, &cont.attrs),327            Data::Struct(_, _) => unreachable!("checked in serde_derive_internals"),328        }329    }330}331332#[cfg(feature = "deserialize_in_place")]333fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<Stmts> {334    // Only remote derives have getters, and we do not generate335    // deserialize_in_place for remote derives.336    assert!(!params.has_getter);337338    if cont.attrs.transparent()339        || cont.attrs.type_from().is_some()340        || cont.attrs.type_try_from().is_some()341        || cont.attrs.identifier().is_some()342        || cont343            .data344            .all_fields()345            .all(|f| f.attrs.deserialize_with().is_some())346    {347        return None;348    }349350    let code = match &cont.data {351        Data::Struct(Style::Struct, fields) => {352            struct_::deserialize_in_place(params, fields, &cont.attrs)?353        }354        Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => {355            tuple::deserialize_in_place(params, fields, &cont.attrs)356        }357        Data::Enum(_) | Data::Struct(Style::Unit, _) => {358            return None;359        }360    };361362    let delife = params.borrowed.de_lifetime();363    let stmts = Stmts(code);364365    let fn_deserialize_in_place = quote_block! {366        fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::#private::Result<(), __D::Error>367        where368            __D: _serde::Deserializer<#delife>,369        {370            #stmts371        }372    };373374    Some(Stmts(fn_deserialize_in_place))375}376377#[cfg(not(feature = "deserialize_in_place"))]378fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option<Stmts> {379    None380}381382/// Generates `Deserialize::deserialize` body for a type with `#[serde(transparent)]` attribute383fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment {384    let fields = match &cont.data {385        Data::Struct(_, fields) => fields,386        Data::Enum(_) => unreachable!(),387    };388389    let this_value = &params.this_value;390    let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap();391392    let path = match transparent_field.attrs.deserialize_with() {393        Some(path) => quote!(#path),394        None => {395            let span = transparent_field.original.span();396            quote_spanned!(span=> _serde::Deserialize::deserialize)397        }398    };399400    let assign = fields.iter().map(|field| {401        let member = &field.member;402        if ptr::eq(field, transparent_field) {403            quote!(#member: __transparent)404        } else {405            let value = match field.attrs.default() {406                attr::Default::Default => quote!(_serde::#private::Default::default()),407                // If #path returns wrong type, error will be reported here (^^^^^).408                // We attach span of the path to the function so it will be reported409                // on the #[serde(default = "...")]410                //                          ^^^^^411                attr::Default::Path(path) => quote_spanned!(path.span()=> #path()),412                attr::Default::None => quote!(_serde::#private::PhantomData),413            };414            quote!(#member: #value)415        }416    });417418    quote_block! {419        _serde::#private::Result::map(420            #path(__deserializer),421            |__transparent| #this_value { #(#assign),* })422    }423}424425/// Generates `Deserialize::deserialize` body for a type with `#[serde(from)]` attribute426fn deserialize_from(type_from: &syn::Type) -> Fragment {427    quote_block! {428        _serde::#private::Result::map(429            <#type_from as _serde::Deserialize>::deserialize(__deserializer),430            _serde::#private::From::from)431    }432}433434/// Generates `Deserialize::deserialize` body for a type with `#[serde(try_from)]` attribute435fn deserialize_try_from(type_try_from: &syn::Type) -> Fragment {436    quote_block! {437        _serde::#private::Result::and_then(438            <#type_try_from as _serde::Deserialize>::deserialize(__deserializer),439            |v| _serde::#private::TryFrom::try_from(v).map_err(_serde::de::Error::custom))440    }441}442443enum TupleForm<'a> {444    Tuple,445    /// Contains a variant name446    ExternallyTagged(&'a syn::Ident),447    /// Contains a variant name448    Untagged(&'a syn::Ident),449}450451fn deserialize_seq(452    type_path: &TokenStream,453    params: &Parameters,454    fields: &[Field],455    is_struct: bool,456    cattrs: &attr::Container,457    expecting: &str,458) -> Fragment {459    let vars = (0..fields.len()).map(field_i as fn(_) -> _);460461    let deserialized_count = fields462        .iter()463        .filter(|field| !field.attrs.skip_deserializing())464        .count();465    let expecting = if deserialized_count == 1 {466        format!("{} with 1 element", expecting)467    } else {468        format!("{} with {} elements", expecting, deserialized_count)469    };470    let expecting = cattrs.expecting().unwrap_or(&expecting);471472    let mut index_in_seq = 0_usize;473    let let_values = vars.clone().zip(fields).map(|(var, field)| {474        if field.attrs.skip_deserializing() {475            let default = Expr(expr_is_missing(field, cattrs));476            quote! {477                let #var = #default;478            }479        } else {480            let visit = match field.attrs.deserialize_with() {481                None => {482                    let field_ty = field.ty;483                    let span = field.original.span();484                    let func =485                        quote_spanned!(span=> _serde::de::SeqAccess::next_element::<#field_ty>);486                    quote!(#func(&mut __seq)?)487                }488                Some(path) => {489                    let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);490                    quote!({491                        #wrapper492                        _serde::#private::Option::map(493                            _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)?,494                            |__wrap| __wrap.value)495                    })496                }497            };498            let value_if_none = expr_is_missing_seq(None, index_in_seq, field, cattrs, expecting);499            let assign = quote! {500                let #var = match #visit {501                    _serde::#private::Some(__value) => __value,502                    _serde::#private::None => #value_if_none,503                };504            };505            index_in_seq += 1;506            assign507        }508    });509510    let mut result = if is_struct {511        let names = fields.iter().map(|f| &f.member);512        quote! {513            #type_path { #( #names: #vars ),* }514        }515    } else {516        quote! {517            #type_path ( #(#vars),* )518        }519    };520521    if params.has_getter {522        let this_type = &params.this_type;523        let (_, ty_generics, _) = params.generics.split_for_impl();524        result = quote! {525            _serde::#private::Into::<#this_type #ty_generics>::into(#result)526        };527    }528529    let let_default = match cattrs.default() {530        attr::Default::Default => Some(quote!(531            let __default: Self::Value = _serde::#private::Default::default();532        )),533        // If #path returns wrong type, error will be reported here (^^^^^).534        // We attach span of the path to the function so it will be reported535        // on the #[serde(default = "...")]536        //                          ^^^^^537        attr::Default::Path(path) => Some(quote_spanned!(path.span()=>538            let __default: Self::Value = #path();539        )),540        attr::Default::None => {541            // We don't need the default value, to prevent an unused variable warning542            // we'll leave the line empty.543            None544        }545    };546547    quote_block! {548        #let_default549        #(#let_values)*550        _serde::#private::Ok(#result)551    }552}553554#[cfg(feature = "deserialize_in_place")]555fn deserialize_seq_in_place(556    params: &Parameters,557    fields: &[Field],558    cattrs: &attr::Container,559    expecting: &str,560) -> Fragment {561    let deserialized_count = fields562        .iter()563        .filter(|field| !field.attrs.skip_deserializing())564        .count();565    let expecting = if deserialized_count == 1 {566        format!("{} with 1 element", expecting)567    } else {568        format!("{} with {} elements", expecting, deserialized_count)569    };570    let expecting = cattrs.expecting().unwrap_or(&expecting);571572    let mut index_in_seq = 0usize;573    let write_values = fields.iter().map(|field| {574        let member = &field.member;575576        if field.attrs.skip_deserializing() {577            let default = Expr(expr_is_missing(field, cattrs));578            quote! {579                self.place.#member = #default;580            }581        } else {582            let value_if_none = expr_is_missing_seq(Some(quote!(self.place.#member = )), index_in_seq, field, cattrs, expecting);583            let write = match field.attrs.deserialize_with() {584                None => {585                    quote! {586                        if let _serde::#private::None = _serde::de::SeqAccess::next_element_seed(&mut __seq,587                            _serde::#private::de::InPlaceSeed(&mut self.place.#member))?588                        {589                            #value_if_none;590                        }591                    }592                }593                Some(path) => {594                    let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);595                    quote!({596                        #wrapper597                        match _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq) {598                            _serde::#private::Ok(_serde::#private::Some(__wrap)) => {599                                self.place.#member = __wrap.value;600                            }601                            _serde::#private::Ok(_serde::#private::None) => {602                                #value_if_none;603                            }604                            _serde::#private::Err(__err) => {605                                return _serde::#private::Err(__err);606                            }607                        }608                    })609                }610            };611            index_in_seq += 1;612            write613        }614    });615616    let this_type = &params.this_type;617    let (_, ty_generics, _) = params.generics.split_for_impl();618    let let_default = match cattrs.default() {619        attr::Default::Default => Some(quote!(620            let __default: #this_type #ty_generics = _serde::#private::Default::default();621        )),622        // If #path returns wrong type, error will be reported here (^^^^^).623        // We attach span of the path to the function so it will be reported624        // on the #[serde(default = "...")]625        //                          ^^^^^626        attr::Default::Path(path) => Some(quote_spanned!(path.span()=>627            let __default: #this_type #ty_generics = #path();628        )),629        attr::Default::None => {630            // We don't need the default value, to prevent an unused variable warning631            // we'll leave the line empty.632            None633        }634    };635636    quote_block! {637        #let_default638        #(#write_values)*639        _serde::#private::Ok(())640    }641}642643enum StructForm<'a> {644    Struct,645    /// Contains a variant name646    ExternallyTagged(&'a syn::Ident),647    /// Contains a variant name648    InternallyTagged(&'a syn::Ident),649    /// Contains a variant name650    Untagged(&'a syn::Ident),651}652653struct FieldWithAliases<'a> {654    ident: Ident,655    aliases: &'a BTreeSet<Name>,656}657658pub(crate) fn field_i(i: usize) -> Ident {659    Ident::new(&format!("__field{}", i), Span::call_site())660}661662/// This function wraps the expression in `#[serde(deserialize_with = "...")]`663/// in a trait to prevent it from accessing the internal `Deserialize` state.664fn wrap_deserialize_with(665    params: &Parameters,666    value_ty: &TokenStream,667    deserialize_with: &syn::ExprPath,668) -> (TokenStream, TokenStream) {669    let this_type = &params.this_type;670    let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =671        params.generics_with_de_lifetime();672    let delife = params.borrowed.de_lifetime();673    let deserializer_var = quote!(__deserializer);674675    // If #deserialize_with returns wrong type, error will be reported here (^^^^^).676    // We attach span of the path to the function so it will be reported677    // on the #[serde(with = "...")]678    //                       ^^^^^679    let value = quote_spanned! {deserialize_with.span()=>680        #deserialize_with(#deserializer_var)?681    };682    let wrapper = quote! {683        #[doc(hidden)]684        struct __DeserializeWith #de_impl_generics #where_clause {685            value: #value_ty,686            phantom: _serde::#private::PhantomData<#this_type #ty_generics>,687            lifetime: _serde::#private::PhantomData<&#delife ()>,688        }689690        #[automatically_derived]691        impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause {692            fn deserialize<__D>(#deserializer_var: __D) -> _serde::#private::Result<Self, __D::Error>693            where694                __D: _serde::Deserializer<#delife>,695            {696                _serde::#private::Ok(__DeserializeWith {697                    value: #value,698                    phantom: _serde::#private::PhantomData,699                    lifetime: _serde::#private::PhantomData,700                })701            }702        }703    };704705    let wrapper_ty = quote!(__DeserializeWith #de_ty_generics);706707    (wrapper, wrapper_ty)708}709710fn wrap_deserialize_field_with(711    params: &Parameters,712    field_ty: &syn::Type,713    deserialize_with: &syn::ExprPath,714) -> (TokenStream, TokenStream) {715    wrap_deserialize_with(params, &quote!(#field_ty), deserialize_with)716}717718// Generates closure that converts single input parameter to the final value.719fn unwrap_to_variant_closure(720    params: &Parameters,721    variant: &Variant,722    with_wrapper: bool,723) -> TokenStream {724    let this_value = &params.this_value;725    let variant_ident = &variant.ident;726727    let (arg, wrapper) = if with_wrapper {728        (quote! { __wrap }, quote! { __wrap.value })729    } else {730        let field_tys = variant.fields.iter().map(|field| field.ty);731        (quote! { __wrap: (#(#field_tys),*) }, quote! { __wrap })732    };733734    let field_access = (0..variant.fields.len()).map(|n| {735        Member::Unnamed(Index {736            index: n as u32,737            span: Span::call_site(),738        })739    });740741    match variant.style {742        Style::Struct if variant.fields.len() == 1 => {743            let member = &variant.fields[0].member;744            quote! {745                |#arg| #this_value::#variant_ident { #member: #wrapper }746            }747        }748        Style::Struct => {749            let members = variant.fields.iter().map(|field| &field.member);750            quote! {751                |#arg| #this_value::#variant_ident { #(#members: #wrapper.#field_access),* }752            }753        }754        Style::Tuple => quote! {755            |#arg| #this_value::#variant_ident(#(#wrapper.#field_access),*)756        },757        Style::Newtype => quote! {758            |#arg| #this_value::#variant_ident(#wrapper)759        },760        Style::Unit => quote! {761            |#arg| #this_value::#variant_ident762        },763    }764}765766fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment {767    match field.attrs.default() {768        attr::Default::Default => {769            let span = field.original.span();770            let func = quote_spanned!(span=> _serde::#private::Default::default);771            return quote_expr!(#func());772        }773        attr::Default::Path(path) => {774            // If #path returns wrong type, error will be reported here (^^^^^).775            // We attach span of the path to the function so it will be reported776            // on the #[serde(default = "...")]777            //                          ^^^^^778            return Fragment::Expr(quote_spanned!(path.span()=> #path()));779        }780        attr::Default::None => { /* below */ }781    }782783    match *cattrs.default() {784        attr::Default::Default | attr::Default::Path(_) => {785            let member = &field.member;786            return quote_expr!(__default.#member);787        }788        attr::Default::None => { /* below */ }789    }790791    let name = field.attrs.name().deserialize_name();792    match field.attrs.deserialize_with() {793        None => {794            let span = field.original.span();795            let func = quote_spanned!(span=> _serde::#private::de::missing_field);796            quote_expr! {797                #func(#name)?798            }799        }800        Some(_) => {801            quote_expr! {802                return _serde::#private::Err(<__A::Error as _serde::de::Error>::missing_field(#name))803            }804        }805    }806}807808fn expr_is_missing_seq(809    assign_to: Option<TokenStream>,810    index: usize,811    field: &Field,812    cattrs: &attr::Container,813    expecting: &str,814) -> TokenStream {815    match field.attrs.default() {816        attr::Default::Default => {817            let span = field.original.span();818            return quote_spanned!(span=> #assign_to _serde::#private::Default::default());819        }820        attr::Default::Path(path) => {821            // If #path returns wrong type, error will be reported here (^^^^^).822            // We attach span of the path to the function so it will be reported823            // on the #[serde(default = "...")]824            //                          ^^^^^825            return quote_spanned!(path.span()=> #assign_to #path());826        }827        attr::Default::None => { /* below */ }828    }829830    match *cattrs.default() {831        attr::Default::Default | attr::Default::Path(_) => {832            let member = &field.member;833            quote!(#assign_to __default.#member)834        }835        attr::Default::None => quote!(836            return _serde::#private::Err(_serde::de::Error::invalid_length(#index, &#expecting))837        ),838    }839}840841fn effective_style(variant: &Variant) -> Style {842    match variant.style {843        Style::Newtype if variant.fields[0].attrs.skip_deserializing() => Style::Unit,844        other => other,845    }846}847848/// True if there is any field with a `#[serde(flatten)]` attribute, other than849/// fields which are skipped.850fn has_flatten(fields: &[Field]) -> bool {851    fields852        .iter()853        .any(|field| field.attrs.flatten() && !field.attrs.skip_deserializing())854}855856struct DeImplGenerics<'a>(&'a Parameters);857#[cfg(feature = "deserialize_in_place")]858struct InPlaceImplGenerics<'a>(&'a Parameters);859860impl<'a> ToTokens for DeImplGenerics<'a> {861    fn to_tokens(&self, tokens: &mut TokenStream) {862        let mut generics = self.0.generics.clone();863        if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() {864            generics.params = Some(syn::GenericParam::Lifetime(de_lifetime))865                .into_iter()866                .chain(generics.params)867                .collect();868        }869        let (impl_generics, _, _) = generics.split_for_impl();870        impl_generics.to_tokens(tokens);871    }872}873874#[cfg(feature = "deserialize_in_place")]875impl<'a> ToTokens for InPlaceImplGenerics<'a> {876    fn to_tokens(&self, tokens: &mut TokenStream) {877        let place_lifetime = place_lifetime();878        let mut generics = self.0.generics.clone();879880        // Add lifetime for `&'place mut Self, and `'a: 'place`881        for param in &mut generics.params {882            match param {883                syn::GenericParam::Lifetime(param) => {884                    param.bounds.push(place_lifetime.lifetime.clone());885                }886                syn::GenericParam::Type(param) => {887                    param.bounds.push(syn::TypeParamBound::Lifetime(888                        place_lifetime.lifetime.clone(),889                    ));890                }891                syn::GenericParam::Const(_) => {}892            }893        }894        generics.params = Some(syn::GenericParam::Lifetime(place_lifetime))895            .into_iter()896            .chain(generics.params)897            .collect();898        if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() {899            generics.params = Some(syn::GenericParam::Lifetime(de_lifetime))900                .into_iter()901                .chain(generics.params)902                .collect();903        }904        let (impl_generics, _, _) = generics.split_for_impl();905        impl_generics.to_tokens(tokens);906    }907}908909#[cfg(feature = "deserialize_in_place")]910impl<'a> DeImplGenerics<'a> {911    fn in_place(self) -> InPlaceImplGenerics<'a> {912        InPlaceImplGenerics(self.0)913    }914}915916struct DeTypeGenerics<'a>(&'a Parameters);917#[cfg(feature = "deserialize_in_place")]918struct InPlaceTypeGenerics<'a>(&'a Parameters);919920fn de_type_generics_to_tokens(921    mut generics: syn::Generics,922    borrowed: &BorrowedLifetimes,923    tokens: &mut TokenStream,924) {925    if borrowed.de_lifetime_param().is_some() {926        let def = syn::LifetimeParam {927            attrs: Vec::new(),928            lifetime: syn::Lifetime::new("'de", Span::call_site()),929            colon_token: None,930            bounds: Punctuated::new(),931        };932        // Prepend 'de lifetime to list of generics933        generics.params = Some(syn::GenericParam::Lifetime(def))934            .into_iter()935            .chain(generics.params)936            .collect();937    }938    let (_, ty_generics, _) = generics.split_for_impl();939    ty_generics.to_tokens(tokens);940}941942impl<'a> ToTokens for DeTypeGenerics<'a> {943    fn to_tokens(&self, tokens: &mut TokenStream) {944        de_type_generics_to_tokens(self.0.generics.clone(), &self.0.borrowed, tokens);945    }946}947948#[cfg(feature = "deserialize_in_place")]949impl<'a> ToTokens for InPlaceTypeGenerics<'a> {950    fn to_tokens(&self, tokens: &mut TokenStream) {951        let mut generics = self.0.generics.clone();952        generics.params = Some(syn::GenericParam::Lifetime(place_lifetime()))953            .into_iter()954            .chain(generics.params)955            .collect();956957        de_type_generics_to_tokens(generics, &self.0.borrowed, tokens);958    }959}960961#[cfg(feature = "deserialize_in_place")]962impl<'a> DeTypeGenerics<'a> {963    fn in_place(self) -> InPlaceTypeGenerics<'a> {964        InPlaceTypeGenerics(self.0)965    }966}967968#[cfg(feature = "deserialize_in_place")]969fn place_lifetime() -> syn::LifetimeParam {970    syn::LifetimeParam {971        attrs: Vec::new(),972        lifetime: syn::Lifetime::new("'place", Span::call_site()),973        colon_token: None,974        bounds: Punctuated::new(),975    }976}