serde_derive/
de.rs

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};
14
15mod enum_;
16mod enum_adjacently;
17mod enum_externally;
18mod enum_internally;
19mod enum_untagged;
20mod identifier;
21mod struct_;
22mod tuple;
23mod unit;
24
25pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result<TokenStream> {
26    replace_receiver(input);
27
28    let ctxt = Ctxt::new();
29    let cont = match Container::from_ast(&ctxt, input, Derive::Deserialize, &private.ident()) {
30        Some(cont) => cont,
31        None => return Err(ctxt.check().unwrap_err()),
32    };
33    precondition(&ctxt, &cont);
34    ctxt.check()?;
35
36    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);
42
43    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_deprecated
49            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                where
52                    __D: _serde::Deserializer<#delife>,
53                {
54                    #used
55                    #body
56                }
57            }
58        }
59    } else {
60        let fn_deserialize_in_place = deserialize_in_place_body(&cont, &params);
61
62        quote! {
63            #[automatically_derived]
64            #allow_deprecated
65            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                where
68                    __D: _serde::Deserializer<#delife>,
69                {
70                    #body
71                }
72
73                #fn_deserialize_in_place
74            }
75        }
76    };
77
78    Ok(dummy::wrap_in_const(
79        cont.attrs.custom_serde_path(),
80        impl_block,
81    ))
82}
83
84fn precondition(cx: &Ctxt, cont: &Container) {
85    precondition_sized(cx, cont);
86    precondition_no_de_lifetime(cx, cont);
87}
88
89fn 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}
101
102fn 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}
115
116struct Parameters {
117    /// Name of the type the `derive` is on.
118    local: syn::Ident,
119
120    /// Path to the type the impl is for. Either a single `Ident` for local
121    /// types (does not include generic parameters) or `some::remote::Path` for
122    /// remote types.
123    this_type: syn::Path,
124
125    /// Same as `this_type` but using `::<T>` for generic parameters for use in
126    /// expression position.
127    this_value: syn::Path,
128
129    /// Generics including any explicit and inferred bounds for the impl.
130    generics: syn::Generics,
131
132    /// Lifetimes borrowed from the deserializer. These will become bounds on
133    /// the `'de` lifetime of the deserializer.
134    borrowed: BorrowedLifetimes,
135
136    /// At least one field has a serde(getter) attribute, implying that the
137    /// remote type has a private field.
138    has_getter: bool,
139
140    /// Type has a repr(packed) attribute.
141    is_packed: bool,
142}
143
144impl 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();
153
154        Parameters {
155            local,
156            this_type,
157            this_value,
158            generics,
159            borrowed,
160            has_getter,
161            is_packed,
162        }
163    }
164
165    /// Type name to use in error messages and `&'static str` arguments to
166    /// various Deserializer methods.
167    fn type_name(&self) -> String {
168        self.this_type.segments.last().unwrap().ident.to_string()
169    }
170
171    /// Split the data structure's generics into the pieces to use for its
172    /// `Deserialize` impl, augmented with an additional `'de` lifetime for use
173    /// 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}
188
189// All the generics in the input, plus a bound `T: Deserialize` for each generic
190// field type that will be deserialized by us, plus a bound `T: Default` for
191// 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);
194
195    let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound);
196
197    let generics =
198        bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::de_bound);
199
200    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            };
211
212            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            );
219
220            bound::with_bound(
221                cont,
222                &generics,
223                requires_default,
224                &parse_quote!(_serde::#private::Default),
225            )
226        }
227    }
228}
229
230// Fields with a `skip_deserializing` or `deserialize_with` attribute, or which
231// 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. Fields
233// 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 the
235// 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}
246
247// Fields with a `default` attribute (not `default=...`), and fields with a
248// `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        true
252    } else {
253        false
254    }
255}
256
257enum BorrowedLifetimes {
258    Borrowed(BTreeSet<syn::Lifetime>),
259    Static,
260}
261
262impl 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    }
269
270    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}
282
283// 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. If
286// 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 redundant
291// 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::Static
301    } else {
302        BorrowedLifetimes::Borrowed(lifetimes)
303    }
304}
305
306fn 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}
331
332#[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 generate
335    // deserialize_in_place for remote derives.
336    assert!(!params.has_getter);
337
338    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        || cont
343            .data
344            .all_fields()
345            .all(|f| f.attrs.deserialize_with().is_some())
346    {
347        return None;
348    }
349
350    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    };
361
362    let delife = params.borrowed.de_lifetime();
363    let stmts = Stmts(code);
364
365    let fn_deserialize_in_place = quote_block! {
366        fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::#private::Result<(), __D::Error>
367        where
368            __D: _serde::Deserializer<#delife>,
369        {
370            #stmts
371        }
372    };
373
374    Some(Stmts(fn_deserialize_in_place))
375}
376
377#[cfg(not(feature = "deserialize_in_place"))]
378fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option<Stmts> {
379    None
380}
381
382/// Generates `Deserialize::deserialize` body for a type with `#[serde(transparent)]` attribute
383fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment {
384    let fields = match &cont.data {
385        Data::Struct(_, fields) => fields,
386        Data::Enum(_) => unreachable!(),
387    };
388
389    let this_value = &params.this_value;
390    let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap();
391
392    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    };
399
400    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 reported
409                // 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    });
417
418    quote_block! {
419        _serde::#private::Result::map(
420            #path(__deserializer),
421            |__transparent| #this_value { #(#assign),* })
422    }
423}
424
425/// Generates `Deserialize::deserialize` body for a type with `#[serde(from)]` attribute
426fn 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}
433
434/// Generates `Deserialize::deserialize` body for a type with `#[serde(try_from)]` attribute
435fn 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}
442
443enum TupleForm<'a> {
444    Tuple,
445    /// Contains a variant name
446    ExternallyTagged(&'a syn::Ident),
447    /// Contains a variant name
448    Untagged(&'a syn::Ident),
449}
450
451fn 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(_) -> _);
460
461    let deserialized_count = fields
462        .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);
471
472    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                        #wrapper
492                        _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            assign
507        }
508    });
509
510    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    };
520
521    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    }
528
529    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 reported
535        // 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 warning
542            // we'll leave the line empty.
543            None
544        }
545    };
546
547    quote_block! {
548        #let_default
549        #(#let_values)*
550        _serde::#private::Ok(#result)
551    }
552}
553
554#[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 = fields
562        .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);
571
572    let mut index_in_seq = 0usize;
573    let write_values = fields.iter().map(|field| {
574        let member = &field.member;
575
576        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                        #wrapper
597                        match _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)? {
598                            _serde::#private::Some(__wrap) => {
599                                self.place.#member = __wrap.value;
600                            }
601                            _serde::#private::None => {
602                                #value_if_none;
603                            }
604                        }
605                    })
606                }
607            };
608            index_in_seq += 1;
609            write
610        }
611    });
612
613    let this_type = &params.this_type;
614    let (_, ty_generics, _) = params.generics.split_for_impl();
615    let let_default = match cattrs.default() {
616        attr::Default::Default => Some(quote!(
617            let __default: #this_type #ty_generics = _serde::#private::Default::default();
618        )),
619        // If #path returns wrong type, error will be reported here (^^^^^).
620        // We attach span of the path to the function so it will be reported
621        // on the #[serde(default = "...")]
622        //                          ^^^^^
623        attr::Default::Path(path) => Some(quote_spanned!(path.span()=>
624            let __default: #this_type #ty_generics = #path();
625        )),
626        attr::Default::None => {
627            // We don't need the default value, to prevent an unused variable warning
628            // we'll leave the line empty.
629            None
630        }
631    };
632
633    quote_block! {
634        #let_default
635        #(#write_values)*
636        _serde::#private::Ok(())
637    }
638}
639
640enum StructForm<'a> {
641    Struct,
642    /// Contains a variant name
643    ExternallyTagged(&'a syn::Ident),
644    /// Contains a variant name
645    InternallyTagged(&'a syn::Ident),
646    /// Contains a variant name
647    Untagged(&'a syn::Ident),
648}
649
650struct FieldWithAliases<'a> {
651    ident: Ident,
652    aliases: &'a BTreeSet<Name>,
653}
654
655fn field_i(i: usize) -> Ident {
656    Ident::new(&format!("__field{}", i), Span::call_site())
657}
658
659/// This function wraps the expression in `#[serde(deserialize_with = "...")]`
660/// in a trait to prevent it from accessing the internal `Deserialize` state.
661fn wrap_deserialize_with(
662    params: &Parameters,
663    value_ty: &TokenStream,
664    deserialize_with: &syn::ExprPath,
665) -> (TokenStream, TokenStream) {
666    let this_type = &params.this_type;
667    let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
668        params.generics_with_de_lifetime();
669    let delife = params.borrowed.de_lifetime();
670    let deserializer_var = quote!(__deserializer);
671
672    // If #deserialize_with returns wrong type, error will be reported here (^^^^^).
673    // We attach span of the path to the function so it will be reported
674    // on the #[serde(with = "...")]
675    //                       ^^^^^
676    let value = quote_spanned! {deserialize_with.span()=>
677        #deserialize_with(#deserializer_var)?
678    };
679    let wrapper = quote! {
680        #[doc(hidden)]
681        struct __DeserializeWith #de_impl_generics #where_clause {
682            value: #value_ty,
683            phantom: _serde::#private::PhantomData<#this_type #ty_generics>,
684            lifetime: _serde::#private::PhantomData<&#delife ()>,
685        }
686
687        #[automatically_derived]
688        impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause {
689            fn deserialize<__D>(#deserializer_var: __D) -> _serde::#private::Result<Self, __D::Error>
690            where
691                __D: _serde::Deserializer<#delife>,
692            {
693                _serde::#private::Ok(__DeserializeWith {
694                    value: #value,
695                    phantom: _serde::#private::PhantomData,
696                    lifetime: _serde::#private::PhantomData,
697                })
698            }
699        }
700    };
701
702    let wrapper_ty = quote!(__DeserializeWith #de_ty_generics);
703
704    (wrapper, wrapper_ty)
705}
706
707fn wrap_deserialize_field_with(
708    params: &Parameters,
709    field_ty: &syn::Type,
710    deserialize_with: &syn::ExprPath,
711) -> (TokenStream, TokenStream) {
712    wrap_deserialize_with(params, &quote!(#field_ty), deserialize_with)
713}
714
715// Generates closure that converts single input parameter to the final value.
716fn unwrap_to_variant_closure(
717    params: &Parameters,
718    variant: &Variant,
719    with_wrapper: bool,
720) -> TokenStream {
721    let this_value = &params.this_value;
722    let variant_ident = &variant.ident;
723
724    let (arg, wrapper) = if with_wrapper {
725        (quote! { __wrap }, quote! { __wrap.value })
726    } else {
727        let field_tys = variant.fields.iter().map(|field| field.ty);
728        (quote! { __wrap: (#(#field_tys),*) }, quote! { __wrap })
729    };
730
731    let field_access = (0..variant.fields.len()).map(|n| {
732        Member::Unnamed(Index {
733            index: n as u32,
734            span: Span::call_site(),
735        })
736    });
737
738    match variant.style {
739        Style::Struct if variant.fields.len() == 1 => {
740            let member = &variant.fields[0].member;
741            quote! {
742                |#arg| #this_value::#variant_ident { #member: #wrapper }
743            }
744        }
745        Style::Struct => {
746            let members = variant.fields.iter().map(|field| &field.member);
747            quote! {
748                |#arg| #this_value::#variant_ident { #(#members: #wrapper.#field_access),* }
749            }
750        }
751        Style::Tuple => quote! {
752            |#arg| #this_value::#variant_ident(#(#wrapper.#field_access),*)
753        },
754        Style::Newtype => quote! {
755            |#arg| #this_value::#variant_ident(#wrapper)
756        },
757        Style::Unit => quote! {
758            |#arg| #this_value::#variant_ident
759        },
760    }
761}
762
763fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment {
764    match field.attrs.default() {
765        attr::Default::Default => {
766            let span = field.original.span();
767            let func = quote_spanned!(span=> _serde::#private::Default::default);
768            return quote_expr!(#func());
769        }
770        attr::Default::Path(path) => {
771            // If #path returns wrong type, error will be reported here (^^^^^).
772            // We attach span of the path to the function so it will be reported
773            // on the #[serde(default = "...")]
774            //                          ^^^^^
775            return Fragment::Expr(quote_spanned!(path.span()=> #path()));
776        }
777        attr::Default::None => { /* below */ }
778    }
779
780    match *cattrs.default() {
781        attr::Default::Default | attr::Default::Path(_) => {
782            let member = &field.member;
783            return quote_expr!(__default.#member);
784        }
785        attr::Default::None => { /* below */ }
786    }
787
788    let name = field.attrs.name().deserialize_name();
789    match field.attrs.deserialize_with() {
790        None => {
791            let span = field.original.span();
792            let func = quote_spanned!(span=> _serde::#private::de::missing_field);
793            quote_expr! {
794                #func(#name)?
795            }
796        }
797        Some(_) => {
798            quote_expr! {
799                return _serde::#private::Err(<__A::Error as _serde::de::Error>::missing_field(#name))
800            }
801        }
802    }
803}
804
805fn expr_is_missing_seq(
806    assign_to: Option<TokenStream>,
807    index: usize,
808    field: &Field,
809    cattrs: &attr::Container,
810    expecting: &str,
811) -> TokenStream {
812    match field.attrs.default() {
813        attr::Default::Default => {
814            let span = field.original.span();
815            return quote_spanned!(span=> #assign_to _serde::#private::Default::default());
816        }
817        attr::Default::Path(path) => {
818            // If #path returns wrong type, error will be reported here (^^^^^).
819            // We attach span of the path to the function so it will be reported
820            // on the #[serde(default = "...")]
821            //                          ^^^^^
822            return quote_spanned!(path.span()=> #assign_to #path());
823        }
824        attr::Default::None => { /* below */ }
825    }
826
827    match *cattrs.default() {
828        attr::Default::Default | attr::Default::Path(_) => {
829            let member = &field.member;
830            quote!(#assign_to __default.#member)
831        }
832        attr::Default::None => quote!(
833            return _serde::#private::Err(_serde::de::Error::invalid_length(#index, &#expecting))
834        ),
835    }
836}
837
838fn effective_style(variant: &Variant) -> Style {
839    match variant.style {
840        Style::Newtype if variant.fields[0].attrs.skip_deserializing() => Style::Unit,
841        other => other,
842    }
843}
844
845/// True if there is any field with a `#[serde(flatten)]` attribute, other than
846/// fields which are skipped.
847fn has_flatten(fields: &[Field]) -> bool {
848    fields
849        .iter()
850        .any(|field| field.attrs.flatten() && !field.attrs.skip_deserializing())
851}
852
853struct DeImplGenerics<'a>(&'a Parameters);
854#[cfg(feature = "deserialize_in_place")]
855struct InPlaceImplGenerics<'a>(&'a Parameters);
856
857impl<'a> ToTokens for DeImplGenerics<'a> {
858    fn to_tokens(&self, tokens: &mut TokenStream) {
859        let mut generics = self.0.generics.clone();
860        if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() {
861            generics.params = Some(syn::GenericParam::Lifetime(de_lifetime))
862                .into_iter()
863                .chain(generics.params)
864                .collect();
865        }
866        let (impl_generics, _, _) = generics.split_for_impl();
867        impl_generics.to_tokens(tokens);
868    }
869}
870
871#[cfg(feature = "deserialize_in_place")]
872impl<'a> ToTokens for InPlaceImplGenerics<'a> {
873    fn to_tokens(&self, tokens: &mut TokenStream) {
874        let place_lifetime = place_lifetime();
875        let mut generics = self.0.generics.clone();
876
877        // Add lifetime for `&'place mut Self, and `'a: 'place`
878        for param in &mut generics.params {
879            match param {
880                syn::GenericParam::Lifetime(param) => {
881                    param.bounds.push(place_lifetime.lifetime.clone());
882                }
883                syn::GenericParam::Type(param) => {
884                    param.bounds.push(syn::TypeParamBound::Lifetime(
885                        place_lifetime.lifetime.clone(),
886                    ));
887                }
888                syn::GenericParam::Const(_) => {}
889            }
890        }
891        generics.params = Some(syn::GenericParam::Lifetime(place_lifetime))
892            .into_iter()
893            .chain(generics.params)
894            .collect();
895        if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() {
896            generics.params = Some(syn::GenericParam::Lifetime(de_lifetime))
897                .into_iter()
898                .chain(generics.params)
899                .collect();
900        }
901        let (impl_generics, _, _) = generics.split_for_impl();
902        impl_generics.to_tokens(tokens);
903    }
904}
905
906#[cfg(feature = "deserialize_in_place")]
907impl<'a> DeImplGenerics<'a> {
908    fn in_place(self) -> InPlaceImplGenerics<'a> {
909        InPlaceImplGenerics(self.0)
910    }
911}
912
913struct DeTypeGenerics<'a>(&'a Parameters);
914#[cfg(feature = "deserialize_in_place")]
915struct InPlaceTypeGenerics<'a>(&'a Parameters);
916
917fn de_type_generics_to_tokens(
918    mut generics: syn::Generics,
919    borrowed: &BorrowedLifetimes,
920    tokens: &mut TokenStream,
921) {
922    if borrowed.de_lifetime_param().is_some() {
923        let def = syn::LifetimeParam {
924            attrs: Vec::new(),
925            lifetime: syn::Lifetime::new("'de", Span::call_site()),
926            colon_token: None,
927            bounds: Punctuated::new(),
928        };
929        // Prepend 'de lifetime to list of generics
930        generics.params = Some(syn::GenericParam::Lifetime(def))
931            .into_iter()
932            .chain(generics.params)
933            .collect();
934    }
935    let (_, ty_generics, _) = generics.split_for_impl();
936    ty_generics.to_tokens(tokens);
937}
938
939impl<'a> ToTokens for DeTypeGenerics<'a> {
940    fn to_tokens(&self, tokens: &mut TokenStream) {
941        de_type_generics_to_tokens(self.0.generics.clone(), &self.0.borrowed, tokens);
942    }
943}
944
945#[cfg(feature = "deserialize_in_place")]
946impl<'a> ToTokens for InPlaceTypeGenerics<'a> {
947    fn to_tokens(&self, tokens: &mut TokenStream) {
948        let mut generics = self.0.generics.clone();
949        generics.params = Some(syn::GenericParam::Lifetime(place_lifetime()))
950            .into_iter()
951            .chain(generics.params)
952            .collect();
953
954        de_type_generics_to_tokens(generics, &self.0.borrowed, tokens);
955    }
956}
957
958#[cfg(feature = "deserialize_in_place")]
959impl<'a> DeTypeGenerics<'a> {
960    fn in_place(self) -> InPlaceTypeGenerics<'a> {
961        InPlaceTypeGenerics(self.0)
962    }
963}
964
965#[cfg(feature = "deserialize_in_place")]
966fn place_lifetime() -> syn::LifetimeParam {
967    syn::LifetimeParam {
968        attrs: Vec::new(),
969        lifetime: syn::Lifetime::new("'place", Span::call_site()),
970        colon_token: None,
971        bounds: Punctuated::new(),
972    }
973}