1 | use crate::fragment::{Expr, Fragment, Match, Stmts}; |
2 | use crate::internals::ast::{Container, Data, Field, Style, Variant}; |
3 | use crate::internals::{attr, replace_receiver, ungroup, Ctxt, Derive}; |
4 | use crate::{bound, dummy, pretend, this}; |
5 | use proc_macro2::{Literal, Span, TokenStream}; |
6 | use quote::{quote, quote_spanned, ToTokens}; |
7 | use std::collections::BTreeSet; |
8 | use std::ptr; |
9 | use syn::punctuated::Punctuated; |
10 | use syn::spanned::Spanned; |
11 | use syn::{parse_quote, Ident, Index, Member}; |
12 | |
13 | pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result<TokenStream> { |
14 | replace_receiver(input); |
15 | |
16 | let ctxt = Ctxt::new(); |
17 | let cont = match Container::from_ast(&ctxt, input, Derive::Deserialize) { |
18 | Some(cont) => cont, |
19 | None => return Err(ctxt.check().unwrap_err()), |
20 | }; |
21 | precondition(&ctxt, &cont); |
22 | ctxt.check()?; |
23 | |
24 | let ident = &cont.ident; |
25 | let params = Parameters::new(&cont); |
26 | let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms); |
27 | let body = Stmts(deserialize_body(&cont, ¶ms)); |
28 | let delife = params.borrowed.de_lifetime(); |
29 | let serde = cont.attrs.serde_path(); |
30 | |
31 | let impl_block = if let Some(remote) = cont.attrs.remote() { |
32 | let vis = &input.vis; |
33 | let used = pretend::pretend_used(&cont, params.is_packed); |
34 | quote! { |
35 | impl #de_impl_generics #ident #ty_generics #where_clause { |
36 | #vis fn deserialize<__D>(__deserializer: __D) -> #serde::__private::Result<#remote #ty_generics, __D::Error> |
37 | where |
38 | __D: #serde::Deserializer<#delife>, |
39 | { |
40 | #used |
41 | #body |
42 | } |
43 | } |
44 | } |
45 | } else { |
46 | let fn_deserialize_in_place = deserialize_in_place_body(&cont, ¶ms); |
47 | |
48 | quote! { |
49 | #[automatically_derived] |
50 | impl #de_impl_generics #serde::Deserialize<#delife> for #ident #ty_generics #where_clause { |
51 | fn deserialize<__D>(__deserializer: __D) -> #serde::__private::Result<Self, __D::Error> |
52 | where |
53 | __D: #serde::Deserializer<#delife>, |
54 | { |
55 | #body |
56 | } |
57 | |
58 | #fn_deserialize_in_place |
59 | } |
60 | } |
61 | }; |
62 | |
63 | Ok(dummy::wrap_in_const( |
64 | cont.attrs.custom_serde_path(), |
65 | impl_block, |
66 | )) |
67 | } |
68 | |
69 | fn precondition(cx: &Ctxt, cont: &Container) { |
70 | precondition_sized(cx, cont); |
71 | precondition_no_de_lifetime(cx, cont); |
72 | } |
73 | |
74 | fn precondition_sized(cx: &Ctxt, cont: &Container) { |
75 | if let Data::Struct(_, fields: &Vec>) = &cont.data { |
76 | if let Some(last: &Field<'_>) = fields.last() { |
77 | if let syn::Type::Slice(_) = ungroup(last.ty) { |
78 | cx.error_spanned_by( |
79 | obj:cont.original, |
80 | msg:"cannot deserialize a dynamically sized struct" , |
81 | ); |
82 | } |
83 | } |
84 | } |
85 | } |
86 | |
87 | fn precondition_no_de_lifetime(cx: &Ctxt, cont: &Container) { |
88 | if let BorrowedLifetimes::Borrowed(_) = borrowed_lifetimes(cont) { |
89 | for param: &LifetimeParam in cont.generics.lifetimes() { |
90 | if param.lifetime.to_string() == "'de" { |
91 | cx.error_spanned_by( |
92 | ¶m.lifetime, |
93 | msg:"cannot deserialize when there is a lifetime parameter called 'de" , |
94 | ); |
95 | return; |
96 | } |
97 | } |
98 | } |
99 | } |
100 | |
101 | struct Parameters { |
102 | /// Name of the type the `derive` is on. |
103 | local: syn::Ident, |
104 | |
105 | /// Path to the type the impl is for. Either a single `Ident` for local |
106 | /// types (does not include generic parameters) or `some::remote::Path` for |
107 | /// remote types. |
108 | this_type: syn::Path, |
109 | |
110 | /// Same as `this_type` but using `::<T>` for generic parameters for use in |
111 | /// expression position. |
112 | this_value: syn::Path, |
113 | |
114 | /// Generics including any explicit and inferred bounds for the impl. |
115 | generics: syn::Generics, |
116 | |
117 | /// Lifetimes borrowed from the deserializer. These will become bounds on |
118 | /// the `'de` lifetime of the deserializer. |
119 | borrowed: BorrowedLifetimes, |
120 | |
121 | /// At least one field has a serde(getter) attribute, implying that the |
122 | /// remote type has a private field. |
123 | has_getter: bool, |
124 | |
125 | /// Type has a repr(packed) attribute. |
126 | is_packed: bool, |
127 | } |
128 | |
129 | impl Parameters { |
130 | fn new(cont: &Container) -> Self { |
131 | let local = cont.ident.clone(); |
132 | let this_type = this::this_type(cont); |
133 | let this_value = this::this_value(cont); |
134 | let borrowed = borrowed_lifetimes(cont); |
135 | let generics = build_generics(cont, &borrowed); |
136 | let has_getter = cont.data.has_getter(); |
137 | let is_packed = cont.attrs.is_packed(); |
138 | |
139 | Parameters { |
140 | local, |
141 | this_type, |
142 | this_value, |
143 | generics, |
144 | borrowed, |
145 | has_getter, |
146 | is_packed, |
147 | } |
148 | } |
149 | |
150 | /// Type name to use in error messages and `&'static str` arguments to |
151 | /// various Deserializer methods. |
152 | fn type_name(&self) -> String { |
153 | self.this_type.segments.last().unwrap().ident.to_string() |
154 | } |
155 | } |
156 | |
157 | // All the generics in the input, plus a bound `T: Deserialize` for each generic |
158 | // field type that will be deserialized by us, plus a bound `T: Default` for |
159 | // each generic field type that will be set to a default value. |
160 | fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics { |
161 | let generics = bound::without_defaults(cont.generics); |
162 | |
163 | let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound); |
164 | |
165 | let generics = |
166 | bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::de_bound); |
167 | |
168 | match cont.attrs.de_bound() { |
169 | Some(predicates) => bound::with_where_predicates(&generics, predicates), |
170 | None => { |
171 | let generics = match *cont.attrs.default() { |
172 | attr::Default::Default => bound::with_self_bound( |
173 | cont, |
174 | &generics, |
175 | &parse_quote!(_serde::__private::Default), |
176 | ), |
177 | attr::Default::None | attr::Default::Path(_) => generics, |
178 | }; |
179 | |
180 | let delife = borrowed.de_lifetime(); |
181 | let generics = bound::with_bound( |
182 | cont, |
183 | &generics, |
184 | needs_deserialize_bound, |
185 | &parse_quote!(_serde::Deserialize<#delife>), |
186 | ); |
187 | |
188 | bound::with_bound( |
189 | cont, |
190 | &generics, |
191 | requires_default, |
192 | &parse_quote!(_serde::__private::Default), |
193 | ) |
194 | } |
195 | } |
196 | } |
197 | |
198 | // Fields with a `skip_deserializing` or `deserialize_with` attribute, or which |
199 | // belong to a variant with a `skip_deserializing` or `deserialize_with` |
200 | // attribute, are not deserialized by us so we do not generate a bound. Fields |
201 | // with a `bound` attribute specify their own bound so we do not generate one. |
202 | // All other fields may need a `T: Deserialize` bound where T is the type of the |
203 | // field. |
204 | fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { |
205 | !field.skip_deserializing() |
206 | && field.deserialize_with().is_none() |
207 | && field.de_bound().is_none() |
208 | && variant.map_or(default:true, |variant: &Variant| { |
209 | !variant.skip_deserializing() |
210 | && variant.deserialize_with().is_none() |
211 | && variant.de_bound().is_none() |
212 | }) |
213 | } |
214 | |
215 | // Fields with a `default` attribute (not `default=...`), and fields with a |
216 | // `skip_deserializing` attribute that do not also have `default=...`. |
217 | fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool { |
218 | if let attr::Default::Default = *field.default() { |
219 | true |
220 | } else { |
221 | false |
222 | } |
223 | } |
224 | |
225 | enum BorrowedLifetimes { |
226 | Borrowed(BTreeSet<syn::Lifetime>), |
227 | Static, |
228 | } |
229 | |
230 | impl BorrowedLifetimes { |
231 | fn de_lifetime(&self) -> syn::Lifetime { |
232 | match *self { |
233 | BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new(symbol:"'de" , Span::call_site()), |
234 | BorrowedLifetimes::Static => syn::Lifetime::new(symbol:"'static" , Span::call_site()), |
235 | } |
236 | } |
237 | |
238 | fn de_lifetime_param(&self) -> Option<syn::LifetimeParam> { |
239 | match self { |
240 | BorrowedLifetimes::Borrowed(bounds: &BTreeSet) => Some(syn::LifetimeParam { |
241 | attrs: Vec::new(), |
242 | lifetime: syn::Lifetime::new(symbol:"'de" , Span::call_site()), |
243 | colon_token: None, |
244 | bounds: bounds.iter().cloned().collect(), |
245 | }), |
246 | BorrowedLifetimes::Static => None, |
247 | } |
248 | } |
249 | } |
250 | |
251 | // The union of lifetimes borrowed by each field of the container. |
252 | // |
253 | // These turn into bounds on the `'de` lifetime of the Deserialize impl. If |
254 | // lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is: |
255 | // |
256 | // impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c> |
257 | // |
258 | // If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant |
259 | // and we use plain `'static` instead of `'de`. |
260 | fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes { |
261 | let mut lifetimes: BTreeSet = BTreeSet::new(); |
262 | for field: &Field<'_> in cont.data.all_fields() { |
263 | if !field.attrs.skip_deserializing() { |
264 | lifetimes.extend(iter:field.attrs.borrowed_lifetimes().iter().cloned()); |
265 | } |
266 | } |
267 | if lifetimes.iter().any(|b: &Lifetime| b.to_string() == "'static" ) { |
268 | BorrowedLifetimes::Static |
269 | } else { |
270 | BorrowedLifetimes::Borrowed(lifetimes) |
271 | } |
272 | } |
273 | |
274 | fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment { |
275 | if cont.attrs.transparent() { |
276 | deserialize_transparent(cont, params) |
277 | } else if let Some(type_from) = cont.attrs.type_from() { |
278 | deserialize_from(type_from) |
279 | } else if let Some(type_try_from) = cont.attrs.type_try_from() { |
280 | deserialize_try_from(type_try_from) |
281 | } else if let attr::Identifier::No = cont.attrs.identifier() { |
282 | match &cont.data { |
283 | Data::Enum(variants) => deserialize_enum(params, variants, &cont.attrs), |
284 | Data::Struct(Style::Struct, fields) => { |
285 | deserialize_struct(params, fields, &cont.attrs, StructForm::Struct) |
286 | } |
287 | Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { |
288 | deserialize_tuple(params, fields, &cont.attrs, TupleForm::Tuple) |
289 | } |
290 | Data::Struct(Style::Unit, _) => deserialize_unit_struct(params, &cont.attrs), |
291 | } |
292 | } else { |
293 | match &cont.data { |
294 | Data::Enum(variants) => deserialize_custom_identifier(params, variants, &cont.attrs), |
295 | Data::Struct(_, _) => unreachable!("checked in serde_derive_internals" ), |
296 | } |
297 | } |
298 | } |
299 | |
300 | #[cfg (feature = "deserialize_in_place" )] |
301 | fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<Stmts> { |
302 | // Only remote derives have getters, and we do not generate |
303 | // deserialize_in_place for remote derives. |
304 | assert!(!params.has_getter); |
305 | |
306 | if cont.attrs.transparent() |
307 | || cont.attrs.type_from().is_some() |
308 | || cont.attrs.type_try_from().is_some() |
309 | || cont.attrs.identifier().is_some() |
310 | || cont |
311 | .data |
312 | .all_fields() |
313 | .all(|f| f.attrs.deserialize_with().is_some()) |
314 | { |
315 | return None; |
316 | } |
317 | |
318 | let code = match &cont.data { |
319 | Data::Struct(Style::Struct, fields) => { |
320 | deserialize_struct_in_place(params, fields, &cont.attrs)? |
321 | } |
322 | Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { |
323 | deserialize_tuple_in_place(params, fields, &cont.attrs) |
324 | } |
325 | Data::Enum(_) | Data::Struct(Style::Unit, _) => { |
326 | return None; |
327 | } |
328 | }; |
329 | |
330 | let delife = params.borrowed.de_lifetime(); |
331 | let stmts = Stmts(code); |
332 | |
333 | let fn_deserialize_in_place = quote_block! { |
334 | fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::__private::Result<(), __D::Error> |
335 | where |
336 | __D: _serde::Deserializer<#delife>, |
337 | { |
338 | #stmts |
339 | } |
340 | }; |
341 | |
342 | Some(Stmts(fn_deserialize_in_place)) |
343 | } |
344 | |
345 | #[cfg (not(feature = "deserialize_in_place" ))] |
346 | fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option<Stmts> { |
347 | None |
348 | } |
349 | |
350 | fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment { |
351 | let fields = match &cont.data { |
352 | Data::Struct(_, fields) => fields, |
353 | Data::Enum(_) => unreachable!(), |
354 | }; |
355 | |
356 | let this_value = ¶ms.this_value; |
357 | let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap(); |
358 | |
359 | let path = match transparent_field.attrs.deserialize_with() { |
360 | Some(path) => quote!(#path), |
361 | None => { |
362 | let span = transparent_field.original.span(); |
363 | quote_spanned!(span=> _serde::Deserialize::deserialize) |
364 | } |
365 | }; |
366 | |
367 | let assign = fields.iter().map(|field| { |
368 | let member = &field.member; |
369 | if ptr::eq(field, transparent_field) { |
370 | quote!(#member: __transparent) |
371 | } else { |
372 | let value = match field.attrs.default() { |
373 | attr::Default::Default => quote!(_serde::__private::Default::default()), |
374 | attr::Default::Path(path) => quote!(#path()), |
375 | attr::Default::None => quote!(_serde::__private::PhantomData), |
376 | }; |
377 | quote!(#member: #value) |
378 | } |
379 | }); |
380 | |
381 | quote_block! { |
382 | _serde::__private::Result::map( |
383 | #path(__deserializer), |
384 | |__transparent| #this_value { #(#assign),* }) |
385 | } |
386 | } |
387 | |
388 | fn deserialize_from(type_from: &syn::Type) -> Fragment { |
389 | quote_block! { |
390 | _serde::__private::Result::map( |
391 | <#type_from as _serde::Deserialize>::deserialize(__deserializer), |
392 | _serde::__private::From::from) |
393 | } |
394 | } |
395 | |
396 | fn deserialize_try_from(type_try_from: &syn::Type) -> Fragment { |
397 | quote_block! { |
398 | _serde::__private::Result::and_then( |
399 | <#type_try_from as _serde::Deserialize>::deserialize(__deserializer), |
400 | |v| _serde::__private::TryFrom::try_from(v).map_err(_serde::de::Error::custom)) |
401 | } |
402 | } |
403 | |
404 | fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fragment { |
405 | let this_type = ¶ms.this_type; |
406 | let this_value = ¶ms.this_value; |
407 | let type_name = cattrs.name().deserialize_name(); |
408 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
409 | split_with_de_lifetime(params); |
410 | let delife = params.borrowed.de_lifetime(); |
411 | |
412 | let expecting = format!("unit struct {}" , params.type_name()); |
413 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
414 | |
415 | quote_block! { |
416 | #[doc(hidden)] |
417 | struct __Visitor #de_impl_generics #where_clause { |
418 | marker: _serde::__private::PhantomData<#this_type #ty_generics>, |
419 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
420 | } |
421 | |
422 | impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { |
423 | type Value = #this_type #ty_generics; |
424 | |
425 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
426 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
427 | } |
428 | |
429 | #[inline] |
430 | fn visit_unit<__E>(self) -> _serde::__private::Result<Self::Value, __E> |
431 | where |
432 | __E: _serde::de::Error, |
433 | { |
434 | _serde::__private::Ok(#this_value) |
435 | } |
436 | } |
437 | |
438 | _serde::Deserializer::deserialize_unit_struct( |
439 | __deserializer, |
440 | #type_name, |
441 | __Visitor { |
442 | marker: _serde::__private::PhantomData::<#this_type #ty_generics>, |
443 | lifetime: _serde::__private::PhantomData, |
444 | }, |
445 | ) |
446 | } |
447 | } |
448 | |
449 | enum TupleForm<'a> { |
450 | Tuple, |
451 | /// Contains a variant name |
452 | ExternallyTagged(&'a syn::Ident), |
453 | /// Contains a variant name and an intermediate deserializer from which actual |
454 | /// deserialization will be performed |
455 | Untagged(&'a syn::Ident, TokenStream), |
456 | } |
457 | |
458 | fn deserialize_tuple( |
459 | params: &Parameters, |
460 | fields: &[Field], |
461 | cattrs: &attr::Container, |
462 | form: TupleForm, |
463 | ) -> Fragment { |
464 | assert!(!cattrs.has_flatten()); |
465 | |
466 | let field_count = fields |
467 | .iter() |
468 | .filter(|field| !field.attrs.skip_deserializing()) |
469 | .count(); |
470 | |
471 | let this_type = ¶ms.this_type; |
472 | let this_value = ¶ms.this_value; |
473 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
474 | split_with_de_lifetime(params); |
475 | let delife = params.borrowed.de_lifetime(); |
476 | |
477 | // If there are getters (implying private fields), construct the local type |
478 | // and use an `Into` conversion to get the remote type. If there are no |
479 | // getters then construct the target type directly. |
480 | let construct = if params.has_getter { |
481 | let local = ¶ms.local; |
482 | quote!(#local) |
483 | } else { |
484 | quote!(#this_value) |
485 | }; |
486 | |
487 | let type_path = match form { |
488 | TupleForm::Tuple => construct, |
489 | TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => { |
490 | quote!(#construct::#variant_ident) |
491 | } |
492 | }; |
493 | let expecting = match form { |
494 | TupleForm::Tuple => format!("tuple struct {}" , params.type_name()), |
495 | TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => { |
496 | format!("tuple variant {}:: {}" , params.type_name(), variant_ident) |
497 | } |
498 | }; |
499 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
500 | |
501 | let nfields = fields.len(); |
502 | |
503 | let visit_newtype_struct = match form { |
504 | TupleForm::Tuple if nfields == 1 => { |
505 | Some(deserialize_newtype_struct(&type_path, params, &fields[0])) |
506 | } |
507 | _ => None, |
508 | }; |
509 | |
510 | let visit_seq = Stmts(deserialize_seq( |
511 | &type_path, params, fields, false, cattrs, expecting, |
512 | )); |
513 | |
514 | let visitor_expr = quote! { |
515 | __Visitor { |
516 | marker: _serde::__private::PhantomData::<#this_type #ty_generics>, |
517 | lifetime: _serde::__private::PhantomData, |
518 | } |
519 | }; |
520 | let dispatch = match form { |
521 | TupleForm::Tuple if nfields == 1 => { |
522 | let type_name = cattrs.name().deserialize_name(); |
523 | quote! { |
524 | _serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr) |
525 | } |
526 | } |
527 | TupleForm::Tuple => { |
528 | let type_name = cattrs.name().deserialize_name(); |
529 | quote! { |
530 | _serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr) |
531 | } |
532 | } |
533 | TupleForm::ExternallyTagged(_) => quote! { |
534 | _serde::de::VariantAccess::tuple_variant(__variant, #field_count, #visitor_expr) |
535 | }, |
536 | TupleForm::Untagged(_, deserializer) => quote! { |
537 | _serde::Deserializer::deserialize_tuple(#deserializer, #field_count, #visitor_expr) |
538 | }, |
539 | }; |
540 | |
541 | let visitor_var = if field_count == 0 { |
542 | quote!(_) |
543 | } else { |
544 | quote!(mut __seq) |
545 | }; |
546 | |
547 | quote_block! { |
548 | #[doc(hidden)] |
549 | struct __Visitor #de_impl_generics #where_clause { |
550 | marker: _serde::__private::PhantomData<#this_type #ty_generics>, |
551 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
552 | } |
553 | |
554 | impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { |
555 | type Value = #this_type #ty_generics; |
556 | |
557 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
558 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
559 | } |
560 | |
561 | #visit_newtype_struct |
562 | |
563 | #[inline] |
564 | fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
565 | where |
566 | __A: _serde::de::SeqAccess<#delife>, |
567 | { |
568 | #visit_seq |
569 | } |
570 | } |
571 | |
572 | #dispatch |
573 | } |
574 | } |
575 | |
576 | #[cfg (feature = "deserialize_in_place" )] |
577 | fn deserialize_tuple_in_place( |
578 | params: &Parameters, |
579 | fields: &[Field], |
580 | cattrs: &attr::Container, |
581 | ) -> Fragment { |
582 | assert!(!cattrs.has_flatten()); |
583 | |
584 | let field_count = fields |
585 | .iter() |
586 | .filter(|field| !field.attrs.skip_deserializing()) |
587 | .count(); |
588 | |
589 | let this_type = ¶ms.this_type; |
590 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
591 | split_with_de_lifetime(params); |
592 | let delife = params.borrowed.de_lifetime(); |
593 | |
594 | let expecting = format!("tuple struct {}" , params.type_name()); |
595 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
596 | |
597 | let nfields = fields.len(); |
598 | |
599 | let visit_newtype_struct = if nfields == 1 { |
600 | // We do not generate deserialize_in_place if every field has a |
601 | // deserialize_with. |
602 | assert!(fields[0].attrs.deserialize_with().is_none()); |
603 | |
604 | Some(quote! { |
605 | #[inline] |
606 | fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::__private::Result<Self::Value, __E::Error> |
607 | where |
608 | __E: _serde::Deserializer<#delife>, |
609 | { |
610 | _serde::Deserialize::deserialize_in_place(__e, &mut self.place.0) |
611 | } |
612 | }) |
613 | } else { |
614 | None |
615 | }; |
616 | |
617 | let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); |
618 | |
619 | let visitor_expr = quote! { |
620 | __Visitor { |
621 | place: __place, |
622 | lifetime: _serde::__private::PhantomData, |
623 | } |
624 | }; |
625 | |
626 | let type_name = cattrs.name().deserialize_name(); |
627 | let dispatch = if nfields == 1 { |
628 | quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) |
629 | } else { |
630 | quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr)) |
631 | }; |
632 | |
633 | let visitor_var = if field_count == 0 { |
634 | quote!(_) |
635 | } else { |
636 | quote!(mut __seq) |
637 | }; |
638 | |
639 | let in_place_impl_generics = de_impl_generics.in_place(); |
640 | let in_place_ty_generics = de_ty_generics.in_place(); |
641 | let place_life = place_lifetime(); |
642 | |
643 | quote_block! { |
644 | #[doc(hidden)] |
645 | struct __Visitor #in_place_impl_generics #where_clause { |
646 | place: &#place_life mut #this_type #ty_generics, |
647 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
648 | } |
649 | |
650 | impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { |
651 | type Value = (); |
652 | |
653 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
654 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
655 | } |
656 | |
657 | #visit_newtype_struct |
658 | |
659 | #[inline] |
660 | fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
661 | where |
662 | __A: _serde::de::SeqAccess<#delife>, |
663 | { |
664 | #visit_seq |
665 | } |
666 | } |
667 | |
668 | #dispatch |
669 | } |
670 | } |
671 | |
672 | fn deserialize_seq( |
673 | type_path: &TokenStream, |
674 | params: &Parameters, |
675 | fields: &[Field], |
676 | is_struct: bool, |
677 | cattrs: &attr::Container, |
678 | expecting: &str, |
679 | ) -> Fragment { |
680 | let vars = (0..fields.len()).map(field_i as fn(_) -> _); |
681 | |
682 | let deserialized_count = fields |
683 | .iter() |
684 | .filter(|field| !field.attrs.skip_deserializing()) |
685 | .count(); |
686 | let expecting = if deserialized_count == 1 { |
687 | format!(" {} with 1 element" , expecting) |
688 | } else { |
689 | format!(" {} with {} elements" , expecting, deserialized_count) |
690 | }; |
691 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
692 | |
693 | let mut index_in_seq = 0_usize; |
694 | let let_values = vars.clone().zip(fields).map(|(var, field)| { |
695 | if field.attrs.skip_deserializing() { |
696 | let default = Expr(expr_is_missing(field, cattrs)); |
697 | quote! { |
698 | let #var = #default; |
699 | } |
700 | } else { |
701 | let visit = match field.attrs.deserialize_with() { |
702 | None => { |
703 | let field_ty = field.ty; |
704 | let span = field.original.span(); |
705 | let func = |
706 | quote_spanned!(span=> _serde::de::SeqAccess::next_element::<#field_ty>); |
707 | quote!(#func(&mut __seq)?) |
708 | } |
709 | Some(path) => { |
710 | let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); |
711 | quote!({ |
712 | #wrapper |
713 | _serde::__private::Option::map( |
714 | _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)?, |
715 | |__wrap| __wrap.value) |
716 | }) |
717 | } |
718 | }; |
719 | let value_if_none = expr_is_missing_seq(None, index_in_seq, field, cattrs, expecting); |
720 | let assign = quote! { |
721 | let #var = match #visit { |
722 | _serde::__private::Some(__value) => __value, |
723 | _serde::__private::None => #value_if_none, |
724 | }; |
725 | }; |
726 | index_in_seq += 1; |
727 | assign |
728 | } |
729 | }); |
730 | |
731 | let mut result = if is_struct { |
732 | let names = fields.iter().map(|f| &f.member); |
733 | quote! { |
734 | #type_path { #( #names: #vars ),* } |
735 | } |
736 | } else { |
737 | quote! { |
738 | #type_path ( #(#vars),* ) |
739 | } |
740 | }; |
741 | |
742 | if params.has_getter { |
743 | let this_type = ¶ms.this_type; |
744 | let (_, ty_generics, _) = params.generics.split_for_impl(); |
745 | result = quote! { |
746 | _serde::__private::Into::<#this_type #ty_generics>::into(#result) |
747 | }; |
748 | } |
749 | |
750 | let let_default = match cattrs.default() { |
751 | attr::Default::Default => Some(quote!( |
752 | let __default: Self::Value = _serde::__private::Default::default(); |
753 | )), |
754 | attr::Default::Path(path) => Some(quote!( |
755 | let __default: Self::Value = #path(); |
756 | )), |
757 | attr::Default::None => { |
758 | // We don't need the default value, to prevent an unused variable warning |
759 | // we'll leave the line empty. |
760 | None |
761 | } |
762 | }; |
763 | |
764 | quote_block! { |
765 | #let_default |
766 | #(#let_values)* |
767 | _serde::__private::Ok(#result) |
768 | } |
769 | } |
770 | |
771 | #[cfg (feature = "deserialize_in_place" )] |
772 | fn deserialize_seq_in_place( |
773 | params: &Parameters, |
774 | fields: &[Field], |
775 | cattrs: &attr::Container, |
776 | expecting: &str, |
777 | ) -> Fragment { |
778 | let deserialized_count = fields |
779 | .iter() |
780 | .filter(|field| !field.attrs.skip_deserializing()) |
781 | .count(); |
782 | let expecting = if deserialized_count == 1 { |
783 | format!(" {} with 1 element" , expecting) |
784 | } else { |
785 | format!(" {} with {} elements" , expecting, deserialized_count) |
786 | }; |
787 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
788 | |
789 | let mut index_in_seq = 0usize; |
790 | let write_values = fields.iter().map(|field| { |
791 | let member = &field.member; |
792 | |
793 | if field.attrs.skip_deserializing() { |
794 | let default = Expr(expr_is_missing(field, cattrs)); |
795 | quote! { |
796 | self.place.#member = #default; |
797 | } |
798 | } else { |
799 | let value_if_none = expr_is_missing_seq(Some(quote!(self.place.#member = )), index_in_seq, field, cattrs, expecting); |
800 | let write = match field.attrs.deserialize_with() { |
801 | None => { |
802 | quote! { |
803 | if let _serde::__private::None = _serde::de::SeqAccess::next_element_seed(&mut __seq, |
804 | _serde::__private::de::InPlaceSeed(&mut self.place.#member))? |
805 | { |
806 | #value_if_none; |
807 | } |
808 | } |
809 | } |
810 | Some(path) => { |
811 | let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); |
812 | quote!({ |
813 | #wrapper |
814 | match _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)? { |
815 | _serde::__private::Some(__wrap) => { |
816 | self.place.#member = __wrap.value; |
817 | } |
818 | _serde::__private::None => { |
819 | #value_if_none; |
820 | } |
821 | } |
822 | }) |
823 | } |
824 | }; |
825 | index_in_seq += 1; |
826 | write |
827 | } |
828 | }); |
829 | |
830 | let this_type = ¶ms.this_type; |
831 | let (_, ty_generics, _) = params.generics.split_for_impl(); |
832 | let let_default = match cattrs.default() { |
833 | attr::Default::Default => Some(quote!( |
834 | let __default: #this_type #ty_generics = _serde::__private::Default::default(); |
835 | )), |
836 | attr::Default::Path(path) => Some(quote!( |
837 | let __default: #this_type #ty_generics = #path(); |
838 | )), |
839 | attr::Default::None => { |
840 | // We don't need the default value, to prevent an unused variable warning |
841 | // we'll leave the line empty. |
842 | None |
843 | } |
844 | }; |
845 | |
846 | quote_block! { |
847 | #let_default |
848 | #(#write_values)* |
849 | _serde::__private::Ok(()) |
850 | } |
851 | } |
852 | |
853 | fn deserialize_newtype_struct( |
854 | type_path: &TokenStream, |
855 | params: &Parameters, |
856 | field: &Field, |
857 | ) -> TokenStream { |
858 | let delife = params.borrowed.de_lifetime(); |
859 | let field_ty = field.ty; |
860 | |
861 | let value = match field.attrs.deserialize_with() { |
862 | None => { |
863 | let span = field.original.span(); |
864 | let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); |
865 | quote! { |
866 | #func(__e)? |
867 | } |
868 | } |
869 | Some(path) => { |
870 | quote! { |
871 | #path(__e)? |
872 | } |
873 | } |
874 | }; |
875 | |
876 | let mut result = quote!(#type_path(__field0)); |
877 | if params.has_getter { |
878 | let this_type = ¶ms.this_type; |
879 | let (_, ty_generics, _) = params.generics.split_for_impl(); |
880 | result = quote! { |
881 | _serde::__private::Into::<#this_type #ty_generics>::into(#result) |
882 | }; |
883 | } |
884 | |
885 | quote! { |
886 | #[inline] |
887 | fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::__private::Result<Self::Value, __E::Error> |
888 | where |
889 | __E: _serde::Deserializer<#delife>, |
890 | { |
891 | let __field0: #field_ty = #value; |
892 | _serde::__private::Ok(#result) |
893 | } |
894 | } |
895 | } |
896 | |
897 | enum StructForm<'a> { |
898 | Struct, |
899 | /// Contains a variant name |
900 | ExternallyTagged(&'a syn::Ident), |
901 | /// Contains a variant name and an intermediate deserializer from which actual |
902 | /// deserialization will be performed |
903 | InternallyTagged(&'a syn::Ident, TokenStream), |
904 | /// Contains a variant name and an intermediate deserializer from which actual |
905 | /// deserialization will be performed |
906 | Untagged(&'a syn::Ident, TokenStream), |
907 | } |
908 | |
909 | fn deserialize_struct( |
910 | params: &Parameters, |
911 | fields: &[Field], |
912 | cattrs: &attr::Container, |
913 | form: StructForm, |
914 | ) -> Fragment { |
915 | let this_type = ¶ms.this_type; |
916 | let this_value = ¶ms.this_value; |
917 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
918 | split_with_de_lifetime(params); |
919 | let delife = params.borrowed.de_lifetime(); |
920 | |
921 | // If there are getters (implying private fields), construct the local type |
922 | // and use an `Into` conversion to get the remote type. If there are no |
923 | // getters then construct the target type directly. |
924 | let construct = if params.has_getter { |
925 | let local = ¶ms.local; |
926 | quote!(#local) |
927 | } else { |
928 | quote!(#this_value) |
929 | }; |
930 | |
931 | let type_path = match form { |
932 | StructForm::Struct => construct, |
933 | StructForm::ExternallyTagged(variant_ident) |
934 | | StructForm::InternallyTagged(variant_ident, _) |
935 | | StructForm::Untagged(variant_ident, _) => quote!(#construct::#variant_ident), |
936 | }; |
937 | let expecting = match form { |
938 | StructForm::Struct => format!("struct {}" , params.type_name()), |
939 | StructForm::ExternallyTagged(variant_ident) |
940 | | StructForm::InternallyTagged(variant_ident, _) |
941 | | StructForm::Untagged(variant_ident, _) => { |
942 | format!("struct variant {}:: {}" , params.type_name(), variant_ident) |
943 | } |
944 | }; |
945 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
946 | |
947 | let field_names_idents: Vec<_> = fields |
948 | .iter() |
949 | .enumerate() |
950 | // Skip fields that shouldn't be deserialized or that were flattened, |
951 | // so they don't appear in the storage in their literal form |
952 | .filter(|&(_, field)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) |
953 | .map(|(i, field)| { |
954 | ( |
955 | field.attrs.name().deserialize_name(), |
956 | field_i(i), |
957 | field.attrs.aliases(), |
958 | ) |
959 | }) |
960 | .collect(); |
961 | let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs); |
962 | |
963 | // untagged struct variants do not get a visit_seq method. The same applies to |
964 | // structs that only have a map representation. |
965 | let visit_seq = match form { |
966 | StructForm::Untagged(..) => None, |
967 | _ if cattrs.has_flatten() => None, |
968 | _ => { |
969 | let mut_seq = if field_names_idents.is_empty() { |
970 | quote!(_) |
971 | } else { |
972 | quote!(mut __seq) |
973 | }; |
974 | |
975 | let visit_seq = Stmts(deserialize_seq( |
976 | &type_path, params, fields, true, cattrs, expecting, |
977 | )); |
978 | |
979 | Some(quote! { |
980 | #[inline] |
981 | fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
982 | where |
983 | __A: _serde::de::SeqAccess<#delife>, |
984 | { |
985 | #visit_seq |
986 | } |
987 | }) |
988 | } |
989 | }; |
990 | let visit_map = Stmts(deserialize_map(&type_path, params, fields, cattrs)); |
991 | |
992 | let visitor_seed = match form { |
993 | StructForm::ExternallyTagged(..) if cattrs.has_flatten() => Some(quote! { |
994 | impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Visitor #de_ty_generics #where_clause { |
995 | type Value = #this_type #ty_generics; |
996 | |
997 | fn deserialize<__D>(self, __deserializer: __D) -> _serde::__private::Result<Self::Value, __D::Error> |
998 | where |
999 | __D: _serde::Deserializer<#delife>, |
1000 | { |
1001 | _serde::Deserializer::deserialize_map(__deserializer, self) |
1002 | } |
1003 | } |
1004 | }), |
1005 | _ => None, |
1006 | }; |
1007 | |
1008 | let fields_stmt = if cattrs.has_flatten() { |
1009 | None |
1010 | } else { |
1011 | let field_names = field_names_idents |
1012 | .iter() |
1013 | .flat_map(|&(_, _, aliases)| aliases); |
1014 | |
1015 | Some(quote! { |
1016 | #[doc(hidden)] |
1017 | const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; |
1018 | }) |
1019 | }; |
1020 | |
1021 | let visitor_expr = quote! { |
1022 | __Visitor { |
1023 | marker: _serde::__private::PhantomData::<#this_type #ty_generics>, |
1024 | lifetime: _serde::__private::PhantomData, |
1025 | } |
1026 | }; |
1027 | let dispatch = match form { |
1028 | StructForm::Struct if cattrs.has_flatten() => quote! { |
1029 | _serde::Deserializer::deserialize_map(__deserializer, #visitor_expr) |
1030 | }, |
1031 | StructForm::Struct => { |
1032 | let type_name = cattrs.name().deserialize_name(); |
1033 | quote! { |
1034 | _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) |
1035 | } |
1036 | } |
1037 | StructForm::ExternallyTagged(_) if cattrs.has_flatten() => quote! { |
1038 | _serde::de::VariantAccess::newtype_variant_seed(__variant, #visitor_expr) |
1039 | }, |
1040 | StructForm::ExternallyTagged(_) => quote! { |
1041 | _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) |
1042 | }, |
1043 | StructForm::InternallyTagged(_, deserializer) => quote! { |
1044 | _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) |
1045 | }, |
1046 | StructForm::Untagged(_, deserializer) => quote! { |
1047 | _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) |
1048 | }, |
1049 | }; |
1050 | |
1051 | quote_block! { |
1052 | #field_visitor |
1053 | |
1054 | #[doc(hidden)] |
1055 | struct __Visitor #de_impl_generics #where_clause { |
1056 | marker: _serde::__private::PhantomData<#this_type #ty_generics>, |
1057 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
1058 | } |
1059 | |
1060 | impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { |
1061 | type Value = #this_type #ty_generics; |
1062 | |
1063 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
1064 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
1065 | } |
1066 | |
1067 | #visit_seq |
1068 | |
1069 | #[inline] |
1070 | fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
1071 | where |
1072 | __A: _serde::de::MapAccess<#delife>, |
1073 | { |
1074 | #visit_map |
1075 | } |
1076 | } |
1077 | |
1078 | #visitor_seed |
1079 | |
1080 | #fields_stmt |
1081 | |
1082 | #dispatch |
1083 | } |
1084 | } |
1085 | |
1086 | #[cfg (feature = "deserialize_in_place" )] |
1087 | fn deserialize_struct_in_place( |
1088 | params: &Parameters, |
1089 | fields: &[Field], |
1090 | cattrs: &attr::Container, |
1091 | ) -> Option<Fragment> { |
1092 | // for now we do not support in_place deserialization for structs that |
1093 | // are represented as map. |
1094 | if cattrs.has_flatten() { |
1095 | return None; |
1096 | } |
1097 | |
1098 | let this_type = ¶ms.this_type; |
1099 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
1100 | split_with_de_lifetime(params); |
1101 | let delife = params.borrowed.de_lifetime(); |
1102 | |
1103 | let expecting = format!("struct {}" , params.type_name()); |
1104 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
1105 | |
1106 | let field_names_idents: Vec<_> = fields |
1107 | .iter() |
1108 | .enumerate() |
1109 | .filter(|&(_, field)| !field.attrs.skip_deserializing()) |
1110 | .map(|(i, field)| { |
1111 | ( |
1112 | field.attrs.name().deserialize_name(), |
1113 | field_i(i), |
1114 | field.attrs.aliases(), |
1115 | ) |
1116 | }) |
1117 | .collect(); |
1118 | |
1119 | let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs); |
1120 | |
1121 | let mut_seq = if field_names_idents.is_empty() { |
1122 | quote!(_) |
1123 | } else { |
1124 | quote!(mut __seq) |
1125 | }; |
1126 | let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); |
1127 | let visit_map = Stmts(deserialize_map_in_place(params, fields, cattrs)); |
1128 | let field_names = field_names_idents |
1129 | .iter() |
1130 | .flat_map(|&(_, _, aliases)| aliases); |
1131 | let type_name = cattrs.name().deserialize_name(); |
1132 | |
1133 | let in_place_impl_generics = de_impl_generics.in_place(); |
1134 | let in_place_ty_generics = de_ty_generics.in_place(); |
1135 | let place_life = place_lifetime(); |
1136 | |
1137 | Some(quote_block! { |
1138 | #field_visitor |
1139 | |
1140 | #[doc(hidden)] |
1141 | struct __Visitor #in_place_impl_generics #where_clause { |
1142 | place: &#place_life mut #this_type #ty_generics, |
1143 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
1144 | } |
1145 | |
1146 | impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { |
1147 | type Value = (); |
1148 | |
1149 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
1150 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
1151 | } |
1152 | |
1153 | #[inline] |
1154 | fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
1155 | where |
1156 | __A: _serde::de::SeqAccess<#delife>, |
1157 | { |
1158 | #visit_seq |
1159 | } |
1160 | |
1161 | #[inline] |
1162 | fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
1163 | where |
1164 | __A: _serde::de::MapAccess<#delife>, |
1165 | { |
1166 | #visit_map |
1167 | } |
1168 | } |
1169 | |
1170 | #[doc(hidden)] |
1171 | const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; |
1172 | |
1173 | _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, __Visitor { |
1174 | place: __place, |
1175 | lifetime: _serde::__private::PhantomData, |
1176 | }) |
1177 | }) |
1178 | } |
1179 | |
1180 | fn deserialize_enum( |
1181 | params: &Parameters, |
1182 | variants: &[Variant], |
1183 | cattrs: &attr::Container, |
1184 | ) -> Fragment { |
1185 | // The variants have already been checked (in ast.rs) that all untagged variants appear at the end |
1186 | match variants.iter().position(|var: &Variant<'_>| var.attrs.untagged()) { |
1187 | Some(variant_idx: usize) => { |
1188 | let (tagged: &[Variant<'_>], untagged: &[Variant<'_>]) = variants.split_at(mid:variant_idx); |
1189 | let tagged_frag: Expr = Expr(deserialize_homogeneous_enum(params, variants:tagged, cattrs)); |
1190 | deserialize_untagged_enum_after(params, variants:untagged, cattrs, first_attempt:Some(tagged_frag)) |
1191 | } |
1192 | None => deserialize_homogeneous_enum(params, variants, cattrs), |
1193 | } |
1194 | } |
1195 | |
1196 | fn deserialize_homogeneous_enum( |
1197 | params: &Parameters, |
1198 | variants: &[Variant], |
1199 | cattrs: &attr::Container, |
1200 | ) -> Fragment { |
1201 | match cattrs.tag() { |
1202 | attr::TagType::External => deserialize_externally_tagged_enum(params, variants, cattrs), |
1203 | attr::TagType::Internal { tag: &String } => { |
1204 | deserialize_internally_tagged_enum(params, variants, cattrs, tag) |
1205 | } |
1206 | attr::TagType::Adjacent { tag: &String, content: &String } => { |
1207 | deserialize_adjacently_tagged_enum(params, variants, cattrs, tag, content) |
1208 | } |
1209 | attr::TagType::None => deserialize_untagged_enum(params, variants, cattrs), |
1210 | } |
1211 | } |
1212 | |
1213 | fn prepare_enum_variant_enum( |
1214 | variants: &[Variant], |
1215 | cattrs: &attr::Container, |
1216 | ) -> (TokenStream, Stmts) { |
1217 | let mut deserialized_variants = variants |
1218 | .iter() |
1219 | .enumerate() |
1220 | .filter(|&(_, variant)| !variant.attrs.skip_deserializing()); |
1221 | |
1222 | let variant_names_idents: Vec<_> = deserialized_variants |
1223 | .clone() |
1224 | .map(|(i, variant)| { |
1225 | ( |
1226 | variant.attrs.name().deserialize_name(), |
1227 | field_i(i), |
1228 | variant.attrs.aliases(), |
1229 | ) |
1230 | }) |
1231 | .collect(); |
1232 | |
1233 | let fallthrough = deserialized_variants |
1234 | .position(|(_, variant)| variant.attrs.other()) |
1235 | .map(|other_idx| { |
1236 | let ignore_variant = variant_names_idents[other_idx].1.clone(); |
1237 | quote!(_serde::__private::Ok(__Field::#ignore_variant)) |
1238 | }); |
1239 | |
1240 | let variants_stmt = { |
1241 | let variant_names = variant_names_idents.iter().map(|(name, _, _)| name); |
1242 | quote! { |
1243 | #[doc(hidden)] |
1244 | const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; |
1245 | } |
1246 | }; |
1247 | |
1248 | let variant_visitor = Stmts(deserialize_generated_identifier( |
1249 | &variant_names_idents, |
1250 | cattrs, |
1251 | true, |
1252 | None, |
1253 | fallthrough, |
1254 | )); |
1255 | |
1256 | (variants_stmt, variant_visitor) |
1257 | } |
1258 | |
1259 | fn deserialize_externally_tagged_enum( |
1260 | params: &Parameters, |
1261 | variants: &[Variant], |
1262 | cattrs: &attr::Container, |
1263 | ) -> Fragment { |
1264 | let this_type = ¶ms.this_type; |
1265 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
1266 | split_with_de_lifetime(params); |
1267 | let delife = params.borrowed.de_lifetime(); |
1268 | |
1269 | let type_name = cattrs.name().deserialize_name(); |
1270 | let expecting = format!("enum {}" , params.type_name()); |
1271 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
1272 | |
1273 | let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants, cattrs); |
1274 | |
1275 | // Match arms to extract a variant from a string |
1276 | let variant_arms = variants |
1277 | .iter() |
1278 | .enumerate() |
1279 | .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) |
1280 | .map(|(i, variant)| { |
1281 | let variant_name = field_i(i); |
1282 | |
1283 | let block = Match(deserialize_externally_tagged_variant( |
1284 | params, variant, cattrs, |
1285 | )); |
1286 | |
1287 | quote! { |
1288 | (__Field::#variant_name, __variant) => #block |
1289 | } |
1290 | }); |
1291 | |
1292 | let all_skipped = variants |
1293 | .iter() |
1294 | .all(|variant| variant.attrs.skip_deserializing()); |
1295 | let match_variant = if all_skipped { |
1296 | // This is an empty enum like `enum Impossible {}` or an enum in which |
1297 | // all variants have `#[serde(skip_deserializing)]`. |
1298 | quote! { |
1299 | // FIXME: Once feature(exhaustive_patterns) is stable: |
1300 | // let _serde::__private::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data); |
1301 | // _serde::__private::Err(__err) |
1302 | _serde::__private::Result::map( |
1303 | _serde::de::EnumAccess::variant::<__Field>(__data), |
1304 | |(__impossible, _)| match __impossible {}) |
1305 | } |
1306 | } else { |
1307 | quote! { |
1308 | match _serde::de::EnumAccess::variant(__data)? { |
1309 | #(#variant_arms)* |
1310 | } |
1311 | } |
1312 | }; |
1313 | |
1314 | quote_block! { |
1315 | #variant_visitor |
1316 | |
1317 | #[doc(hidden)] |
1318 | struct __Visitor #de_impl_generics #where_clause { |
1319 | marker: _serde::__private::PhantomData<#this_type #ty_generics>, |
1320 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
1321 | } |
1322 | |
1323 | impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { |
1324 | type Value = #this_type #ty_generics; |
1325 | |
1326 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
1327 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
1328 | } |
1329 | |
1330 | fn visit_enum<__A>(self, __data: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
1331 | where |
1332 | __A: _serde::de::EnumAccess<#delife>, |
1333 | { |
1334 | #match_variant |
1335 | } |
1336 | } |
1337 | |
1338 | #variants_stmt |
1339 | |
1340 | _serde::Deserializer::deserialize_enum( |
1341 | __deserializer, |
1342 | #type_name, |
1343 | VARIANTS, |
1344 | __Visitor { |
1345 | marker: _serde::__private::PhantomData::<#this_type #ty_generics>, |
1346 | lifetime: _serde::__private::PhantomData, |
1347 | }, |
1348 | ) |
1349 | } |
1350 | } |
1351 | |
1352 | fn deserialize_internally_tagged_enum( |
1353 | params: &Parameters, |
1354 | variants: &[Variant], |
1355 | cattrs: &attr::Container, |
1356 | tag: &str, |
1357 | ) -> Fragment { |
1358 | let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants, cattrs); |
1359 | |
1360 | // Match arms to extract a variant from a string |
1361 | let variant_arms = variants |
1362 | .iter() |
1363 | .enumerate() |
1364 | .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) |
1365 | .map(|(i, variant)| { |
1366 | let variant_name = field_i(i); |
1367 | |
1368 | let block = Match(deserialize_internally_tagged_variant( |
1369 | params, |
1370 | variant, |
1371 | cattrs, |
1372 | quote!(__deserializer), |
1373 | )); |
1374 | |
1375 | quote! { |
1376 | __Field::#variant_name => #block |
1377 | } |
1378 | }); |
1379 | |
1380 | let expecting = format!("internally tagged enum {}" , params.type_name()); |
1381 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
1382 | |
1383 | quote_block! { |
1384 | #variant_visitor |
1385 | |
1386 | #variants_stmt |
1387 | |
1388 | let (__tag, __content) = _serde::Deserializer::deserialize_any( |
1389 | __deserializer, |
1390 | _serde::__private::de::TaggedContentVisitor::<__Field>::new(#tag, #expecting))?; |
1391 | let __deserializer = _serde::__private::de::ContentDeserializer::<__D::Error>::new(__content); |
1392 | |
1393 | match __tag { |
1394 | #(#variant_arms)* |
1395 | } |
1396 | } |
1397 | } |
1398 | |
1399 | fn deserialize_adjacently_tagged_enum( |
1400 | params: &Parameters, |
1401 | variants: &[Variant], |
1402 | cattrs: &attr::Container, |
1403 | tag: &str, |
1404 | content: &str, |
1405 | ) -> Fragment { |
1406 | let this_type = ¶ms.this_type; |
1407 | let this_value = ¶ms.this_value; |
1408 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
1409 | split_with_de_lifetime(params); |
1410 | let delife = params.borrowed.de_lifetime(); |
1411 | |
1412 | let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants, cattrs); |
1413 | |
1414 | let variant_arms: &Vec<_> = &variants |
1415 | .iter() |
1416 | .enumerate() |
1417 | .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) |
1418 | .map(|(i, variant)| { |
1419 | let variant_index = field_i(i); |
1420 | |
1421 | let block = Match(deserialize_untagged_variant( |
1422 | params, |
1423 | variant, |
1424 | cattrs, |
1425 | quote!(__deserializer), |
1426 | )); |
1427 | |
1428 | quote! { |
1429 | __Field::#variant_index => #block |
1430 | } |
1431 | }) |
1432 | .collect(); |
1433 | |
1434 | let rust_name = params.type_name(); |
1435 | let expecting = format!("adjacently tagged enum {}" , rust_name); |
1436 | let expecting = cattrs.expecting().unwrap_or(&expecting); |
1437 | let type_name = cattrs.name().deserialize_name(); |
1438 | let deny_unknown_fields = cattrs.deny_unknown_fields(); |
1439 | |
1440 | // If unknown fields are allowed, we pick the visitor that can step over |
1441 | // those. Otherwise we pick the visitor that fails on unknown keys. |
1442 | let field_visitor_ty = if deny_unknown_fields { |
1443 | quote! { _serde::__private::de::TagOrContentFieldVisitor } |
1444 | } else { |
1445 | quote! { _serde::__private::de::TagContentOtherFieldVisitor } |
1446 | }; |
1447 | |
1448 | let tag_or_content = quote! { |
1449 | #field_visitor_ty { |
1450 | tag: #tag, |
1451 | content: #content, |
1452 | } |
1453 | }; |
1454 | |
1455 | let variant_seed = quote! { |
1456 | _serde::__private::de::AdjacentlyTaggedEnumVariantSeed::<__Field> { |
1457 | enum_name: #rust_name, |
1458 | variants: VARIANTS, |
1459 | fields_enum: _serde::__private::PhantomData |
1460 | } |
1461 | }; |
1462 | |
1463 | let mut missing_content = quote! { |
1464 | _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#content)) |
1465 | }; |
1466 | let mut missing_content_fallthrough = quote!(); |
1467 | let missing_content_arms = variants |
1468 | .iter() |
1469 | .enumerate() |
1470 | .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) |
1471 | .filter_map(|(i, variant)| { |
1472 | let variant_index = field_i(i); |
1473 | let variant_ident = &variant.ident; |
1474 | |
1475 | let arm = match variant.style { |
1476 | Style::Unit => quote! { |
1477 | _serde::__private::Ok(#this_value::#variant_ident) |
1478 | }, |
1479 | Style::Newtype if variant.attrs.deserialize_with().is_none() => { |
1480 | let span = variant.original.span(); |
1481 | let func = quote_spanned!(span=> _serde::__private::de::missing_field); |
1482 | quote! { |
1483 | #func(#content).map(#this_value::#variant_ident) |
1484 | } |
1485 | } |
1486 | _ => { |
1487 | missing_content_fallthrough = quote!(_ => #missing_content); |
1488 | return None; |
1489 | } |
1490 | }; |
1491 | Some(quote! { |
1492 | __Field::#variant_index => #arm, |
1493 | }) |
1494 | }) |
1495 | .collect::<Vec<_>>(); |
1496 | if !missing_content_arms.is_empty() { |
1497 | missing_content = quote! { |
1498 | match __field { |
1499 | #(#missing_content_arms)* |
1500 | #missing_content_fallthrough |
1501 | } |
1502 | }; |
1503 | } |
1504 | |
1505 | // Advance the map by one key, returning early in case of error. |
1506 | let next_key = quote! { |
1507 | _serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)? |
1508 | }; |
1509 | |
1510 | let variant_from_map = quote! { |
1511 | _serde::de::MapAccess::next_value_seed(&mut __map, #variant_seed)? |
1512 | }; |
1513 | |
1514 | // When allowing unknown fields, we want to transparently step through keys |
1515 | // we don't care about until we find `tag`, `content`, or run out of keys. |
1516 | let next_relevant_key = if deny_unknown_fields { |
1517 | next_key |
1518 | } else { |
1519 | quote!({ |
1520 | let mut __rk : _serde::__private::Option<_serde::__private::de::TagOrContentField> = _serde::__private::None; |
1521 | while let _serde::__private::Some(__k) = #next_key { |
1522 | match __k { |
1523 | _serde::__private::de::TagContentOtherField::Other => { |
1524 | let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; |
1525 | continue; |
1526 | }, |
1527 | _serde::__private::de::TagContentOtherField::Tag => { |
1528 | __rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag); |
1529 | break; |
1530 | } |
1531 | _serde::__private::de::TagContentOtherField::Content => { |
1532 | __rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Content); |
1533 | break; |
1534 | } |
1535 | } |
1536 | } |
1537 | |
1538 | __rk |
1539 | }) |
1540 | }; |
1541 | |
1542 | // Step through remaining keys, looking for duplicates of previously-seen |
1543 | // keys. When unknown fields are denied, any key that isn't a duplicate will |
1544 | // at this point immediately produce an error. |
1545 | let visit_remaining_keys = quote! { |
1546 | match #next_relevant_key { |
1547 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { |
1548 | _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) |
1549 | } |
1550 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { |
1551 | _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) |
1552 | } |
1553 | _serde::__private::None => _serde::__private::Ok(__ret), |
1554 | } |
1555 | }; |
1556 | |
1557 | let finish_content_then_tag = if variant_arms.is_empty() { |
1558 | quote! { |
1559 | match #variant_from_map {} |
1560 | } |
1561 | } else { |
1562 | quote! { |
1563 | let __ret = match #variant_from_map { |
1564 | // Deserialize the buffered content now that we know the variant. |
1565 | #(#variant_arms)* |
1566 | }?; |
1567 | // Visit remaining keys, looking for duplicates. |
1568 | #visit_remaining_keys |
1569 | } |
1570 | }; |
1571 | |
1572 | quote_block! { |
1573 | #variant_visitor |
1574 | |
1575 | #variants_stmt |
1576 | |
1577 | #[doc(hidden)] |
1578 | struct __Seed #de_impl_generics #where_clause { |
1579 | field: __Field, |
1580 | marker: _serde::__private::PhantomData<#this_type #ty_generics>, |
1581 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
1582 | } |
1583 | |
1584 | impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause { |
1585 | type Value = #this_type #ty_generics; |
1586 | |
1587 | fn deserialize<__D>(self, __deserializer: __D) -> _serde::__private::Result<Self::Value, __D::Error> |
1588 | where |
1589 | __D: _serde::Deserializer<#delife>, |
1590 | { |
1591 | match self.field { |
1592 | #(#variant_arms)* |
1593 | } |
1594 | } |
1595 | } |
1596 | |
1597 | #[doc(hidden)] |
1598 | struct __Visitor #de_impl_generics #where_clause { |
1599 | marker: _serde::__private::PhantomData<#this_type #ty_generics>, |
1600 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
1601 | } |
1602 | |
1603 | impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { |
1604 | type Value = #this_type #ty_generics; |
1605 | |
1606 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
1607 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
1608 | } |
1609 | |
1610 | fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
1611 | where |
1612 | __A: _serde::de::MapAccess<#delife>, |
1613 | { |
1614 | // Visit the first relevant key. |
1615 | match #next_relevant_key { |
1616 | // First key is the tag. |
1617 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { |
1618 | // Parse the tag. |
1619 | let __field = #variant_from_map; |
1620 | // Visit the second key. |
1621 | match #next_relevant_key { |
1622 | // Second key is a duplicate of the tag. |
1623 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { |
1624 | _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) |
1625 | } |
1626 | // Second key is the content. |
1627 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { |
1628 | let __ret = _serde::de::MapAccess::next_value_seed(&mut __map, |
1629 | __Seed { |
1630 | field: __field, |
1631 | marker: _serde::__private::PhantomData, |
1632 | lifetime: _serde::__private::PhantomData, |
1633 | })?; |
1634 | // Visit remaining keys, looking for duplicates. |
1635 | #visit_remaining_keys |
1636 | } |
1637 | // There is no second key; might be okay if the we have a unit variant. |
1638 | _serde::__private::None => #missing_content |
1639 | } |
1640 | } |
1641 | // First key is the content. |
1642 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { |
1643 | // Buffer up the content. |
1644 | let __content = _serde::de::MapAccess::next_value::<_serde::__private::de::Content>(&mut __map)?; |
1645 | // Visit the second key. |
1646 | match #next_relevant_key { |
1647 | // Second key is the tag. |
1648 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { |
1649 | let __deserializer = _serde::__private::de::ContentDeserializer::<__A::Error>::new(__content); |
1650 | #finish_content_then_tag |
1651 | } |
1652 | // Second key is a duplicate of the content. |
1653 | _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { |
1654 | _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) |
1655 | } |
1656 | // There is no second key. |
1657 | _serde::__private::None => { |
1658 | _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) |
1659 | } |
1660 | } |
1661 | } |
1662 | // There is no first key. |
1663 | _serde::__private::None => { |
1664 | _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) |
1665 | } |
1666 | } |
1667 | } |
1668 | |
1669 | fn visit_seq<__A>(self, mut __seq: __A) -> _serde::__private::Result<Self::Value, __A::Error> |
1670 | where |
1671 | __A: _serde::de::SeqAccess<#delife>, |
1672 | { |
1673 | // Visit the first element - the tag. |
1674 | match _serde::de::SeqAccess::next_element(&mut __seq)? { |
1675 | _serde::__private::Some(__field) => { |
1676 | // Visit the second element - the content. |
1677 | match _serde::de::SeqAccess::next_element_seed( |
1678 | &mut __seq, |
1679 | __Seed { |
1680 | field: __field, |
1681 | marker: _serde::__private::PhantomData, |
1682 | lifetime: _serde::__private::PhantomData, |
1683 | }, |
1684 | )? { |
1685 | _serde::__private::Some(__ret) => _serde::__private::Ok(__ret), |
1686 | // There is no second element. |
1687 | _serde::__private::None => { |
1688 | _serde::__private::Err(_serde::de::Error::invalid_length(1, &self)) |
1689 | } |
1690 | } |
1691 | } |
1692 | // There is no first element. |
1693 | _serde::__private::None => { |
1694 | _serde::__private::Err(_serde::de::Error::invalid_length(0, &self)) |
1695 | } |
1696 | } |
1697 | } |
1698 | } |
1699 | |
1700 | #[doc(hidden)] |
1701 | const FIELDS: &'static [&'static str] = &[#tag, #content]; |
1702 | _serde::Deserializer::deserialize_struct( |
1703 | __deserializer, |
1704 | #type_name, |
1705 | FIELDS, |
1706 | __Visitor { |
1707 | marker: _serde::__private::PhantomData::<#this_type #ty_generics>, |
1708 | lifetime: _serde::__private::PhantomData, |
1709 | }, |
1710 | ) |
1711 | } |
1712 | } |
1713 | |
1714 | fn deserialize_untagged_enum( |
1715 | params: &Parameters, |
1716 | variants: &[Variant], |
1717 | cattrs: &attr::Container, |
1718 | ) -> Fragment { |
1719 | let first_attempt: Option = None; |
1720 | deserialize_untagged_enum_after(params, variants, cattrs, first_attempt) |
1721 | } |
1722 | |
1723 | fn deserialize_untagged_enum_after( |
1724 | params: &Parameters, |
1725 | variants: &[Variant], |
1726 | cattrs: &attr::Container, |
1727 | first_attempt: Option<Expr>, |
1728 | ) -> Fragment { |
1729 | let attempts = variants |
1730 | .iter() |
1731 | .filter(|variant| !variant.attrs.skip_deserializing()) |
1732 | .map(|variant| { |
1733 | Expr(deserialize_untagged_variant( |
1734 | params, |
1735 | variant, |
1736 | cattrs, |
1737 | quote!(__deserializer), |
1738 | )) |
1739 | }); |
1740 | // TODO this message could be better by saving the errors from the failed |
1741 | // attempts. The heuristic used by TOML was to count the number of fields |
1742 | // processed before an error, and use the error that happened after the |
1743 | // largest number of fields. I'm not sure I like that. Maybe it would be |
1744 | // better to save all the errors and combine them into one message that |
1745 | // explains why none of the variants matched. |
1746 | let fallthrough_msg = format!( |
1747 | "data did not match any variant of untagged enum {}" , |
1748 | params.type_name() |
1749 | ); |
1750 | let fallthrough_msg = cattrs.expecting().unwrap_or(&fallthrough_msg); |
1751 | |
1752 | // Ignore any error associated with non-untagged deserialization so that we |
1753 | // can fall through to the untagged variants. This may be infallible so we |
1754 | // need to provide the error type. |
1755 | let first_attempt = first_attempt.map(|expr| { |
1756 | quote! { |
1757 | if let _serde::__private::Result::<_, __D::Error>::Ok(__ok) = (|| #expr)() { |
1758 | return _serde::__private::Ok(__ok); |
1759 | } |
1760 | } |
1761 | }); |
1762 | |
1763 | quote_block! { |
1764 | let __content = <_serde::__private::de::Content as _serde::Deserialize>::deserialize(__deserializer)?; |
1765 | let __deserializer = _serde::__private::de::ContentRefDeserializer::<__D::Error>::new(&__content); |
1766 | |
1767 | #first_attempt |
1768 | |
1769 | #( |
1770 | if let _serde::__private::Ok(__ok) = #attempts { |
1771 | return _serde::__private::Ok(__ok); |
1772 | } |
1773 | )* |
1774 | |
1775 | _serde::__private::Err(_serde::de::Error::custom(#fallthrough_msg)) |
1776 | } |
1777 | } |
1778 | |
1779 | fn deserialize_externally_tagged_variant( |
1780 | params: &Parameters, |
1781 | variant: &Variant, |
1782 | cattrs: &attr::Container, |
1783 | ) -> Fragment { |
1784 | if let Some(path) = variant.attrs.deserialize_with() { |
1785 | let (wrapper, wrapper_ty, unwrap_fn) = wrap_deserialize_variant_with(params, variant, path); |
1786 | return quote_block! { |
1787 | #wrapper |
1788 | _serde::__private::Result::map( |
1789 | _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn) |
1790 | }; |
1791 | } |
1792 | |
1793 | let variant_ident = &variant.ident; |
1794 | |
1795 | match variant.style { |
1796 | Style::Unit => { |
1797 | let this_value = ¶ms.this_value; |
1798 | quote_block! { |
1799 | _serde::de::VariantAccess::unit_variant(__variant)?; |
1800 | _serde::__private::Ok(#this_value::#variant_ident) |
1801 | } |
1802 | } |
1803 | Style::Newtype => deserialize_externally_tagged_newtype_variant( |
1804 | variant_ident, |
1805 | params, |
1806 | &variant.fields[0], |
1807 | cattrs, |
1808 | ), |
1809 | Style::Tuple => deserialize_tuple( |
1810 | params, |
1811 | &variant.fields, |
1812 | cattrs, |
1813 | TupleForm::ExternallyTagged(variant_ident), |
1814 | ), |
1815 | Style::Struct => deserialize_struct( |
1816 | params, |
1817 | &variant.fields, |
1818 | cattrs, |
1819 | StructForm::ExternallyTagged(variant_ident), |
1820 | ), |
1821 | } |
1822 | } |
1823 | |
1824 | // Generates significant part of the visit_seq and visit_map bodies of visitors |
1825 | // for the variants of internally tagged enum. |
1826 | fn deserialize_internally_tagged_variant( |
1827 | params: &Parameters, |
1828 | variant: &Variant, |
1829 | cattrs: &attr::Container, |
1830 | deserializer: TokenStream, |
1831 | ) -> Fragment { |
1832 | if variant.attrs.deserialize_with().is_some() { |
1833 | return deserialize_untagged_variant(params, variant, cattrs, deserializer); |
1834 | } |
1835 | |
1836 | let variant_ident = &variant.ident; |
1837 | |
1838 | match effective_style(variant) { |
1839 | Style::Unit => { |
1840 | let this_value = ¶ms.this_value; |
1841 | let type_name = params.type_name(); |
1842 | let variant_name = variant.ident.to_string(); |
1843 | let default = variant.fields.first().map(|field| { |
1844 | let default = Expr(expr_is_missing(field, cattrs)); |
1845 | quote!((#default)) |
1846 | }); |
1847 | quote_block! { |
1848 | _serde::Deserializer::deserialize_any(#deserializer, _serde::__private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))?; |
1849 | _serde::__private::Ok(#this_value::#variant_ident #default) |
1850 | } |
1851 | } |
1852 | Style::Newtype => deserialize_untagged_newtype_variant( |
1853 | variant_ident, |
1854 | params, |
1855 | &variant.fields[0], |
1856 | &deserializer, |
1857 | ), |
1858 | Style::Struct => deserialize_struct( |
1859 | params, |
1860 | &variant.fields, |
1861 | cattrs, |
1862 | StructForm::InternallyTagged(variant_ident, deserializer), |
1863 | ), |
1864 | Style::Tuple => unreachable!("checked in serde_derive_internals" ), |
1865 | } |
1866 | } |
1867 | |
1868 | fn deserialize_untagged_variant( |
1869 | params: &Parameters, |
1870 | variant: &Variant, |
1871 | cattrs: &attr::Container, |
1872 | deserializer: TokenStream, |
1873 | ) -> Fragment { |
1874 | if let Some(path) = variant.attrs.deserialize_with() { |
1875 | let unwrap_fn = unwrap_to_variant_closure(params, variant, false); |
1876 | return quote_block! { |
1877 | _serde::__private::Result::map(#path(#deserializer), #unwrap_fn) |
1878 | }; |
1879 | } |
1880 | |
1881 | let variant_ident = &variant.ident; |
1882 | |
1883 | match effective_style(variant) { |
1884 | Style::Unit => { |
1885 | let this_value = ¶ms.this_value; |
1886 | let type_name = params.type_name(); |
1887 | let variant_name = variant.ident.to_string(); |
1888 | let default = variant.fields.first().map(|field| { |
1889 | let default = Expr(expr_is_missing(field, cattrs)); |
1890 | quote!((#default)) |
1891 | }); |
1892 | quote_expr! { |
1893 | match _serde::Deserializer::deserialize_any( |
1894 | #deserializer, |
1895 | _serde::__private::de::UntaggedUnitVisitor::new(#type_name, #variant_name) |
1896 | ) { |
1897 | _serde::__private::Ok(()) => _serde::__private::Ok(#this_value::#variant_ident #default), |
1898 | _serde::__private::Err(__err) => _serde::__private::Err(__err), |
1899 | } |
1900 | } |
1901 | } |
1902 | Style::Newtype => deserialize_untagged_newtype_variant( |
1903 | variant_ident, |
1904 | params, |
1905 | &variant.fields[0], |
1906 | &deserializer, |
1907 | ), |
1908 | Style::Tuple => deserialize_tuple( |
1909 | params, |
1910 | &variant.fields, |
1911 | cattrs, |
1912 | TupleForm::Untagged(variant_ident, deserializer), |
1913 | ), |
1914 | Style::Struct => deserialize_struct( |
1915 | params, |
1916 | &variant.fields, |
1917 | cattrs, |
1918 | StructForm::Untagged(variant_ident, deserializer), |
1919 | ), |
1920 | } |
1921 | } |
1922 | |
1923 | fn deserialize_externally_tagged_newtype_variant( |
1924 | variant_ident: &syn::Ident, |
1925 | params: &Parameters, |
1926 | field: &Field, |
1927 | cattrs: &attr::Container, |
1928 | ) -> Fragment { |
1929 | let this_value = ¶ms.this_value; |
1930 | |
1931 | if field.attrs.skip_deserializing() { |
1932 | let default = Expr(expr_is_missing(field, cattrs)); |
1933 | return quote_block! { |
1934 | _serde::de::VariantAccess::unit_variant(__variant)?; |
1935 | _serde::__private::Ok(#this_value::#variant_ident(#default)) |
1936 | }; |
1937 | } |
1938 | |
1939 | match field.attrs.deserialize_with() { |
1940 | None => { |
1941 | let field_ty = field.ty; |
1942 | let span = field.original.span(); |
1943 | let func = |
1944 | quote_spanned!(span=> _serde::de::VariantAccess::newtype_variant::<#field_ty>); |
1945 | quote_expr! { |
1946 | _serde::__private::Result::map(#func(__variant), #this_value::#variant_ident) |
1947 | } |
1948 | } |
1949 | Some(path) => { |
1950 | let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); |
1951 | quote_block! { |
1952 | #wrapper |
1953 | _serde::__private::Result::map( |
1954 | _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), |
1955 | |__wrapper| #this_value::#variant_ident(__wrapper.value)) |
1956 | } |
1957 | } |
1958 | } |
1959 | } |
1960 | |
1961 | fn deserialize_untagged_newtype_variant( |
1962 | variant_ident: &syn::Ident, |
1963 | params: &Parameters, |
1964 | field: &Field, |
1965 | deserializer: &TokenStream, |
1966 | ) -> Fragment { |
1967 | let this_value: &Path = ¶ms.this_value; |
1968 | let field_ty: &Type = field.ty; |
1969 | match field.attrs.deserialize_with() { |
1970 | None => { |
1971 | let span: Span = field.original.span(); |
1972 | let func: TokenStream = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); |
1973 | quote_expr! { |
1974 | _serde::__private::Result::map(#func(#deserializer), #this_value::#variant_ident) |
1975 | } |
1976 | } |
1977 | Some(path: &ExprPath) => { |
1978 | quote_block! { |
1979 | let __value: _serde::__private::Result<#field_ty, _> = #path(#deserializer); |
1980 | _serde::__private::Result::map(__value, #this_value::#variant_ident) |
1981 | } |
1982 | } |
1983 | } |
1984 | } |
1985 | |
1986 | fn deserialize_generated_identifier( |
1987 | fields: &[(&str, Ident, &BTreeSet<String>)], |
1988 | cattrs: &attr::Container, |
1989 | is_variant: bool, |
1990 | ignore_variant: Option<TokenStream>, |
1991 | fallthrough: Option<TokenStream>, |
1992 | ) -> Fragment { |
1993 | let this_value = quote!(__Field); |
1994 | let field_idents: &Vec<_> = &fields.iter().map(|(_, ident, _)| ident).collect(); |
1995 | |
1996 | let visitor_impl = Stmts(deserialize_identifier( |
1997 | &this_value, |
1998 | fields, |
1999 | is_variant, |
2000 | fallthrough, |
2001 | None, |
2002 | !is_variant && cattrs.has_flatten(), |
2003 | None, |
2004 | )); |
2005 | |
2006 | let lifetime = if !is_variant && cattrs.has_flatten() { |
2007 | Some(quote!(<'de>)) |
2008 | } else { |
2009 | None |
2010 | }; |
2011 | |
2012 | quote_block! { |
2013 | #[allow(non_camel_case_types)] |
2014 | #[doc(hidden)] |
2015 | enum __Field #lifetime { |
2016 | #(#field_idents,)* |
2017 | #ignore_variant |
2018 | } |
2019 | |
2020 | #[doc(hidden)] |
2021 | struct __FieldVisitor; |
2022 | |
2023 | impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { |
2024 | type Value = __Field #lifetime; |
2025 | |
2026 | #visitor_impl |
2027 | } |
2028 | |
2029 | impl<'de> _serde::Deserialize<'de> for __Field #lifetime { |
2030 | #[inline] |
2031 | fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result<Self, __D::Error> |
2032 | where |
2033 | __D: _serde::Deserializer<'de>, |
2034 | { |
2035 | _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor) |
2036 | } |
2037 | } |
2038 | } |
2039 | } |
2040 | |
2041 | /// Generates enum and its `Deserialize` implementation that represents each |
2042 | /// non-skipped field of the struct |
2043 | fn deserialize_field_identifier( |
2044 | fields: &[(&str, Ident, &BTreeSet<String>)], |
2045 | cattrs: &attr::Container, |
2046 | ) -> Stmts { |
2047 | let (ignore_variant: Option, fallthrough: Option) = if cattrs.has_flatten() { |
2048 | let ignore_variant: TokenStream = quote!(__other(_serde::__private::de::Content<'de>),); |
2049 | let fallthrough: TokenStream = quote!(_serde::__private::Ok(__Field::__other(__value))); |
2050 | (Some(ignore_variant), Some(fallthrough)) |
2051 | } else if cattrs.deny_unknown_fields() { |
2052 | (None, None) |
2053 | } else { |
2054 | let ignore_variant: TokenStream = quote!(__ignore,); |
2055 | let fallthrough: TokenStream = quote!(_serde::__private::Ok(__Field::__ignore)); |
2056 | (Some(ignore_variant), Some(fallthrough)) |
2057 | }; |
2058 | |
2059 | Stmts(deserialize_generated_identifier( |
2060 | fields, |
2061 | cattrs, |
2062 | is_variant:false, |
2063 | ignore_variant, |
2064 | fallthrough, |
2065 | )) |
2066 | } |
2067 | |
2068 | // Generates `Deserialize::deserialize` body for an enum with |
2069 | // `serde(field_identifier)` or `serde(variant_identifier)` attribute. |
2070 | fn deserialize_custom_identifier( |
2071 | params: &Parameters, |
2072 | variants: &[Variant], |
2073 | cattrs: &attr::Container, |
2074 | ) -> Fragment { |
2075 | let is_variant = match cattrs.identifier() { |
2076 | attr::Identifier::Variant => true, |
2077 | attr::Identifier::Field => false, |
2078 | attr::Identifier::No => unreachable!(), |
2079 | }; |
2080 | |
2081 | let this_type = params.this_type.to_token_stream(); |
2082 | let this_value = params.this_value.to_token_stream(); |
2083 | |
2084 | let (ordinary, fallthrough, fallthrough_borrowed) = if let Some(last) = variants.last() { |
2085 | let last_ident = &last.ident; |
2086 | if last.attrs.other() { |
2087 | // Process `serde(other)` attribute. It would always be found on the |
2088 | // last variant (checked in `check_identifier`), so all preceding |
2089 | // are ordinary variants. |
2090 | let ordinary = &variants[..variants.len() - 1]; |
2091 | let fallthrough = quote!(_serde::__private::Ok(#this_value::#last_ident)); |
2092 | (ordinary, Some(fallthrough), None) |
2093 | } else if let Style::Newtype = last.style { |
2094 | let ordinary = &variants[..variants.len() - 1]; |
2095 | let fallthrough = |value| { |
2096 | quote! { |
2097 | _serde::__private::Result::map( |
2098 | _serde::Deserialize::deserialize( |
2099 | _serde::__private::de::IdentifierDeserializer::from(#value) |
2100 | ), |
2101 | #this_value::#last_ident) |
2102 | } |
2103 | }; |
2104 | ( |
2105 | ordinary, |
2106 | Some(fallthrough(quote!(__value))), |
2107 | Some(fallthrough(quote!(_serde::__private::de::Borrowed( |
2108 | __value |
2109 | )))), |
2110 | ) |
2111 | } else { |
2112 | (variants, None, None) |
2113 | } |
2114 | } else { |
2115 | (variants, None, None) |
2116 | }; |
2117 | |
2118 | let names_idents: Vec<_> = ordinary |
2119 | .iter() |
2120 | .map(|variant| { |
2121 | ( |
2122 | variant.attrs.name().deserialize_name(), |
2123 | variant.ident.clone(), |
2124 | variant.attrs.aliases(), |
2125 | ) |
2126 | }) |
2127 | .collect(); |
2128 | |
2129 | let names = names_idents.iter().flat_map(|&(_, _, aliases)| aliases); |
2130 | |
2131 | let names_const = if fallthrough.is_some() { |
2132 | None |
2133 | } else if is_variant { |
2134 | let variants = quote! { |
2135 | #[doc(hidden)] |
2136 | const VARIANTS: &'static [&'static str] = &[ #(#names),* ]; |
2137 | }; |
2138 | Some(variants) |
2139 | } else { |
2140 | let fields = quote! { |
2141 | #[doc(hidden)] |
2142 | const FIELDS: &'static [&'static str] = &[ #(#names),* ]; |
2143 | }; |
2144 | Some(fields) |
2145 | }; |
2146 | |
2147 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
2148 | split_with_de_lifetime(params); |
2149 | let delife = params.borrowed.de_lifetime(); |
2150 | let visitor_impl = Stmts(deserialize_identifier( |
2151 | &this_value, |
2152 | &names_idents, |
2153 | is_variant, |
2154 | fallthrough, |
2155 | fallthrough_borrowed, |
2156 | false, |
2157 | cattrs.expecting(), |
2158 | )); |
2159 | |
2160 | quote_block! { |
2161 | #names_const |
2162 | |
2163 | #[doc(hidden)] |
2164 | struct __FieldVisitor #de_impl_generics #where_clause { |
2165 | marker: _serde::__private::PhantomData<#this_type #ty_generics>, |
2166 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
2167 | } |
2168 | |
2169 | impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause { |
2170 | type Value = #this_type #ty_generics; |
2171 | |
2172 | #visitor_impl |
2173 | } |
2174 | |
2175 | let __visitor = __FieldVisitor { |
2176 | marker: _serde::__private::PhantomData::<#this_type #ty_generics>, |
2177 | lifetime: _serde::__private::PhantomData, |
2178 | }; |
2179 | _serde::Deserializer::deserialize_identifier(__deserializer, __visitor) |
2180 | } |
2181 | } |
2182 | |
2183 | fn deserialize_identifier( |
2184 | this_value: &TokenStream, |
2185 | fields: &[(&str, Ident, &BTreeSet<String>)], |
2186 | is_variant: bool, |
2187 | fallthrough: Option<TokenStream>, |
2188 | fallthrough_borrowed: Option<TokenStream>, |
2189 | collect_other_fields: bool, |
2190 | expecting: Option<&str>, |
2191 | ) -> Fragment { |
2192 | let str_mapping = fields.iter().map(|(_, ident, aliases)| { |
2193 | // `aliases` also contains a main name |
2194 | quote!(#(#aliases)|* => _serde::__private::Ok(#this_value::#ident)) |
2195 | }); |
2196 | let bytes_mapping = fields.iter().map(|(_, ident, aliases)| { |
2197 | // `aliases` also contains a main name |
2198 | let aliases = aliases |
2199 | .iter() |
2200 | .map(|alias| Literal::byte_string(alias.as_bytes())); |
2201 | quote!(#(#aliases)|* => _serde::__private::Ok(#this_value::#ident)) |
2202 | }); |
2203 | |
2204 | let expecting = expecting.unwrap_or(if is_variant { |
2205 | "variant identifier" |
2206 | } else { |
2207 | "field identifier" |
2208 | }); |
2209 | |
2210 | let bytes_to_str = if fallthrough.is_some() || collect_other_fields { |
2211 | None |
2212 | } else { |
2213 | Some(quote! { |
2214 | let __value = &_serde::__private::from_utf8_lossy(__value); |
2215 | }) |
2216 | }; |
2217 | |
2218 | let ( |
2219 | value_as_str_content, |
2220 | value_as_borrowed_str_content, |
2221 | value_as_bytes_content, |
2222 | value_as_borrowed_bytes_content, |
2223 | ) = if collect_other_fields { |
2224 | ( |
2225 | Some(quote! { |
2226 | let __value = _serde::__private::de::Content::String(_serde::__private::ToString::to_string(__value)); |
2227 | }), |
2228 | Some(quote! { |
2229 | let __value = _serde::__private::de::Content::Str(__value); |
2230 | }), |
2231 | Some(quote! { |
2232 | let __value = _serde::__private::de::Content::ByteBuf(__value.to_vec()); |
2233 | }), |
2234 | Some(quote! { |
2235 | let __value = _serde::__private::de::Content::Bytes(__value); |
2236 | }), |
2237 | ) |
2238 | } else { |
2239 | (None, None, None, None) |
2240 | }; |
2241 | |
2242 | let fallthrough_arm_tokens; |
2243 | let fallthrough_arm = if let Some(fallthrough) = &fallthrough { |
2244 | fallthrough |
2245 | } else if is_variant { |
2246 | fallthrough_arm_tokens = quote! { |
2247 | _serde::__private::Err(_serde::de::Error::unknown_variant(__value, VARIANTS)) |
2248 | }; |
2249 | &fallthrough_arm_tokens |
2250 | } else { |
2251 | fallthrough_arm_tokens = quote! { |
2252 | _serde::__private::Err(_serde::de::Error::unknown_field(__value, FIELDS)) |
2253 | }; |
2254 | &fallthrough_arm_tokens |
2255 | }; |
2256 | |
2257 | let visit_other = if collect_other_fields { |
2258 | quote! { |
2259 | fn visit_bool<__E>(self, __value: bool) -> _serde::__private::Result<Self::Value, __E> |
2260 | where |
2261 | __E: _serde::de::Error, |
2262 | { |
2263 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Bool(__value))) |
2264 | } |
2265 | |
2266 | fn visit_i8<__E>(self, __value: i8) -> _serde::__private::Result<Self::Value, __E> |
2267 | where |
2268 | __E: _serde::de::Error, |
2269 | { |
2270 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I8(__value))) |
2271 | } |
2272 | |
2273 | fn visit_i16<__E>(self, __value: i16) -> _serde::__private::Result<Self::Value, __E> |
2274 | where |
2275 | __E: _serde::de::Error, |
2276 | { |
2277 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I16(__value))) |
2278 | } |
2279 | |
2280 | fn visit_i32<__E>(self, __value: i32) -> _serde::__private::Result<Self::Value, __E> |
2281 | where |
2282 | __E: _serde::de::Error, |
2283 | { |
2284 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I32(__value))) |
2285 | } |
2286 | |
2287 | fn visit_i64<__E>(self, __value: i64) -> _serde::__private::Result<Self::Value, __E> |
2288 | where |
2289 | __E: _serde::de::Error, |
2290 | { |
2291 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I64(__value))) |
2292 | } |
2293 | |
2294 | fn visit_u8<__E>(self, __value: u8) -> _serde::__private::Result<Self::Value, __E> |
2295 | where |
2296 | __E: _serde::de::Error, |
2297 | { |
2298 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U8(__value))) |
2299 | } |
2300 | |
2301 | fn visit_u16<__E>(self, __value: u16) -> _serde::__private::Result<Self::Value, __E> |
2302 | where |
2303 | __E: _serde::de::Error, |
2304 | { |
2305 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U16(__value))) |
2306 | } |
2307 | |
2308 | fn visit_u32<__E>(self, __value: u32) -> _serde::__private::Result<Self::Value, __E> |
2309 | where |
2310 | __E: _serde::de::Error, |
2311 | { |
2312 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U32(__value))) |
2313 | } |
2314 | |
2315 | fn visit_u64<__E>(self, __value: u64) -> _serde::__private::Result<Self::Value, __E> |
2316 | where |
2317 | __E: _serde::de::Error, |
2318 | { |
2319 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U64(__value))) |
2320 | } |
2321 | |
2322 | fn visit_f32<__E>(self, __value: f32) -> _serde::__private::Result<Self::Value, __E> |
2323 | where |
2324 | __E: _serde::de::Error, |
2325 | { |
2326 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::F32(__value))) |
2327 | } |
2328 | |
2329 | fn visit_f64<__E>(self, __value: f64) -> _serde::__private::Result<Self::Value, __E> |
2330 | where |
2331 | __E: _serde::de::Error, |
2332 | { |
2333 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::F64(__value))) |
2334 | } |
2335 | |
2336 | fn visit_char<__E>(self, __value: char) -> _serde::__private::Result<Self::Value, __E> |
2337 | where |
2338 | __E: _serde::de::Error, |
2339 | { |
2340 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Char(__value))) |
2341 | } |
2342 | |
2343 | fn visit_unit<__E>(self) -> _serde::__private::Result<Self::Value, __E> |
2344 | where |
2345 | __E: _serde::de::Error, |
2346 | { |
2347 | _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Unit)) |
2348 | } |
2349 | } |
2350 | } else { |
2351 | let u64_mapping = fields.iter().enumerate().map(|(i, (_, ident, _))| { |
2352 | let i = i as u64; |
2353 | quote!(#i => _serde::__private::Ok(#this_value::#ident)) |
2354 | }); |
2355 | |
2356 | let u64_fallthrough_arm_tokens; |
2357 | let u64_fallthrough_arm = if let Some(fallthrough) = &fallthrough { |
2358 | fallthrough |
2359 | } else { |
2360 | let index_expecting = if is_variant { "variant" } else { "field" }; |
2361 | let fallthrough_msg = format!(" {} index 0 <= i < {}" , index_expecting, fields.len()); |
2362 | u64_fallthrough_arm_tokens = quote! { |
2363 | _serde::__private::Err(_serde::de::Error::invalid_value( |
2364 | _serde::de::Unexpected::Unsigned(__value), |
2365 | &#fallthrough_msg, |
2366 | )) |
2367 | }; |
2368 | &u64_fallthrough_arm_tokens |
2369 | }; |
2370 | |
2371 | quote! { |
2372 | fn visit_u64<__E>(self, __value: u64) -> _serde::__private::Result<Self::Value, __E> |
2373 | where |
2374 | __E: _serde::de::Error, |
2375 | { |
2376 | match __value { |
2377 | #(#u64_mapping,)* |
2378 | _ => #u64_fallthrough_arm, |
2379 | } |
2380 | } |
2381 | } |
2382 | }; |
2383 | |
2384 | let visit_borrowed = if fallthrough_borrowed.is_some() || collect_other_fields { |
2385 | let str_mapping = str_mapping.clone(); |
2386 | let bytes_mapping = bytes_mapping.clone(); |
2387 | let fallthrough_borrowed_arm = fallthrough_borrowed.as_ref().unwrap_or(fallthrough_arm); |
2388 | Some(quote! { |
2389 | fn visit_borrowed_str<__E>(self, __value: &'de str) -> _serde::__private::Result<Self::Value, __E> |
2390 | where |
2391 | __E: _serde::de::Error, |
2392 | { |
2393 | match __value { |
2394 | #(#str_mapping,)* |
2395 | _ => { |
2396 | #value_as_borrowed_str_content |
2397 | #fallthrough_borrowed_arm |
2398 | } |
2399 | } |
2400 | } |
2401 | |
2402 | fn visit_borrowed_bytes<__E>(self, __value: &'de [u8]) -> _serde::__private::Result<Self::Value, __E> |
2403 | where |
2404 | __E: _serde::de::Error, |
2405 | { |
2406 | match __value { |
2407 | #(#bytes_mapping,)* |
2408 | _ => { |
2409 | #bytes_to_str |
2410 | #value_as_borrowed_bytes_content |
2411 | #fallthrough_borrowed_arm |
2412 | } |
2413 | } |
2414 | } |
2415 | }) |
2416 | } else { |
2417 | None |
2418 | }; |
2419 | |
2420 | quote_block! { |
2421 | fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { |
2422 | _serde::__private::Formatter::write_str(__formatter, #expecting) |
2423 | } |
2424 | |
2425 | #visit_other |
2426 | |
2427 | fn visit_str<__E>(self, __value: &str) -> _serde::__private::Result<Self::Value, __E> |
2428 | where |
2429 | __E: _serde::de::Error, |
2430 | { |
2431 | match __value { |
2432 | #(#str_mapping,)* |
2433 | _ => { |
2434 | #value_as_str_content |
2435 | #fallthrough_arm |
2436 | } |
2437 | } |
2438 | } |
2439 | |
2440 | fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::__private::Result<Self::Value, __E> |
2441 | where |
2442 | __E: _serde::de::Error, |
2443 | { |
2444 | match __value { |
2445 | #(#bytes_mapping,)* |
2446 | _ => { |
2447 | #bytes_to_str |
2448 | #value_as_bytes_content |
2449 | #fallthrough_arm |
2450 | } |
2451 | } |
2452 | } |
2453 | |
2454 | #visit_borrowed |
2455 | } |
2456 | } |
2457 | |
2458 | fn deserialize_map( |
2459 | struct_path: &TokenStream, |
2460 | params: &Parameters, |
2461 | fields: &[Field], |
2462 | cattrs: &attr::Container, |
2463 | ) -> Fragment { |
2464 | // Create the field names for the fields. |
2465 | let fields_names: Vec<_> = fields |
2466 | .iter() |
2467 | .enumerate() |
2468 | .map(|(i, field)| (field, field_i(i))) |
2469 | .collect(); |
2470 | |
2471 | // Declare each field that will be deserialized. |
2472 | let let_values = fields_names |
2473 | .iter() |
2474 | .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) |
2475 | .map(|(field, name)| { |
2476 | let field_ty = field.ty; |
2477 | quote! { |
2478 | let mut #name: _serde::__private::Option<#field_ty> = _serde::__private::None; |
2479 | } |
2480 | }); |
2481 | |
2482 | // Collect contents for flatten fields into a buffer |
2483 | let let_collect = if cattrs.has_flatten() { |
2484 | Some(quote! { |
2485 | let mut __collect = _serde::__private::Vec::<_serde::__private::Option<( |
2486 | _serde::__private::de::Content, |
2487 | _serde::__private::de::Content |
2488 | )>>::new(); |
2489 | }) |
2490 | } else { |
2491 | None |
2492 | }; |
2493 | |
2494 | // Match arms to extract a value for a field. |
2495 | let value_arms = fields_names |
2496 | .iter() |
2497 | .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) |
2498 | .map(|(field, name)| { |
2499 | let deser_name = field.attrs.name().deserialize_name(); |
2500 | |
2501 | let visit = match field.attrs.deserialize_with() { |
2502 | None => { |
2503 | let field_ty = field.ty; |
2504 | let span = field.original.span(); |
2505 | let func = |
2506 | quote_spanned!(span=> _serde::de::MapAccess::next_value::<#field_ty>); |
2507 | quote! { |
2508 | #func(&mut __map)? |
2509 | } |
2510 | } |
2511 | Some(path) => { |
2512 | let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); |
2513 | quote!({ |
2514 | #wrapper |
2515 | match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { |
2516 | _serde::__private::Ok(__wrapper) => __wrapper.value, |
2517 | _serde::__private::Err(__err) => { |
2518 | return _serde::__private::Err(__err); |
2519 | } |
2520 | } |
2521 | }) |
2522 | } |
2523 | }; |
2524 | quote! { |
2525 | __Field::#name => { |
2526 | if _serde::__private::Option::is_some(&#name) { |
2527 | return _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); |
2528 | } |
2529 | #name = _serde::__private::Some(#visit); |
2530 | } |
2531 | } |
2532 | }); |
2533 | |
2534 | // Visit ignored values to consume them |
2535 | let ignored_arm = if cattrs.has_flatten() { |
2536 | Some(quote! { |
2537 | __Field::__other(__name) => { |
2538 | __collect.push(_serde::__private::Some(( |
2539 | __name, |
2540 | _serde::de::MapAccess::next_value(&mut __map)?))); |
2541 | } |
2542 | }) |
2543 | } else if cattrs.deny_unknown_fields() { |
2544 | None |
2545 | } else { |
2546 | Some(quote! { |
2547 | _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } |
2548 | }) |
2549 | }; |
2550 | |
2551 | let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); |
2552 | let match_keys = if cattrs.deny_unknown_fields() && all_skipped { |
2553 | quote! { |
2554 | // FIXME: Once feature(exhaustive_patterns) is stable: |
2555 | // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; |
2556 | _serde::__private::Option::map( |
2557 | _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, |
2558 | |__impossible| match __impossible {}); |
2559 | } |
2560 | } else { |
2561 | quote! { |
2562 | while let _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { |
2563 | match __key { |
2564 | #(#value_arms)* |
2565 | #ignored_arm |
2566 | } |
2567 | } |
2568 | } |
2569 | }; |
2570 | |
2571 | let extract_values = fields_names |
2572 | .iter() |
2573 | .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) |
2574 | .map(|(field, name)| { |
2575 | let missing_expr = Match(expr_is_missing(field, cattrs)); |
2576 | |
2577 | quote! { |
2578 | let #name = match #name { |
2579 | _serde::__private::Some(#name) => #name, |
2580 | _serde::__private::None => #missing_expr |
2581 | }; |
2582 | } |
2583 | }); |
2584 | |
2585 | let extract_collected = fields_names |
2586 | .iter() |
2587 | .filter(|&&(field, _)| field.attrs.flatten() && !field.attrs.skip_deserializing()) |
2588 | .map(|(field, name)| { |
2589 | let field_ty = field.ty; |
2590 | let func = match field.attrs.deserialize_with() { |
2591 | None => { |
2592 | let span = field.original.span(); |
2593 | quote_spanned!(span=> _serde::de::Deserialize::deserialize) |
2594 | } |
2595 | Some(path) => quote!(#path), |
2596 | }; |
2597 | quote! { |
2598 | let #name: #field_ty = #func( |
2599 | _serde::__private::de::FlatMapDeserializer( |
2600 | &mut __collect, |
2601 | _serde::__private::PhantomData))?; |
2602 | } |
2603 | }); |
2604 | |
2605 | let collected_deny_unknown_fields = if cattrs.has_flatten() && cattrs.deny_unknown_fields() { |
2606 | Some(quote! { |
2607 | if let _serde::__private::Some(_serde::__private::Some((__key, _))) = |
2608 | __collect.into_iter().filter(_serde::__private::Option::is_some).next() |
2609 | { |
2610 | if let _serde::__private::Some(__key) = __key.as_str() { |
2611 | return _serde::__private::Err( |
2612 | _serde::de::Error::custom(format_args!("unknown field `{}`" , &__key))); |
2613 | } else { |
2614 | return _serde::__private::Err( |
2615 | _serde::de::Error::custom(format_args!("unexpected map key" ))); |
2616 | } |
2617 | } |
2618 | }) |
2619 | } else { |
2620 | None |
2621 | }; |
2622 | |
2623 | let result = fields_names.iter().map(|(field, name)| { |
2624 | let member = &field.member; |
2625 | if field.attrs.skip_deserializing() { |
2626 | let value = Expr(expr_is_missing(field, cattrs)); |
2627 | quote!(#member: #value) |
2628 | } else { |
2629 | quote!(#member: #name) |
2630 | } |
2631 | }); |
2632 | |
2633 | let let_default = match cattrs.default() { |
2634 | attr::Default::Default => Some(quote!( |
2635 | let __default: Self::Value = _serde::__private::Default::default(); |
2636 | )), |
2637 | attr::Default::Path(path) => Some(quote!( |
2638 | let __default: Self::Value = #path(); |
2639 | )), |
2640 | attr::Default::None => { |
2641 | // We don't need the default value, to prevent an unused variable warning |
2642 | // we'll leave the line empty. |
2643 | None |
2644 | } |
2645 | }; |
2646 | |
2647 | let mut result = quote!(#struct_path { #(#result),* }); |
2648 | if params.has_getter { |
2649 | let this_type = ¶ms.this_type; |
2650 | let (_, ty_generics, _) = params.generics.split_for_impl(); |
2651 | result = quote! { |
2652 | _serde::__private::Into::<#this_type #ty_generics>::into(#result) |
2653 | }; |
2654 | } |
2655 | |
2656 | quote_block! { |
2657 | #(#let_values)* |
2658 | |
2659 | #let_collect |
2660 | |
2661 | #match_keys |
2662 | |
2663 | #let_default |
2664 | |
2665 | #(#extract_values)* |
2666 | |
2667 | #(#extract_collected)* |
2668 | |
2669 | #collected_deny_unknown_fields |
2670 | |
2671 | _serde::__private::Ok(#result) |
2672 | } |
2673 | } |
2674 | |
2675 | #[cfg (feature = "deserialize_in_place" )] |
2676 | fn deserialize_map_in_place( |
2677 | params: &Parameters, |
2678 | fields: &[Field], |
2679 | cattrs: &attr::Container, |
2680 | ) -> Fragment { |
2681 | assert!(!cattrs.has_flatten()); |
2682 | |
2683 | // Create the field names for the fields. |
2684 | let fields_names: Vec<_> = fields |
2685 | .iter() |
2686 | .enumerate() |
2687 | .map(|(i, field)| (field, field_i(i))) |
2688 | .collect(); |
2689 | |
2690 | // For deserialize_in_place, declare booleans for each field that will be |
2691 | // deserialized. |
2692 | let let_flags = fields_names |
2693 | .iter() |
2694 | .filter(|&&(field, _)| !field.attrs.skip_deserializing()) |
2695 | .map(|(_, name)| { |
2696 | quote! { |
2697 | let mut #name: bool = false; |
2698 | } |
2699 | }); |
2700 | |
2701 | // Match arms to extract a value for a field. |
2702 | let value_arms_from = fields_names |
2703 | .iter() |
2704 | .filter(|&&(field, _)| !field.attrs.skip_deserializing()) |
2705 | .map(|(field, name)| { |
2706 | let deser_name = field.attrs.name().deserialize_name(); |
2707 | let member = &field.member; |
2708 | |
2709 | let visit = match field.attrs.deserialize_with() { |
2710 | None => { |
2711 | quote! { |
2712 | _serde::de::MapAccess::next_value_seed(&mut __map, _serde::__private::de::InPlaceSeed(&mut self.place.#member))? |
2713 | } |
2714 | } |
2715 | Some(path) => { |
2716 | let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); |
2717 | quote!({ |
2718 | #wrapper |
2719 | self.place.#member = match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { |
2720 | _serde::__private::Ok(__wrapper) => __wrapper.value, |
2721 | _serde::__private::Err(__err) => { |
2722 | return _serde::__private::Err(__err); |
2723 | } |
2724 | }; |
2725 | }) |
2726 | } |
2727 | }; |
2728 | quote! { |
2729 | __Field::#name => { |
2730 | if #name { |
2731 | return _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); |
2732 | } |
2733 | #visit; |
2734 | #name = true; |
2735 | } |
2736 | } |
2737 | }); |
2738 | |
2739 | // Visit ignored values to consume them |
2740 | let ignored_arm = if cattrs.deny_unknown_fields() { |
2741 | None |
2742 | } else { |
2743 | Some(quote! { |
2744 | _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } |
2745 | }) |
2746 | }; |
2747 | |
2748 | let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); |
2749 | |
2750 | let match_keys = if cattrs.deny_unknown_fields() && all_skipped { |
2751 | quote! { |
2752 | // FIXME: Once feature(exhaustive_patterns) is stable: |
2753 | // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; |
2754 | _serde::__private::Option::map( |
2755 | _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, |
2756 | |__impossible| match __impossible {}); |
2757 | } |
2758 | } else { |
2759 | quote! { |
2760 | while let _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { |
2761 | match __key { |
2762 | #(#value_arms_from)* |
2763 | #ignored_arm |
2764 | } |
2765 | } |
2766 | } |
2767 | }; |
2768 | |
2769 | let check_flags = fields_names |
2770 | .iter() |
2771 | .filter(|&&(field, _)| !field.attrs.skip_deserializing()) |
2772 | .map(|(field, name)| { |
2773 | let missing_expr = expr_is_missing(field, cattrs); |
2774 | // If missing_expr unconditionally returns an error, don't try |
2775 | // to assign its value to self.place. |
2776 | if field.attrs.default().is_none() |
2777 | && cattrs.default().is_none() |
2778 | && field.attrs.deserialize_with().is_some() |
2779 | { |
2780 | let missing_expr = Stmts(missing_expr); |
2781 | quote! { |
2782 | if !#name { |
2783 | #missing_expr; |
2784 | } |
2785 | } |
2786 | } else { |
2787 | let member = &field.member; |
2788 | let missing_expr = Expr(missing_expr); |
2789 | quote! { |
2790 | if !#name { |
2791 | self.place.#member = #missing_expr; |
2792 | }; |
2793 | } |
2794 | } |
2795 | }); |
2796 | |
2797 | let this_type = ¶ms.this_type; |
2798 | let (_, _, ty_generics, _) = split_with_de_lifetime(params); |
2799 | |
2800 | let let_default = match cattrs.default() { |
2801 | attr::Default::Default => Some(quote!( |
2802 | let __default: #this_type #ty_generics = _serde::__private::Default::default(); |
2803 | )), |
2804 | attr::Default::Path(path) => Some(quote!( |
2805 | let __default: #this_type #ty_generics = #path(); |
2806 | )), |
2807 | attr::Default::None => { |
2808 | // We don't need the default value, to prevent an unused variable warning |
2809 | // we'll leave the line empty. |
2810 | None |
2811 | } |
2812 | }; |
2813 | |
2814 | quote_block! { |
2815 | #(#let_flags)* |
2816 | |
2817 | #match_keys |
2818 | |
2819 | #let_default |
2820 | |
2821 | #(#check_flags)* |
2822 | |
2823 | _serde::__private::Ok(()) |
2824 | } |
2825 | } |
2826 | |
2827 | fn field_i(i: usize) -> Ident { |
2828 | Ident::new(&format!("__field {}" , i), Span::call_site()) |
2829 | } |
2830 | |
2831 | /// This function wraps the expression in `#[serde(deserialize_with = "...")]` |
2832 | /// in a trait to prevent it from accessing the internal `Deserialize` state. |
2833 | fn wrap_deserialize_with( |
2834 | params: &Parameters, |
2835 | value_ty: &TokenStream, |
2836 | deserialize_with: &syn::ExprPath, |
2837 | ) -> (TokenStream, TokenStream) { |
2838 | let this_type = ¶ms.this_type; |
2839 | let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
2840 | split_with_de_lifetime(params); |
2841 | let delife = params.borrowed.de_lifetime(); |
2842 | |
2843 | let wrapper = quote! { |
2844 | #[doc(hidden)] |
2845 | struct __DeserializeWith #de_impl_generics #where_clause { |
2846 | value: #value_ty, |
2847 | phantom: _serde::__private::PhantomData<#this_type #ty_generics>, |
2848 | lifetime: _serde::__private::PhantomData<&#delife ()>, |
2849 | } |
2850 | |
2851 | impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause { |
2852 | fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result<Self, __D::Error> |
2853 | where |
2854 | __D: _serde::Deserializer<#delife>, |
2855 | { |
2856 | _serde::__private::Ok(__DeserializeWith { |
2857 | value: #deserialize_with(__deserializer)?, |
2858 | phantom: _serde::__private::PhantomData, |
2859 | lifetime: _serde::__private::PhantomData, |
2860 | }) |
2861 | } |
2862 | } |
2863 | }; |
2864 | |
2865 | let wrapper_ty = quote!(__DeserializeWith #de_ty_generics); |
2866 | |
2867 | (wrapper, wrapper_ty) |
2868 | } |
2869 | |
2870 | fn wrap_deserialize_field_with( |
2871 | params: &Parameters, |
2872 | field_ty: &syn::Type, |
2873 | deserialize_with: &syn::ExprPath, |
2874 | ) -> (TokenStream, TokenStream) { |
2875 | wrap_deserialize_with(params, "e!(#field_ty), deserialize_with) |
2876 | } |
2877 | |
2878 | fn wrap_deserialize_variant_with( |
2879 | params: &Parameters, |
2880 | variant: &Variant, |
2881 | deserialize_with: &syn::ExprPath, |
2882 | ) -> (TokenStream, TokenStream, TokenStream) { |
2883 | let field_tys: impl Iterator = variant.fields.iter().map(|field: &Field<'_>| field.ty); |
2884 | let (wrapper: TokenStream, wrapper_ty: TokenStream) = |
2885 | wrap_deserialize_with(params, "e!((#(#field_tys),*)), deserialize_with); |
2886 | |
2887 | let unwrap_fn: TokenStream = unwrap_to_variant_closure(params, variant, with_wrapper:true); |
2888 | |
2889 | (wrapper, wrapper_ty, unwrap_fn) |
2890 | } |
2891 | |
2892 | // Generates closure that converts single input parameter to the final value. |
2893 | fn unwrap_to_variant_closure( |
2894 | params: &Parameters, |
2895 | variant: &Variant, |
2896 | with_wrapper: bool, |
2897 | ) -> TokenStream { |
2898 | let this_value = ¶ms.this_value; |
2899 | let variant_ident = &variant.ident; |
2900 | |
2901 | let (arg, wrapper) = if with_wrapper { |
2902 | (quote! { __wrap }, quote! { __wrap.value }) |
2903 | } else { |
2904 | let field_tys = variant.fields.iter().map(|field| field.ty); |
2905 | (quote! { __wrap: (#(#field_tys),*) }, quote! { __wrap }) |
2906 | }; |
2907 | |
2908 | let field_access = (0..variant.fields.len()).map(|n| { |
2909 | Member::Unnamed(Index { |
2910 | index: n as u32, |
2911 | span: Span::call_site(), |
2912 | }) |
2913 | }); |
2914 | |
2915 | match variant.style { |
2916 | Style::Struct if variant.fields.len() == 1 => { |
2917 | let member = &variant.fields[0].member; |
2918 | quote! { |
2919 | |#arg| #this_value::#variant_ident { #member: #wrapper } |
2920 | } |
2921 | } |
2922 | Style::Struct => { |
2923 | let members = variant.fields.iter().map(|field| &field.member); |
2924 | quote! { |
2925 | |#arg| #this_value::#variant_ident { #(#members: #wrapper.#field_access),* } |
2926 | } |
2927 | } |
2928 | Style::Tuple => quote! { |
2929 | |#arg| #this_value::#variant_ident(#(#wrapper.#field_access),*) |
2930 | }, |
2931 | Style::Newtype => quote! { |
2932 | |#arg| #this_value::#variant_ident(#wrapper) |
2933 | }, |
2934 | Style::Unit => quote! { |
2935 | |#arg| #this_value::#variant_ident |
2936 | }, |
2937 | } |
2938 | } |
2939 | |
2940 | fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { |
2941 | match field.attrs.default() { |
2942 | attr::Default::Default => { |
2943 | let span = field.original.span(); |
2944 | let func = quote_spanned!(span=> _serde::__private::Default::default); |
2945 | return quote_expr!(#func()); |
2946 | } |
2947 | attr::Default::Path(path) => { |
2948 | return quote_expr!(#path()); |
2949 | } |
2950 | attr::Default::None => { /* below */ } |
2951 | } |
2952 | |
2953 | match *cattrs.default() { |
2954 | attr::Default::Default | attr::Default::Path(_) => { |
2955 | let member = &field.member; |
2956 | return quote_expr!(__default.#member); |
2957 | } |
2958 | attr::Default::None => { /* below */ } |
2959 | } |
2960 | |
2961 | let name = field.attrs.name().deserialize_name(); |
2962 | match field.attrs.deserialize_with() { |
2963 | None => { |
2964 | let span = field.original.span(); |
2965 | let func = quote_spanned!(span=> _serde::__private::de::missing_field); |
2966 | quote_expr! { |
2967 | #func(#name)? |
2968 | } |
2969 | } |
2970 | Some(_) => { |
2971 | quote_expr! { |
2972 | return _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#name)) |
2973 | } |
2974 | } |
2975 | } |
2976 | } |
2977 | |
2978 | fn expr_is_missing_seq( |
2979 | assign_to: Option<TokenStream>, |
2980 | index: usize, |
2981 | field: &Field, |
2982 | cattrs: &attr::Container, |
2983 | expecting: &str, |
2984 | ) -> TokenStream { |
2985 | match field.attrs.default() { |
2986 | attr::Default::Default => { |
2987 | let span: Span = field.original.span(); |
2988 | return quote_spanned!(span=> #assign_to _serde::__private::Default::default()); |
2989 | } |
2990 | attr::Default::Path(path: &ExprPath) => { |
2991 | return quote_spanned!(path.span()=> #assign_to #path()); |
2992 | } |
2993 | attr::Default::None => { /* below */ } |
2994 | } |
2995 | |
2996 | match *cattrs.default() { |
2997 | attr::Default::Default | attr::Default::Path(_) => { |
2998 | let member: &Member = &field.member; |
2999 | quote!(#assign_to __default.#member) |
3000 | } |
3001 | attr::Default::None => quote!( |
3002 | return _serde::__private::Err(_serde::de::Error::invalid_length(#index, &#expecting)) |
3003 | ), |
3004 | } |
3005 | } |
3006 | |
3007 | fn effective_style(variant: &Variant) -> Style { |
3008 | match variant.style { |
3009 | Style::Newtype if variant.fields[0].attrs.skip_deserializing() => Style::Unit, |
3010 | other: Style => other, |
3011 | } |
3012 | } |
3013 | |
3014 | struct DeImplGenerics<'a>(&'a Parameters); |
3015 | #[cfg (feature = "deserialize_in_place" )] |
3016 | struct InPlaceImplGenerics<'a>(&'a Parameters); |
3017 | |
3018 | impl<'a> ToTokens for DeImplGenerics<'a> { |
3019 | fn to_tokens(&self, tokens: &mut TokenStream) { |
3020 | let mut generics: Generics = self.0.generics.clone(); |
3021 | if let Some(de_lifetime: LifetimeParam) = self.0.borrowed.de_lifetime_param() { |
3022 | generics.params = Someimpl Iterator (syn::GenericParam::Lifetime(de_lifetime)) |
3023 | .into_iter() |
3024 | .chain(generics.params) |
3025 | .collect(); |
3026 | } |
3027 | let (impl_generics: ImplGenerics<'_>, _, _) = generics.split_for_impl(); |
3028 | impl_generics.to_tokens(tokens); |
3029 | } |
3030 | } |
3031 | |
3032 | #[cfg (feature = "deserialize_in_place" )] |
3033 | impl<'a> ToTokens for InPlaceImplGenerics<'a> { |
3034 | fn to_tokens(&self, tokens: &mut TokenStream) { |
3035 | let place_lifetime = place_lifetime(); |
3036 | let mut generics = self.0.generics.clone(); |
3037 | |
3038 | // Add lifetime for `&'place mut Self, and `'a: 'place` |
3039 | for param in &mut generics.params { |
3040 | match param { |
3041 | syn::GenericParam::Lifetime(param) => { |
3042 | param.bounds.push(place_lifetime.lifetime.clone()); |
3043 | } |
3044 | syn::GenericParam::Type(param) => { |
3045 | param.bounds.push(syn::TypeParamBound::Lifetime( |
3046 | place_lifetime.lifetime.clone(), |
3047 | )); |
3048 | } |
3049 | syn::GenericParam::Const(_) => {} |
3050 | } |
3051 | } |
3052 | generics.params = Some(syn::GenericParam::Lifetime(place_lifetime)) |
3053 | .into_iter() |
3054 | .chain(generics.params) |
3055 | .collect(); |
3056 | if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() { |
3057 | generics.params = Some(syn::GenericParam::Lifetime(de_lifetime)) |
3058 | .into_iter() |
3059 | .chain(generics.params) |
3060 | .collect(); |
3061 | } |
3062 | let (impl_generics, _, _) = generics.split_for_impl(); |
3063 | impl_generics.to_tokens(tokens); |
3064 | } |
3065 | } |
3066 | |
3067 | #[cfg (feature = "deserialize_in_place" )] |
3068 | impl<'a> DeImplGenerics<'a> { |
3069 | fn in_place(self) -> InPlaceImplGenerics<'a> { |
3070 | InPlaceImplGenerics(self.0) |
3071 | } |
3072 | } |
3073 | |
3074 | struct DeTypeGenerics<'a>(&'a Parameters); |
3075 | #[cfg (feature = "deserialize_in_place" )] |
3076 | struct InPlaceTypeGenerics<'a>(&'a Parameters); |
3077 | |
3078 | fn de_type_generics_to_tokens( |
3079 | mut generics: syn::Generics, |
3080 | borrowed: &BorrowedLifetimes, |
3081 | tokens: &mut TokenStream, |
3082 | ) { |
3083 | if borrowed.de_lifetime_param().is_some() { |
3084 | let def: LifetimeParam = syn::LifetimeParam { |
3085 | attrs: Vec::new(), |
3086 | lifetime: syn::Lifetime::new(symbol:"'de" , Span::call_site()), |
3087 | colon_token: None, |
3088 | bounds: Punctuated::new(), |
3089 | }; |
3090 | // Prepend 'de lifetime to list of generics |
3091 | generics.params = Someimpl Iterator (syn::GenericParam::Lifetime(def)) |
3092 | .into_iter() |
3093 | .chain(generics.params) |
3094 | .collect(); |
3095 | } |
3096 | let (_, ty_generics: TypeGenerics<'_>, _) = generics.split_for_impl(); |
3097 | ty_generics.to_tokens(tokens); |
3098 | } |
3099 | |
3100 | impl<'a> ToTokens for DeTypeGenerics<'a> { |
3101 | fn to_tokens(&self, tokens: &mut TokenStream) { |
3102 | de_type_generics_to_tokens(self.0.generics.clone(), &self.0.borrowed, tokens); |
3103 | } |
3104 | } |
3105 | |
3106 | #[cfg (feature = "deserialize_in_place" )] |
3107 | impl<'a> ToTokens for InPlaceTypeGenerics<'a> { |
3108 | fn to_tokens(&self, tokens: &mut TokenStream) { |
3109 | let mut generics = self.0.generics.clone(); |
3110 | generics.params = Some(syn::GenericParam::Lifetime(place_lifetime())) |
3111 | .into_iter() |
3112 | .chain(generics.params) |
3113 | .collect(); |
3114 | |
3115 | de_type_generics_to_tokens(generics, &self.0.borrowed, tokens); |
3116 | } |
3117 | } |
3118 | |
3119 | #[cfg (feature = "deserialize_in_place" )] |
3120 | impl<'a> DeTypeGenerics<'a> { |
3121 | fn in_place(self) -> InPlaceTypeGenerics<'a> { |
3122 | InPlaceTypeGenerics(self.0) |
3123 | } |
3124 | } |
3125 | |
3126 | #[cfg (feature = "deserialize_in_place" )] |
3127 | fn place_lifetime() -> syn::LifetimeParam { |
3128 | syn::LifetimeParam { |
3129 | attrs: Vec::new(), |
3130 | lifetime: syn::Lifetime::new("'place" , Span::call_site()), |
3131 | colon_token: None, |
3132 | bounds: Punctuated::new(), |
3133 | } |
3134 | } |
3135 | |
3136 | fn split_with_de_lifetime( |
3137 | params: &Parameters, |
3138 | ) -> ( |
3139 | DeImplGenerics, |
3140 | DeTypeGenerics, |
3141 | syn::TypeGenerics, |
3142 | Option<&syn::WhereClause>, |
3143 | ) { |
3144 | let de_impl_generics: DeImplGenerics<'_> = DeImplGenerics(params); |
3145 | let de_ty_generics: DeTypeGenerics<'_> = DeTypeGenerics(params); |
3146 | let (_, ty_generics: TypeGenerics<'_>, where_clause: Option<&WhereClause>) = params.generics.split_for_impl(); |
3147 | (de_impl_generics, de_ty_generics, ty_generics, where_clause) |
3148 | } |
3149 | |