| 1 |
use crate::deprecated::allow_deprecated; |
| 2 |
use crate::fragment::{Expr, Fragment, Stmts}; |
| 3 |
use crate::internals::ast::{Container, Data, Field, Style, Variant}; |
| 4 |
use crate::internals::name::Name; |
| 5 |
use crate::internals::{attr, replace_receiver, ungroup, Ctxt, Derive}; |
| 6 |
use crate::{bound, dummy, pretend, private, this}; |
| 7 |
use proc_macro2::{Span, TokenStream}; |
| 8 |
use quote::{quote, quote_spanned, ToTokens}; |
| 9 |
use std::collections::BTreeSet; |
| 10 |
use std::ptr; |
| 11 |
use syn::punctuated::Punctuated; |
| 12 |
use syn::spanned::Spanned; |
| 13 |
use syn::{parse_quote, Ident, Index, Member}; |
| 14 |
|
| 15 |
mod enum_; |
| 16 |
mod enum_adjacently; |
| 17 |
mod enum_externally; |
| 18 |
mod enum_internally; |
| 19 |
mod enum_untagged; |
| 20 |
mod identifier; |
| 21 |
mod struct_; |
| 22 |
mod tuple; |
| 23 |
mod unit; |
| 24 |
|
| 25 |
pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result<TokenStream> { |
| 26 |
replace_receiver(input); |
| 27 |
|
| 28 |
let ctxt = Ctxt::new(); |
| 29 |
let Some(cont) = Container::from_ast(&ctxt, input, Derive::Deserialize, &private.ident()) |
| 30 |
else { |
| 31 |
return Err(ctxt.check().unwrap_err()); |
| 32 |
}; |
| 33 |
precondition(&ctxt, &cont); |
| 34 |
ctxt.check()?; |
| 35 |
|
| 36 |
let ident = &cont.ident; |
| 37 |
let params = Parameters::new(&cont); |
| 38 |
let (de_impl_generics, _, ty_generics, where_clause) = params.generics_with_de_lifetime(); |
| 39 |
let body = Stmts(deserialize_body(&cont, ¶ms)); |
| 40 |
let delife = params.borrowed.de_lifetime(); |
| 41 |
let allow_deprecated = allow_deprecated(input); |
| 42 |
|
| 43 |
let impl_block = if let Some(remote) = cont.attrs.remote() { |
| 44 |
let vis = &input.vis; |
| 45 |
let used = pretend::pretend_used(&cont, params.is_packed); |
| 46 |
quote! { |
| 47 |
#[automatically_derived] |
| 48 |
#allow_deprecated |
| 49 |
impl #de_impl_generics #ident #ty_generics #where_clause { |
| 50 |
#vis fn deserialize<__D>(__deserializer: __D) -> _serde::#private::Result<#remote #ty_generics, __D::Error> |
| 51 |
where |
| 52 |
__D: _serde::Deserializer<#delife>, |
| 53 |
{ |
| 54 |
#used |
| 55 |
#body |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
} else { |
| 60 |
let fn_deserialize_in_place = deserialize_in_place_body(&cont, ¶ms); |
| 61 |
|
| 62 |
quote! { |
| 63 |
#[automatically_derived] |
| 64 |
#allow_deprecated |
| 65 |
impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause { |
| 66 |
fn deserialize<__D>(__deserializer: __D) -> _serde::#private::Result<Self, __D::Error> |
| 67 |
where |
| 68 |
__D: _serde::Deserializer<#delife>, |
| 69 |
{ |
| 70 |
#body |
| 71 |
} |
| 72 |
|
| 73 |
#fn_deserialize_in_place |
| 74 |
} |
| 75 |
} |
| 76 |
}; |
| 77 |
|
| 78 |
Ok(dummy::wrap_in_const( |
| 79 |
cont.attrs.custom_serde_path(), |
| 80 |
impl_block, |
| 81 |
)) |
| 82 |
} |
| 83 |
|
| 84 |
fn precondition(cx: &Ctxt, cont: &Container) { |
| 85 |
precondition_sized(cx, cont); |
| 86 |
precondition_no_de_lifetime(cx, cont); |
| 87 |
} |
| 88 |
|
| 89 |
fn precondition_sized(cx: &Ctxt, cont: &Container) { |
| 90 |
if let Data::Struct(_, fields) = &cont.data { |
| 91 |
if let Some(last) = fields.last() { |
| 92 |
if let syn::Type::Slice(_) = ungroup(last.ty) { |
| 93 |
cx.error_spanned_by( |
| 94 |
cont.original, |
| 95 |
"cannot deserialize a dynamically sized struct", |
| 96 |
); |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
fn precondition_no_de_lifetime(cx: &Ctxt, cont: &Container) { |
| 103 |
if let BorrowedLifetimes::Borrowed(_) = borrowed_lifetimes(cont) { |
| 104 |
for param in cont.generics.lifetimes() { |
| 105 |
if param.lifetime.to_string() == "'de" { |
| 106 |
cx.error_spanned_by( |
| 107 |
¶m.lifetime, |
| 108 |
"cannot deserialize when there is a lifetime parameter called 'de", |
| 109 |
); |
| 110 |
return; |
| 111 |
} |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
struct Parameters { |
| 117 |
/// Name of the type the `derive` is on. |
| 118 |
local: syn::Ident, |
| 119 |
|
| 120 |
/// Path to the type the impl is for. Either a single `Ident` for local |
| 121 |
/// types (does not include generic parameters) or `some::remote::Path` for |
| 122 |
/// remote types. |
| 123 |
this_type: syn::Path, |
| 124 |
|
| 125 |
/// Same as `this_type` but using `::<T>` for generic parameters for use in |
| 126 |
/// expression position. |
| 127 |
this_value: syn::Path, |
| 128 |
|
| 129 |
/// Generics including any explicit and inferred bounds for the impl. |
| 130 |
generics: syn::Generics, |
| 131 |
|
| 132 |
/// Lifetimes borrowed from the deserializer. These will become bounds on |
| 133 |
/// the `'de` lifetime of the deserializer. |
| 134 |
borrowed: BorrowedLifetimes, |
| 135 |
|
| 136 |
/// At least one field has a serde(getter) attribute, implying that the |
| 137 |
/// remote type has a private field. |
| 138 |
has_getter: bool, |
| 139 |
|
| 140 |
/// Type has a repr(packed) attribute. |
| 141 |
is_packed: bool, |
| 142 |
} |
| 143 |
|
| 144 |
impl Parameters { |
| 145 |
fn new(cont: &Container) -> Self { |
| 146 |
let local = cont.ident.clone(); |
| 147 |
let this_type = this::this_type(cont); |
| 148 |
let this_value = this::this_value(cont); |
| 149 |
let borrowed = borrowed_lifetimes(cont); |
| 150 |
let generics = build_generics(cont, &borrowed); |
| 151 |
let has_getter = cont.data.has_getter(); |
| 152 |
let is_packed = cont.attrs.is_packed(); |
| 153 |
|
| 154 |
Parameters { |
| 155 |
local, |
| 156 |
this_type, |
| 157 |
this_value, |
| 158 |
generics, |
| 159 |
borrowed, |
| 160 |
has_getter, |
| 161 |
is_packed, |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
/// Type name to use in error messages and `&'static str` arguments to |
| 166 |
/// various Deserializer methods. |
| 167 |
fn type_name(&self) -> String { |
| 168 |
self.this_type.segments.last().unwrap().ident.to_string() |
| 169 |
} |
| 170 |
|
| 171 |
/// Split the data structure's generics into the pieces to use for its |
| 172 |
/// `Deserialize` impl, augmented with an additional `'de` lifetime for use |
| 173 |
/// as the `Deserialize` trait's lifetime. |
| 174 |
fn generics_with_de_lifetime( |
| 175 |
&self, |
| 176 |
) -> ( |
| 177 |
DeImplGenerics, |
| 178 |
DeTypeGenerics, |
| 179 |
syn::TypeGenerics, |
| 180 |
Option<&syn::WhereClause>, |
| 181 |
) { |
| 182 |
let de_impl_generics = DeImplGenerics(self); |
| 183 |
let de_ty_generics = DeTypeGenerics(self); |
| 184 |
let (_, ty_generics, where_clause) = self.generics.split_for_impl(); |
| 185 |
(de_impl_generics, de_ty_generics, ty_generics, where_clause) |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
// All the generics in the input, plus a bound `T: Deserialize` for each generic |
| 190 |
// field type that will be deserialized by us, plus a bound `T: Default` for |
| 191 |
// each generic field type that will be set to a default value. |
| 192 |
fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics { |
| 193 |
let generics = bound::without_defaults(cont.generics); |
| 194 |
|
| 195 |
let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound); |
| 196 |
|
| 197 |
let generics = |
| 198 |
bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::de_bound); |
| 199 |
|
| 200 |
match cont.attrs.de_bound() { |
| 201 |
Some(predicates) => bound::with_where_predicates(&generics, predicates), |
| 202 |
None => { |
| 203 |
let generics = match *cont.attrs.default() { |
| 204 |
attr::Default::Default => bound::with_self_bound( |
| 205 |
cont, |
| 206 |
&generics, |
| 207 |
&parse_quote!(_serde::#private::Default), |
| 208 |
), |
| 209 |
attr::Default::None | attr::Default::Path(_) => generics, |
| 210 |
}; |
| 211 |
|
| 212 |
let delife = borrowed.de_lifetime(); |
| 213 |
let generics = bound::with_bound( |
| 214 |
cont, |
| 215 |
&generics, |
| 216 |
needs_deserialize_bound, |
| 217 |
&parse_quote!(_serde::Deserialize<#delife>), |
| 218 |
); |
| 219 |
|
| 220 |
bound::with_bound( |
| 221 |
cont, |
| 222 |
&generics, |
| 223 |
requires_default, |
| 224 |
&parse_quote!(_serde::#private::Default), |
| 225 |
) |
| 226 |
} |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
// Fields with a `skip_deserializing` or `deserialize_with` attribute, or which |
| 231 |
// belong to a variant with a `skip_deserializing` or `deserialize_with` |
| 232 |
// attribute, are not deserialized by us so we do not generate a bound. Fields |
| 233 |
// with a `bound` attribute specify their own bound so we do not generate one. |
| 234 |
// All other fields may need a `T: Deserialize` bound where T is the type of the |
| 235 |
// field. |
| 236 |
fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { |
| 237 |
!field.skip_deserializing() |
| 238 |
&& field.deserialize_with().is_none() |
| 239 |
&& field.de_bound().is_none() |
| 240 |
&& variant.map_or(true, |variant| { |
| 241 |
!variant.skip_deserializing() |
| 242 |
&& variant.deserialize_with().is_none() |
| 243 |
&& variant.de_bound().is_none() |
| 244 |
}) |
| 245 |
} |
| 246 |
|
| 247 |
// Fields with a `default` attribute (not `default=...`), and fields with a |
| 248 |
// `skip_deserializing` attribute that do not also have `default=...`. |
| 249 |
fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool { |
| 250 |
if let attr::Default::Default = *field.default() { |
| 251 |
true |
| 252 |
} else { |
| 253 |
false |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
enum BorrowedLifetimes { |
| 258 |
Borrowed(BTreeSet<syn::Lifetime>), |
| 259 |
Static, |
| 260 |
} |
| 261 |
|
| 262 |
impl BorrowedLifetimes { |
| 263 |
fn de_lifetime(&self) -> syn::Lifetime { |
| 264 |
match *self { |
| 265 |
BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de", Span::call_site()), |
| 266 |
BorrowedLifetimes::Static => syn::Lifetime::new("'static", Span::call_site()), |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
fn de_lifetime_param(&self) -> Option<syn::LifetimeParam> { |
| 271 |
match self { |
| 272 |
BorrowedLifetimes::Borrowed(bounds) => Some(syn::LifetimeParam { |
| 273 |
attrs: Vec::new(), |
| 274 |
lifetime: syn::Lifetime::new("'de", Span::call_site()), |
| 275 |
colon_token: None, |
| 276 |
bounds: bounds.iter().cloned().collect(), |
| 277 |
}), |
| 278 |
BorrowedLifetimes::Static => None, |
| 279 |
} |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
// The union of lifetimes borrowed by each field of the container. |
| 284 |
// |
| 285 |
// These turn into bounds on the `'de` lifetime of the Deserialize impl. If |
| 286 |
// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is: |
| 287 |
// |
| 288 |
// impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c> |
| 289 |
// |
| 290 |
// If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant |
| 291 |
// and we use plain `'static` instead of `'de`. |
| 292 |
fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes { |
| 293 |
let mut lifetimes = BTreeSet::new(); |
| 294 |
for field in cont.data.all_fields() { |
| 295 |
if !field.attrs.skip_deserializing() { |
| 296 |
lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned()); |
| 297 |
} |
| 298 |
} |
| 299 |
if lifetimes.iter().any(|b| b.to_string() == "'static") { |
| 300 |
BorrowedLifetimes::Static |
| 301 |
} else { |
| 302 |
BorrowedLifetimes::Borrowed(lifetimes) |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment { |
| 307 |
if cont.attrs.transparent() { |
| 308 |
deserialize_transparent(cont, params) |
| 309 |
} else if let Some(type_from) = cont.attrs.type_from() { |
| 310 |
deserialize_from(type_from) |
| 311 |
} else if let Some(type_try_from) = cont.attrs.type_try_from() { |
| 312 |
deserialize_try_from(type_try_from) |
| 313 |
} else if let attr::Identifier::No = cont.attrs.identifier() { |
| 314 |
match &cont.data { |
| 315 |
Data::Enum(variants) => enum_::deserialize(params, variants, &cont.attrs), |
| 316 |
Data::Struct(Style::Struct, fields) => { |
| 317 |
struct_::deserialize(params, fields, &cont.attrs, StructForm::Struct) |
| 318 |
} |
| 319 |
Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { |
| 320 |
tuple::deserialize(params, fields, &cont.attrs, TupleForm::Tuple) |
| 321 |
} |
| 322 |
Data::Struct(Style::Unit, _) => unit::deserialize(params, &cont.attrs), |
| 323 |
} |
| 324 |
} else { |
| 325 |
match &cont.data { |
| 326 |
Data::Enum(variants) => identifier::deserialize_custom(params, variants, &cont.attrs), |
| 327 |
Data::Struct(_, _) => unreachable!("checked in serde_derive_internals"), |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
#[cfg(feature = "deserialize_in_place")] |
| 333 |
fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<Stmts> { |
| 334 |
// Only remote derives have getters, and we do not generate |
| 335 |
// deserialize_in_place for remote derives. |
| 336 |
assert!(!params.has_getter); |
| 337 |
|
| 338 |
if cont.attrs.transparent() |
| 339 |
|| cont.attrs.type_from().is_some() |
| 340 |
|| cont.attrs.type_try_from().is_some() |
| 341 |
|| cont.attrs.identifier().is_some() |
| 342 |
|| cont |
| 343 |
.data |
| 344 |
.all_fields() |
| 345 |
.all(|f| f.attrs.deserialize_with().is_some()) |
| 346 |
{ |
| 347 |
return None; |
| 348 |
} |
| 349 |
|
| 350 |
let code = match &cont.data { |
| 351 |
Data::Struct(Style::Struct, fields) => { |
| 352 |
struct_::deserialize_in_place(params, fields, &cont.attrs)? |
| 353 |
} |
| 354 |
Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { |
| 355 |
tuple::deserialize_in_place(params, fields, &cont.attrs) |
| 356 |
} |
| 357 |
Data::Enum(_) | Data::Struct(Style::Unit, _) => { |
| 358 |
return None; |
| 359 |
} |
| 360 |
}; |
| 361 |
|
| 362 |
let delife = params.borrowed.de_lifetime(); |
| 363 |
let stmts = Stmts(code); |
| 364 |
|
| 365 |
let fn_deserialize_in_place = quote_block! { |
| 366 |
fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::#private::Result<(), __D::Error> |
| 367 |
where |
| 368 |
__D: _serde::Deserializer<#delife>, |
| 369 |
{ |
| 370 |
#stmts |
| 371 |
} |
| 372 |
}; |
| 373 |
|
| 374 |
Some(Stmts(fn_deserialize_in_place)) |
| 375 |
} |
| 376 |
|
| 377 |
#[cfg(not(feature = "deserialize_in_place"))] |
| 378 |
fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option<Stmts> { |
| 379 |
None |
| 380 |
} |
| 381 |
|
| 382 |
/// Generates `Deserialize::deserialize` body for a type with `#[serde(transparent)]` attribute |
| 383 |
fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment { |
| 384 |
let fields = match &cont.data { |
| 385 |
Data::Struct(_, fields) => fields, |
| 386 |
Data::Enum(_) => unreachable!(), |
| 387 |
}; |
| 388 |
|
| 389 |
let this_value = ¶ms.this_value; |
| 390 |
let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap(); |
| 391 |
|
| 392 |
let path = match transparent_field.attrs.deserialize_with() { |
| 393 |
Some(path) => quote!(#path), |
| 394 |
None => { |
| 395 |
let span = transparent_field.original.span(); |
| 396 |
quote_spanned!(span=> _serde::Deserialize::deserialize) |
| 397 |
} |
| 398 |
}; |
| 399 |
|
| 400 |
let assign = fields.iter().map(|field| { |
| 401 |
let member = &field.member; |
| 402 |
if ptr::eq(field, transparent_field) { |
| 403 |
quote!(#member: __transparent) |
| 404 |
} else { |
| 405 |
let value = match field.attrs.default() { |
| 406 |
attr::Default::Default => quote!(_serde::#private::Default::default()), |
| 407 |
// If #path returns wrong type, error will be reported here (^^^^^). |
| 408 |
// We attach span of the path to the function so it will be reported |
| 409 |
// on the #[serde(default = "...")] |
| 410 |
// ^^^^^ |
| 411 |
attr::Default::Path(path) => quote_spanned!(path.span()=> #path()), |
| 412 |
attr::Default::None => quote!(_serde::#private::PhantomData), |
| 413 |
}; |
| 414 |
quote!(#member: #value) |
| 415 |
} |
| 416 |
}); |
| 417 |
|
| 418 |
quote_block! { |
| 419 |
_serde::#private::Result::map( |
| 420 |
#path(__deserializer), |
| 421 |
|__transparent| #this_value { #(#assign),* }) |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
/// Generates `Deserialize::deserialize` body for a type with `#[serde(from)]` attribute |
| 426 |
fn deserialize_from(type_from: &syn::Type) -> Fragment { |
| 427 |
quote_block! { |
| 428 |
_serde::#private::Result::map( |
| 429 |
<#type_from as _serde::Deserialize>::deserialize(__deserializer), |
| 430 |
_serde::#private::From::from) |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
/// Generates `Deserialize::deserialize` body for a type with `#[serde(try_from)]` attribute |
| 435 |
fn deserialize_try_from(type_try_from: &syn::Type) -> Fragment { |
| 436 |
quote_block! { |
| 437 |
_serde::#private::Result::and_then( |
| 438 |
<#type_try_from as _serde::Deserialize>::deserialize(__deserializer), |
| 439 |
|v| _serde::#private::TryFrom::try_from(v).map_err(_serde::de::Error::custom)) |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
enum TupleForm<'a> { |
| 444 |
Tuple, |
| 445 |
/// Contains a variant name |
| 446 |
ExternallyTagged(&'a syn::Ident), |
| 447 |
/// Contains a variant name |
| 448 |
Untagged(&'a syn::Ident), |
| 449 |
} |
| 450 |
|
| 451 |
fn deserialize_seq( |
| 452 |
type_path: &TokenStream, |
| 453 |
params: &Parameters, |
| 454 |
fields: &[Field], |
| 455 |
is_struct: bool, |
| 456 |
cattrs: &attr::Container, |
| 457 |
expecting: &str, |
| 458 |
) -> Fragment { |
| 459 |
let vars = (0..fields.len()).map(field_i as fn(_) -> _); |
| 460 |
|
| 461 |
let deserialized_count = fields |
| 462 |
.iter() |
| 463 |
.filter(|field| !field.attrs.skip_deserializing()) |
| 464 |
.count(); |
| 465 |
let expecting = if deserialized_count == 1 { |
| 466 |
format!("{} with 1 element", expecting) |
| 467 |
} else { |
| 468 |
format!("{} with {} elements", expecting, deserialized_count) |
| 469 |
}; |
| 470 |
let expecting = cattrs.expecting().unwrap_or(&expecting); |
| 471 |
|
| 472 |
let mut index_in_seq = 0_usize; |
| 473 |
let let_values = vars.clone().zip(fields).map(|(var, field)| { |
| 474 |
if field.attrs.skip_deserializing() { |
| 475 |
let default = Expr(expr_is_missing(field, cattrs)); |
| 476 |
quote! { |
| 477 |
let #var = #default; |
| 478 |
} |
| 479 |
} else { |
| 480 |
let visit = match field.attrs.deserialize_with() { |
| 481 |
None => { |
| 482 |
let field_ty = field.ty; |
| 483 |
let span = field.original.span(); |
| 484 |
let func = |
| 485 |
quote_spanned!(span=> _serde::de::SeqAccess::next_element::<#field_ty>); |
| 486 |
quote!(#func(&mut __seq)?) |
| 487 |
} |
| 488 |
Some(path) => { |
| 489 |
let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); |
| 490 |
quote!({ |
| 491 |
#wrapper |
| 492 |
_serde::#private::Option::map( |
| 493 |
_serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)?, |
| 494 |
|__wrap| __wrap.value) |
| 495 |
}) |
| 496 |
} |
| 497 |
}; |
| 498 |
let value_if_none = expr_is_missing_seq(None, index_in_seq, field, cattrs, expecting); |
| 499 |
let assign = quote! { |
| 500 |
let #var = match #visit { |
| 501 |
_serde::#private::Some(__value) => __value, |
| 502 |
_serde::#private::None => #value_if_none, |
| 503 |
}; |
| 504 |
}; |
| 505 |
index_in_seq += 1; |
| 506 |
assign |
| 507 |
} |
| 508 |
}); |
| 509 |
|
| 510 |
let mut result = if is_struct { |
| 511 |
let names = fields.iter().map(|f| &f.member); |
| 512 |
quote! { |
| 513 |
#type_path { #( #names: #vars ),* } |
| 514 |
} |
| 515 |
} else { |
| 516 |
quote! { |
| 517 |
#type_path ( #(#vars),* ) |
| 518 |
} |
| 519 |
}; |
| 520 |
|
| 521 |
if params.has_getter { |
| 522 |
let this_type = ¶ms.this_type; |
| 523 |
let (_, ty_generics, _) = params.generics.split_for_impl(); |
| 524 |
result = quote! { |
| 525 |
_serde::#private::Into::<#this_type #ty_generics>::into(#result) |
| 526 |
}; |
| 527 |
} |
| 528 |
|
| 529 |
let let_default = match cattrs.default() { |
| 530 |
attr::Default::Default => Some(quote!( |
| 531 |
let __default: Self::Value = _serde::#private::Default::default(); |
| 532 |
)), |
| 533 |
// If #path returns wrong type, error will be reported here (^^^^^). |
| 534 |
// We attach span of the path to the function so it will be reported |
| 535 |
// on the #[serde(default = "...")] |
| 536 |
// ^^^^^ |
| 537 |
attr::Default::Path(path) => Some(quote_spanned!(path.span()=> |
| 538 |
let __default: Self::Value = #path(); |
| 539 |
)), |
| 540 |
attr::Default::None => { |
| 541 |
// We don't need the default value, to prevent an unused variable warning |
| 542 |
// we'll leave the line empty. |
| 543 |
None |
| 544 |
} |
| 545 |
}; |
| 546 |
|
| 547 |
quote_block! { |
| 548 |
#let_default |
| 549 |
#(#let_values)* |
| 550 |
_serde::#private::Ok(#result) |
| 551 |
} |
| 552 |
} |
| 553 |
|
| 554 |
#[cfg(feature = "deserialize_in_place")] |
| 555 |
fn deserialize_seq_in_place( |
| 556 |
params: &Parameters, |
| 557 |
fields: &[Field], |
| 558 |
cattrs: &attr::Container, |
| 559 |
expecting: &str, |
| 560 |
) -> Fragment { |
| 561 |
let deserialized_count = fields |
| 562 |
.iter() |
| 563 |
.filter(|field| !field.attrs.skip_deserializing()) |
| 564 |
.count(); |
| 565 |
let expecting = if deserialized_count == 1 { |
| 566 |
format!("{} with 1 element", expecting) |
| 567 |
} else { |
| 568 |
format!("{} with {} elements", expecting, deserialized_count) |
| 569 |
}; |
| 570 |
let expecting = cattrs.expecting().unwrap_or(&expecting); |
| 571 |
|
| 572 |
let mut index_in_seq = 0usize; |
| 573 |
let write_values = fields.iter().map(|field| { |
| 574 |
let member = &field.member; |
| 575 |
|
| 576 |
if field.attrs.skip_deserializing() { |
| 577 |
let default = Expr(expr_is_missing(field, cattrs)); |
| 578 |
quote! { |
| 579 |
self.place.#member = #default; |
| 580 |
} |
| 581 |
} else { |
| 582 |
let value_if_none = expr_is_missing_seq(Some(quote!(self.place.#member = )), index_in_seq, field, cattrs, expecting); |
| 583 |
let write = match field.attrs.deserialize_with() { |
| 584 |
None => { |
| 585 |
quote! { |
| 586 |
if let _serde::#private::None = _serde::de::SeqAccess::next_element_seed(&mut __seq, |
| 587 |
_serde::#private::de::InPlaceSeed(&mut self.place.#member))? |
| 588 |
{ |
| 589 |
#value_if_none; |
| 590 |
} |
| 591 |
} |
| 592 |
} |
| 593 |
Some(path) => { |
| 594 |
let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); |
| 595 |
quote!({ |
| 596 |
#wrapper |
| 597 |
match _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq) { |
| 598 |
_serde::#private::Ok(_serde::#private::Some(__wrap)) => { |
| 599 |
self.place.#member = __wrap.value; |
| 600 |
} |
| 601 |
_serde::#private::Ok(_serde::#private::None) => { |
| 602 |
#value_if_none; |
| 603 |
} |
| 604 |
_serde::#private::Err(__err) => { |
| 605 |
return _serde::#private::Err(__err); |
| 606 |
} |
| 607 |
} |
| 608 |
}) |
| 609 |
} |
| 610 |
}; |
| 611 |
index_in_seq += 1; |
| 612 |
write |
| 613 |
} |
| 614 |
}); |
| 615 |
|
| 616 |
let this_type = ¶ms.this_type; |
| 617 |
let (_, ty_generics, _) = params.generics.split_for_impl(); |
| 618 |
let let_default = match cattrs.default() { |
| 619 |
attr::Default::Default => Some(quote!( |
| 620 |
let __default: #this_type #ty_generics = _serde::#private::Default::default(); |
| 621 |
)), |
| 622 |
// If #path returns wrong type, error will be reported here (^^^^^). |
| 623 |
// We attach span of the path to the function so it will be reported |
| 624 |
// on the #[serde(default = "...")] |
| 625 |
// ^^^^^ |
| 626 |
attr::Default::Path(path) => Some(quote_spanned!(path.span()=> |
| 627 |
let __default: #this_type #ty_generics = #path(); |
| 628 |
)), |
| 629 |
attr::Default::None => { |
| 630 |
// We don't need the default value, to prevent an unused variable warning |
| 631 |
// we'll leave the line empty. |
| 632 |
None |
| 633 |
} |
| 634 |
}; |
| 635 |
|
| 636 |
quote_block! { |
| 637 |
#let_default |
| 638 |
#(#write_values)* |
| 639 |
_serde::#private::Ok(()) |
| 640 |
} |
| 641 |
} |
| 642 |
|
| 643 |
enum StructForm<'a> { |
| 644 |
Struct, |
| 645 |
/// Contains a variant name |
| 646 |
ExternallyTagged(&'a syn::Ident), |
| 647 |
/// Contains a variant name |
| 648 |
InternallyTagged(&'a syn::Ident), |
| 649 |
/// Contains a variant name |
| 650 |
Untagged(&'a syn::Ident), |
| 651 |
} |
| 652 |
|
| 653 |
struct FieldWithAliases<'a> { |
| 654 |
ident: Ident, |
| 655 |
aliases: &'a BTreeSet<Name>, |
| 656 |
} |
| 657 |
|
| 658 |
pub(crate) fn field_i(i: usize) -> Ident { |
| 659 |
Ident::new(&format!("__field{}", i), Span::call_site()) |
| 660 |
} |
| 661 |
|
| 662 |
/// This function wraps the expression in `#[serde(deserialize_with = "...")]` |
| 663 |
/// in a trait to prevent it from accessing the internal `Deserialize` state. |
| 664 |
fn wrap_deserialize_with( |
| 665 |
params: &Parameters, |
| 666 |
value_ty: &TokenStream, |
| 667 |
deserialize_with: &syn::ExprPath, |
| 668 |
) -> (TokenStream, TokenStream) { |
| 669 |
let this_type = ¶ms.this_type; |
| 670 |
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = |
| 671 |
params.generics_with_de_lifetime(); |
| 672 |
let delife = params.borrowed.de_lifetime(); |
| 673 |
let deserializer_var = quote!(__deserializer); |
| 674 |
|
| 675 |
// If #deserialize_with returns wrong type, error will be reported here (^^^^^). |
| 676 |
// We attach span of the path to the function so it will be reported |
| 677 |
// on the #[serde(with = "...")] |
| 678 |
// ^^^^^ |
| 679 |
let value = quote_spanned! {deserialize_with.span()=> |
| 680 |
#deserialize_with(#deserializer_var)? |
| 681 |
}; |
| 682 |
let wrapper = quote! { |
| 683 |
#[doc(hidden)] |
| 684 |
struct __DeserializeWith #de_impl_generics #where_clause { |
| 685 |
value: #value_ty, |
| 686 |
phantom: _serde::#private::PhantomData<#this_type #ty_generics>, |
| 687 |
lifetime: _serde::#private::PhantomData<&#delife ()>, |
| 688 |
} |
| 689 |
|
| 690 |
#[automatically_derived] |
| 691 |
impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause { |
| 692 |
fn deserialize<__D>(#deserializer_var: __D) -> _serde::#private::Result<Self, __D::Error> |
| 693 |
where |
| 694 |
__D: _serde::Deserializer<#delife>, |
| 695 |
{ |
| 696 |
_serde::#private::Ok(__DeserializeWith { |
| 697 |
value: #value, |
| 698 |
phantom: _serde::#private::PhantomData, |
| 699 |
lifetime: _serde::#private::PhantomData, |
| 700 |
}) |
| 701 |
} |
| 702 |
} |
| 703 |
}; |
| 704 |
|
| 705 |
let wrapper_ty = quote!(__DeserializeWith #de_ty_generics); |
| 706 |
|
| 707 |
(wrapper, wrapper_ty) |
| 708 |
} |
| 709 |
|
| 710 |
fn wrap_deserialize_field_with( |
| 711 |
params: &Parameters, |
| 712 |
field_ty: &syn::Type, |
| 713 |
deserialize_with: &syn::ExprPath, |
| 714 |
) -> (TokenStream, TokenStream) { |
| 715 |
wrap_deserialize_with(params, "e!(#field_ty), deserialize_with) |
| 716 |
} |
| 717 |
|
| 718 |
// Generates closure that converts single input parameter to the final value. |
| 719 |
fn unwrap_to_variant_closure( |
| 720 |
params: &Parameters, |
| 721 |
variant: &Variant, |
| 722 |
with_wrapper: bool, |
| 723 |
) -> TokenStream { |
| 724 |
let this_value = ¶ms.this_value; |
| 725 |
let variant_ident = &variant.ident; |
| 726 |
|
| 727 |
let (arg, wrapper) = if with_wrapper { |
| 728 |
(quote! { __wrap }, quote! { __wrap.value }) |
| 729 |
} else { |
| 730 |
let field_tys = variant.fields.iter().map(|field| field.ty); |
| 731 |
(quote! { __wrap: (#(#field_tys),*) }, quote! { __wrap }) |
| 732 |
}; |
| 733 |
|
| 734 |
let field_access = (0..variant.fields.len()).map(|n| { |
| 735 |
Member::Unnamed(Index { |
| 736 |
index: n as u32, |
| 737 |
span: Span::call_site(), |
| 738 |
}) |
| 739 |
}); |
| 740 |
|
| 741 |
match variant.style { |
| 742 |
Style::Struct if variant.fields.len() == 1 => { |
| 743 |
let member = &variant.fields[0].member; |
| 744 |
quote! { |
| 745 |
|#arg| #this_value::#variant_ident { #member: #wrapper } |
| 746 |
} |
| 747 |
} |
| 748 |
Style::Struct => { |
| 749 |
let members = variant.fields.iter().map(|field| &field.member); |
| 750 |
quote! { |
| 751 |
|#arg| #this_value::#variant_ident { #(#members: #wrapper.#field_access),* } |
| 752 |
} |
| 753 |
} |
| 754 |
Style::Tuple => quote! { |
| 755 |
|#arg| #this_value::#variant_ident(#(#wrapper.#field_access),*) |
| 756 |
}, |
| 757 |
Style::Newtype => quote! { |
| 758 |
|#arg| #this_value::#variant_ident(#wrapper) |
| 759 |
}, |
| 760 |
Style::Unit => quote! { |
| 761 |
|#arg| #this_value::#variant_ident |
| 762 |
}, |
| 763 |
} |
| 764 |
} |
| 765 |
|
| 766 |
fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { |
| 767 |
match field.attrs.default() { |
| 768 |
attr::Default::Default => { |
| 769 |
let span = field.original.span(); |
| 770 |
let func = quote_spanned!(span=> _serde::#private::Default::default); |
| 771 |
return quote_expr!(#func()); |
| 772 |
} |
| 773 |
attr::Default::Path(path) => { |
| 774 |
// If #path returns wrong type, error will be reported here (^^^^^). |
| 775 |
// We attach span of the path to the function so it will be reported |
| 776 |
// on the #[serde(default = "...")] |
| 777 |
// ^^^^^ |
| 778 |
return Fragment::Expr(quote_spanned!(path.span()=> #path())); |
| 779 |
} |
| 780 |
attr::Default::None => { /* below */ } |
| 781 |
} |
| 782 |
|
| 783 |
match *cattrs.default() { |
| 784 |
attr::Default::Default | attr::Default::Path(_) => { |
| 785 |
let member = &field.member; |
| 786 |
return quote_expr!(__default.#member); |
| 787 |
} |
| 788 |
attr::Default::None => { /* below */ } |
| 789 |
} |
| 790 |
|
| 791 |
let name = field.attrs.name().deserialize_name(); |
| 792 |
match field.attrs.deserialize_with() { |
| 793 |
None => { |
| 794 |
let span = field.original.span(); |
| 795 |
let func = quote_spanned!(span=> _serde::#private::de::missing_field); |
| 796 |
quote_expr! { |
| 797 |
#func(#name)? |
| 798 |
} |
| 799 |
} |
| 800 |
Some(_) => { |
| 801 |
quote_expr! { |
| 802 |
return _serde::#private::Err(<__A::Error as _serde::de::Error>::missing_field(#name)) |
| 803 |
} |
| 804 |
} |
| 805 |
} |
| 806 |
} |
| 807 |
|
| 808 |
fn expr_is_missing_seq( |
| 809 |
assign_to: Option<TokenStream>, |
| 810 |
index: usize, |
| 811 |
field: &Field, |
| 812 |
cattrs: &attr::Container, |
| 813 |
expecting: &str, |
| 814 |
) -> TokenStream { |
| 815 |
match field.attrs.default() { |
| 816 |
attr::Default::Default => { |
| 817 |
let span = field.original.span(); |
| 818 |
return quote_spanned!(span=> #assign_to _serde::#private::Default::default()); |
| 819 |
} |
| 820 |
attr::Default::Path(path) => { |
| 821 |
// If #path returns wrong type, error will be reported here (^^^^^). |
| 822 |
// We attach span of the path to the function so it will be reported |
| 823 |
// on the #[serde(default = "...")] |
| 824 |
// ^^^^^ |
| 825 |
return quote_spanned!(path.span()=> #assign_to #path()); |
| 826 |
} |
| 827 |
attr::Default::None => { /* below */ } |
| 828 |
} |
| 829 |
|
| 830 |
match *cattrs.default() { |
| 831 |
attr::Default::Default | attr::Default::Path(_) => { |
| 832 |
let member = &field.member; |
| 833 |
quote!(#assign_to __default.#member) |
| 834 |
} |
| 835 |
attr::Default::None => quote!( |
| 836 |
return _serde::#private::Err(_serde::de::Error::invalid_length(#index, &#expecting)) |
| 837 |
), |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
fn effective_style(variant: &Variant) -> Style { |
| 842 |
match variant.style { |
| 843 |
Style::Newtype if variant.fields[0].attrs.skip_deserializing() => Style::Unit, |
| 844 |
other => other, |
| 845 |
} |
| 846 |
} |
| 847 |
|
| 848 |
/// True if there is any field with a `#[serde(flatten)]` attribute, other than |
| 849 |
/// fields which are skipped. |
| 850 |
fn has_flatten(fields: &[Field]) -> bool { |
| 851 |
fields |
| 852 |
.iter() |
| 853 |
.any(|field| field.attrs.flatten() && !field.attrs.skip_deserializing()) |
| 854 |
} |
| 855 |
|
| 856 |
struct DeImplGenerics<'a>(&'a Parameters); |
| 857 |
#[cfg(feature = "deserialize_in_place")] |
| 858 |
struct InPlaceImplGenerics<'a>(&'a Parameters); |
| 859 |
|
| 860 |
impl<'a> ToTokens for DeImplGenerics<'a> { |
| 861 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 862 |
let mut generics = self.0.generics.clone(); |
| 863 |
if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() { |
| 864 |
generics.params = Some(syn::GenericParam::Lifetime(de_lifetime)) |
| 865 |
.into_iter() |
| 866 |
.chain(generics.params) |
| 867 |
.collect(); |
| 868 |
} |
| 869 |
let (impl_generics, _, _) = generics.split_for_impl(); |
| 870 |
impl_generics.to_tokens(tokens); |
| 871 |
} |
| 872 |
} |
| 873 |
|
| 874 |
#[cfg(feature = "deserialize_in_place")] |
| 875 |
impl<'a> ToTokens for InPlaceImplGenerics<'a> { |
| 876 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 877 |
let place_lifetime = place_lifetime(); |
| 878 |
let mut generics = self.0.generics.clone(); |
| 879 |
|
| 880 |
// Add lifetime for `&'place mut Self, and `'a: 'place` |
| 881 |
for param in &mut generics.params { |
| 882 |
match param { |
| 883 |
syn::GenericParam::Lifetime(param) => { |
| 884 |
param.bounds.push(place_lifetime.lifetime.clone()); |
| 885 |
} |
| 886 |
syn::GenericParam::Type(param) => { |
| 887 |
param.bounds.push(syn::TypeParamBound::Lifetime( |
| 888 |
place_lifetime.lifetime.clone(), |
| 889 |
)); |
| 890 |
} |
| 891 |
syn::GenericParam::Const(_) => {} |
| 892 |
} |
| 893 |
} |
| 894 |
generics.params = Some(syn::GenericParam::Lifetime(place_lifetime)) |
| 895 |
.into_iter() |
| 896 |
.chain(generics.params) |
| 897 |
.collect(); |
| 898 |
if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() { |
| 899 |
generics.params = Some(syn::GenericParam::Lifetime(de_lifetime)) |
| 900 |
.into_iter() |
| 901 |
.chain(generics.params) |
| 902 |
.collect(); |
| 903 |
} |
| 904 |
let (impl_generics, _, _) = generics.split_for_impl(); |
| 905 |
impl_generics.to_tokens(tokens); |
| 906 |
} |
| 907 |
} |
| 908 |
|
| 909 |
#[cfg(feature = "deserialize_in_place")] |
| 910 |
impl<'a> DeImplGenerics<'a> { |
| 911 |
fn in_place(self) -> InPlaceImplGenerics<'a> { |
| 912 |
InPlaceImplGenerics(self.0) |
| 913 |
} |
| 914 |
} |
| 915 |
|
| 916 |
struct DeTypeGenerics<'a>(&'a Parameters); |
| 917 |
#[cfg(feature = "deserialize_in_place")] |
| 918 |
struct InPlaceTypeGenerics<'a>(&'a Parameters); |
| 919 |
|
| 920 |
fn de_type_generics_to_tokens( |
| 921 |
mut generics: syn::Generics, |
| 922 |
borrowed: &BorrowedLifetimes, |
| 923 |
tokens: &mut TokenStream, |
| 924 |
) { |
| 925 |
if borrowed.de_lifetime_param().is_some() { |
| 926 |
let def = syn::LifetimeParam { |
| 927 |
attrs: Vec::new(), |
| 928 |
lifetime: syn::Lifetime::new("'de", Span::call_site()), |
| 929 |
colon_token: None, |
| 930 |
bounds: Punctuated::new(), |
| 931 |
}; |
| 932 |
// Prepend 'de lifetime to list of generics |
| 933 |
generics.params = Some(syn::GenericParam::Lifetime(def)) |
| 934 |
.into_iter() |
| 935 |
.chain(generics.params) |
| 936 |
.collect(); |
| 937 |
} |
| 938 |
let (_, ty_generics, _) = generics.split_for_impl(); |
| 939 |
ty_generics.to_tokens(tokens); |
| 940 |
} |
| 941 |
|
| 942 |
impl<'a> ToTokens for DeTypeGenerics<'a> { |
| 943 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 944 |
de_type_generics_to_tokens(self.0.generics.clone(), &self.0.borrowed, tokens); |
| 945 |
} |
| 946 |
} |
| 947 |
|
| 948 |
#[cfg(feature = "deserialize_in_place")] |
| 949 |
impl<'a> ToTokens for InPlaceTypeGenerics<'a> { |
| 950 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 951 |
let mut generics = self.0.generics.clone(); |
| 952 |
generics.params = Some(syn::GenericParam::Lifetime(place_lifetime())) |
| 953 |
.into_iter() |
| 954 |
.chain(generics.params) |
| 955 |
.collect(); |
| 956 |
|
| 957 |
de_type_generics_to_tokens(generics, &self.0.borrowed, tokens); |
| 958 |
} |
| 959 |
} |
| 960 |
|
| 961 |
#[cfg(feature = "deserialize_in_place")] |
| 962 |
impl<'a> DeTypeGenerics<'a> { |
| 963 |
fn in_place(self) -> InPlaceTypeGenerics<'a> { |
| 964 |
InPlaceTypeGenerics(self.0) |
| 965 |
} |
| 966 |
} |
| 967 |
|
| 968 |
#[cfg(feature = "deserialize_in_place")] |
| 969 |
fn place_lifetime() -> syn::LifetimeParam { |
| 970 |
syn::LifetimeParam { |
| 971 |
attrs: Vec::new(), |
| 972 |
lifetime: syn::Lifetime::new("'place", Span::call_site()), |
| 973 |
colon_token: None, |
| 974 |
bounds: Punctuated::new(), |
| 975 |
} |
| 976 |
} |