1 use internals::symbol::*;
2 use internals::{ungroup, Ctxt};
3 use proc_macro2::{Group, Span, TokenStream, TokenTree};
4 use quote::ToTokens;
5 use std::borrow::Cow;
6 use std::collections::BTreeSet;
7 use std::str::FromStr;
8 use syn;
9 use syn::parse::{self, Parse, ParseStream};
10 use syn::punctuated::Punctuated;
11 use syn::Ident;
12 use syn::Meta::{List, NameValue, Path};
13 use syn::NestedMeta::{Lit, Meta};
14 
15 // This module handles parsing of `#[serde(...)]` attributes. The entrypoints
16 // are `attr::Container::from_ast`, `attr::Variant::from_ast`, and
17 // `attr::Field::from_ast`. Each returns an instance of the corresponding
18 // struct. Note that none of them return a Result. Unrecognized, malformed, or
19 // duplicated attributes result in a span_err but otherwise are ignored. The
20 // user will see errors simultaneously for all bad attributes in the crate
21 // rather than just the first.
22 
23 pub use internals::case::RenameRule;
24 
25 struct Attr<'c, T> {
26     cx: &'c Ctxt,
27     name: Symbol,
28     tokens: TokenStream,
29     value: Option<T>,
30 }
31 
32 impl<'c, T> Attr<'c, T> {
none(cx: &'c Ctxt, name: Symbol) -> Self33     fn none(cx: &'c Ctxt, name: Symbol) -> Self {
34         Attr {
35             cx,
36             name,
37             tokens: TokenStream::new(),
38             value: None,
39         }
40     }
41 
set<A: ToTokens>(&mut self, obj: A, value: T)42     fn set<A: ToTokens>(&mut self, obj: A, value: T) {
43         let tokens = obj.into_token_stream();
44 
45         if self.value.is_some() {
46             self.cx
47                 .error_spanned_by(tokens, format!("duplicate serde attribute `{}`", self.name));
48         } else {
49             self.tokens = tokens;
50             self.value = Some(value);
51         }
52     }
53 
set_opt<A: ToTokens>(&mut self, obj: A, value: Option<T>)54     fn set_opt<A: ToTokens>(&mut self, obj: A, value: Option<T>) {
55         if let Some(value) = value {
56             self.set(obj, value);
57         }
58     }
59 
set_if_none(&mut self, value: T)60     fn set_if_none(&mut self, value: T) {
61         if self.value.is_none() {
62             self.value = Some(value);
63         }
64     }
65 
get(self) -> Option<T>66     fn get(self) -> Option<T> {
67         self.value
68     }
69 
get_with_tokens(self) -> Option<(TokenStream, T)>70     fn get_with_tokens(self) -> Option<(TokenStream, T)> {
71         match self.value {
72             Some(v) => Some((self.tokens, v)),
73             None => None,
74         }
75     }
76 }
77 
78 struct BoolAttr<'c>(Attr<'c, ()>);
79 
80 impl<'c> BoolAttr<'c> {
none(cx: &'c Ctxt, name: Symbol) -> Self81     fn none(cx: &'c Ctxt, name: Symbol) -> Self {
82         BoolAttr(Attr::none(cx, name))
83     }
84 
set_true<A: ToTokens>(&mut self, obj: A)85     fn set_true<A: ToTokens>(&mut self, obj: A) {
86         self.0.set(obj, ());
87     }
88 
get(&self) -> bool89     fn get(&self) -> bool {
90         self.0.value.is_some()
91     }
92 }
93 
94 struct VecAttr<'c, T> {
95     cx: &'c Ctxt,
96     name: Symbol,
97     first_dup_tokens: TokenStream,
98     values: Vec<T>,
99 }
100 
101 impl<'c, T> VecAttr<'c, T> {
none(cx: &'c Ctxt, name: Symbol) -> Self102     fn none(cx: &'c Ctxt, name: Symbol) -> Self {
103         VecAttr {
104             cx,
105             name,
106             first_dup_tokens: TokenStream::new(),
107             values: Vec::new(),
108         }
109     }
110 
insert<A: ToTokens>(&mut self, obj: A, value: T)111     fn insert<A: ToTokens>(&mut self, obj: A, value: T) {
112         if self.values.len() == 1 {
113             self.first_dup_tokens = obj.into_token_stream();
114         }
115         self.values.push(value);
116     }
117 
at_most_one(mut self) -> Result<Option<T>, ()>118     fn at_most_one(mut self) -> Result<Option<T>, ()> {
119         if self.values.len() > 1 {
120             let dup_token = self.first_dup_tokens;
121             self.cx.error_spanned_by(
122                 dup_token,
123                 format!("duplicate serde attribute `{}`", self.name),
124             );
125             Err(())
126         } else {
127             Ok(self.values.pop())
128         }
129     }
130 
get(self) -> Vec<T>131     fn get(self) -> Vec<T> {
132         self.values
133     }
134 }
135 
136 pub struct Name {
137     serialize: String,
138     serialize_renamed: bool,
139     deserialize: String,
140     deserialize_renamed: bool,
141     deserialize_aliases: Vec<String>,
142 }
143 
144 #[allow(deprecated)]
unraw(ident: &Ident) -> String145 fn unraw(ident: &Ident) -> String {
146     // str::trim_start_matches was added in 1.30, trim_left_matches deprecated
147     // in 1.33. We currently support rustc back to 1.15 so we need to continue
148     // to use the deprecated one.
149     ident.to_string().trim_left_matches("r#").to_owned()
150 }
151 
152 impl Name {
from_attrs( source_name: String, ser_name: Attr<String>, de_name: Attr<String>, de_aliases: Option<VecAttr<String>>, ) -> Name153     fn from_attrs(
154         source_name: String,
155         ser_name: Attr<String>,
156         de_name: Attr<String>,
157         de_aliases: Option<VecAttr<String>>,
158     ) -> Name {
159         let deserialize_aliases = match de_aliases {
160             Some(de_aliases) => {
161                 let mut alias_list = BTreeSet::new();
162                 for alias_name in de_aliases.get() {
163                     alias_list.insert(alias_name);
164                 }
165                 alias_list.into_iter().collect()
166             }
167             None => Vec::new(),
168         };
169 
170         let ser_name = ser_name.get();
171         let ser_renamed = ser_name.is_some();
172         let de_name = de_name.get();
173         let de_renamed = de_name.is_some();
174         Name {
175             serialize: ser_name.unwrap_or_else(|| source_name.clone()),
176             serialize_renamed: ser_renamed,
177             deserialize: de_name.unwrap_or(source_name),
178             deserialize_renamed: de_renamed,
179             deserialize_aliases,
180         }
181     }
182 
183     /// Return the container name for the container when serializing.
serialize_name(&self) -> String184     pub fn serialize_name(&self) -> String {
185         self.serialize.clone()
186     }
187 
188     /// Return the container name for the container when deserializing.
deserialize_name(&self) -> String189     pub fn deserialize_name(&self) -> String {
190         self.deserialize.clone()
191     }
192 
deserialize_aliases(&self) -> Vec<String>193     fn deserialize_aliases(&self) -> Vec<String> {
194         let mut aliases = self.deserialize_aliases.clone();
195         let main_name = self.deserialize_name();
196         if !aliases.contains(&main_name) {
197             aliases.push(main_name);
198         }
199         aliases
200     }
201 }
202 
203 pub struct RenameAllRules {
204     serialize: RenameRule,
205     deserialize: RenameRule,
206 }
207 
208 /// Represents struct or enum attribute information.
209 pub struct Container {
210     name: Name,
211     transparent: bool,
212     deny_unknown_fields: bool,
213     default: Default,
214     rename_all_rules: RenameAllRules,
215     ser_bound: Option<Vec<syn::WherePredicate>>,
216     de_bound: Option<Vec<syn::WherePredicate>>,
217     tag: TagType,
218     type_from: Option<syn::Type>,
219     type_try_from: Option<syn::Type>,
220     type_into: Option<syn::Type>,
221     remote: Option<syn::Path>,
222     identifier: Identifier,
223     has_flatten: bool,
224     serde_path: Option<syn::Path>,
225     is_packed: bool,
226 }
227 
228 /// Styles of representing an enum.
229 pub enum TagType {
230     /// The default.
231     ///
232     /// ```json
233     /// {"variant1": {"key1": "value1", "key2": "value2"}}
234     /// ```
235     External,
236 
237     /// `#[serde(tag = "type")]`
238     ///
239     /// ```json
240     /// {"type": "variant1", "key1": "value1", "key2": "value2"}
241     /// ```
242     Internal { tag: String },
243 
244     /// `#[serde(tag = "t", content = "c")]`
245     ///
246     /// ```json
247     /// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}}
248     /// ```
249     Adjacent { tag: String, content: String },
250 
251     /// `#[serde(untagged)]`
252     ///
253     /// ```json
254     /// {"key1": "value1", "key2": "value2"}
255     /// ```
256     None,
257 }
258 
259 /// Whether this enum represents the fields of a struct or the variants of an
260 /// enum.
261 #[derive(Copy, Clone)]
262 pub enum Identifier {
263     /// It does not.
264     No,
265 
266     /// This enum represents the fields of a struct. All of the variants must be
267     /// unit variants, except possibly one which is annotated with
268     /// `#[serde(other)]` and is a newtype variant.
269     Field,
270 
271     /// This enum represents the variants of an enum. All of the variants must
272     /// be unit variants.
273     Variant,
274 }
275 
276 impl Identifier {
277     #[cfg(feature = "deserialize_in_place")]
is_some(self) -> bool278     pub fn is_some(self) -> bool {
279         match self {
280             Identifier::No => false,
281             Identifier::Field | Identifier::Variant => true,
282         }
283     }
284 }
285 
286 impl Container {
287     /// Extract out the `#[serde(...)]` attributes from an item.
from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self288     pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self {
289         let mut ser_name = Attr::none(cx, RENAME);
290         let mut de_name = Attr::none(cx, RENAME);
291         let mut transparent = BoolAttr::none(cx, TRANSPARENT);
292         let mut deny_unknown_fields = BoolAttr::none(cx, DENY_UNKNOWN_FIELDS);
293         let mut default = Attr::none(cx, DEFAULT);
294         let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL);
295         let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL);
296         let mut ser_bound = Attr::none(cx, BOUND);
297         let mut de_bound = Attr::none(cx, BOUND);
298         let mut untagged = BoolAttr::none(cx, UNTAGGED);
299         let mut internal_tag = Attr::none(cx, TAG);
300         let mut content = Attr::none(cx, CONTENT);
301         let mut type_from = Attr::none(cx, FROM);
302         let mut type_try_from = Attr::none(cx, TRY_FROM);
303         let mut type_into = Attr::none(cx, INTO);
304         let mut remote = Attr::none(cx, REMOTE);
305         let mut field_identifier = BoolAttr::none(cx, FIELD_IDENTIFIER);
306         let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER);
307         let mut serde_path = Attr::none(cx, CRATE);
308 
309         for meta_item in item
310             .attrs
311             .iter()
312             .flat_map(|attr| get_serde_meta_items(cx, attr))
313             .flatten()
314         {
315             match &meta_item {
316                 // Parse `#[serde(rename = "foo")]`
317                 Meta(NameValue(m)) if m.path == RENAME => {
318                     if let Ok(s) = get_lit_str(cx, RENAME, &m.lit) {
319                         ser_name.set(&m.path, s.value());
320                         de_name.set(&m.path, s.value());
321                     }
322                 }
323 
324                 // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]`
325                 Meta(List(m)) if m.path == RENAME => {
326                     if let Ok((ser, de)) = get_renames(cx, &m.nested) {
327                         ser_name.set_opt(&m.path, ser.map(syn::LitStr::value));
328                         de_name.set_opt(&m.path, de.map(syn::LitStr::value));
329                     }
330                 }
331 
332                 // Parse `#[serde(rename_all = "foo")]`
333                 Meta(NameValue(m)) if m.path == RENAME_ALL => {
334                     if let Ok(s) = get_lit_str(cx, RENAME_ALL, &m.lit) {
335                         match RenameRule::from_str(&s.value()) {
336                             Ok(rename_rule) => {
337                                 rename_all_ser_rule.set(&m.path, rename_rule);
338                                 rename_all_de_rule.set(&m.path, rename_rule);
339                             }
340                             Err(()) => cx.error_spanned_by(
341                                 s,
342                                 format!(
343                                     "unknown rename rule for #[serde(rename_all = {:?})]",
344                                     s.value(),
345                                 ),
346                             ),
347                         }
348                     }
349                 }
350 
351                 // Parse `#[serde(rename_all(serialize = "foo", deserialize = "bar"))]`
352                 Meta(List(m)) if m.path == RENAME_ALL => {
353                     if let Ok((ser, de)) = get_renames(cx, &m.nested) {
354                         if let Some(ser) = ser {
355                             match RenameRule::from_str(&ser.value()) {
356                                 Ok(rename_rule) => rename_all_ser_rule.set(&m.path, rename_rule),
357                                 Err(()) => cx.error_spanned_by(
358                                     ser,
359                                     format!(
360                                         "unknown rename rule for #[serde(rename_all = {:?})]",
361                                         ser.value(),
362                                     ),
363                                 ),
364                             }
365                         }
366                         if let Some(de) = de {
367                             match RenameRule::from_str(&de.value()) {
368                                 Ok(rename_rule) => rename_all_de_rule.set(&m.path, rename_rule),
369                                 Err(()) => cx.error_spanned_by(
370                                     de,
371                                     format!(
372                                         "unknown rename rule for #[serde(rename_all = {:?})]",
373                                         de.value(),
374                                     ),
375                                 ),
376                             }
377                         }
378                     }
379                 }
380 
381                 // Parse `#[serde(transparent)]`
382                 Meta(Path(word)) if word == TRANSPARENT => {
383                     transparent.set_true(word);
384                 }
385 
386                 // Parse `#[serde(deny_unknown_fields)]`
387                 Meta(Path(word)) if word == DENY_UNKNOWN_FIELDS => {
388                     deny_unknown_fields.set_true(word);
389                 }
390 
391                 // Parse `#[serde(default)]`
392                 Meta(Path(word)) if word == DEFAULT => match &item.data {
393                     syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
394                         syn::Fields::Named(_) => {
395                             default.set(word, Default::Default);
396                         }
397                         syn::Fields::Unnamed(_) | syn::Fields::Unit => cx.error_spanned_by(
398                             fields,
399                             "#[serde(default)] can only be used on structs with named fields",
400                         ),
401                     },
402                     syn::Data::Enum(syn::DataEnum { enum_token, .. }) => cx.error_spanned_by(
403                         enum_token,
404                         "#[serde(default)] can only be used on structs with named fields",
405                     ),
406                     syn::Data::Union(syn::DataUnion { union_token, .. }) => cx.error_spanned_by(
407                         union_token,
408                         "#[serde(default)] can only be used on structs with named fields",
409                     ),
410                 },
411 
412                 // Parse `#[serde(default = "...")]`
413                 Meta(NameValue(m)) if m.path == DEFAULT => {
414                     if let Ok(path) = parse_lit_into_expr_path(cx, DEFAULT, &m.lit) {
415                         match &item.data {
416                             syn::Data::Struct(syn::DataStruct { fields, .. }) => {
417                                 match fields {
418                                     syn::Fields::Named(_) => {
419                                         default.set(&m.path, Default::Path(path));
420                                     }
421                                     syn::Fields::Unnamed(_) | syn::Fields::Unit => cx
422                                         .error_spanned_by(
423                                             fields,
424                                             "#[serde(default = \"...\")] can only be used on structs with named fields",
425                                         ),
426                                 }
427                             }
428                             syn::Data::Enum(syn::DataEnum { enum_token, .. }) => cx
429                                 .error_spanned_by(
430                                     enum_token,
431                                     "#[serde(default = \"...\")] can only be used on structs with named fields",
432                                 ),
433                             syn::Data::Union(syn::DataUnion {
434                                 union_token, ..
435                             }) => cx.error_spanned_by(
436                                 union_token,
437                                 "#[serde(default = \"...\")] can only be used on structs with named fields",
438                             ),
439                         }
440                     }
441                 }
442 
443                 // Parse `#[serde(bound = "T: SomeBound")]`
444                 Meta(NameValue(m)) if m.path == BOUND => {
445                     if let Ok(where_predicates) = parse_lit_into_where(cx, BOUND, BOUND, &m.lit) {
446                         ser_bound.set(&m.path, where_predicates.clone());
447                         de_bound.set(&m.path, where_predicates);
448                     }
449                 }
450 
451                 // Parse `#[serde(bound(serialize = "...", deserialize = "..."))]`
452                 Meta(List(m)) if m.path == BOUND => {
453                     if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) {
454                         ser_bound.set_opt(&m.path, ser);
455                         de_bound.set_opt(&m.path, de);
456                     }
457                 }
458 
459                 // Parse `#[serde(untagged)]`
460                 Meta(Path(word)) if word == UNTAGGED => match item.data {
461                     syn::Data::Enum(_) => {
462                         untagged.set_true(word);
463                     }
464                     syn::Data::Struct(syn::DataStruct { struct_token, .. }) => {
465                         cx.error_spanned_by(
466                             struct_token,
467                             "#[serde(untagged)] can only be used on enums",
468                         );
469                     }
470                     syn::Data::Union(syn::DataUnion { union_token, .. }) => {
471                         cx.error_spanned_by(
472                             union_token,
473                             "#[serde(untagged)] can only be used on enums",
474                         );
475                     }
476                 },
477 
478                 // Parse `#[serde(tag = "type")]`
479                 Meta(NameValue(m)) if m.path == TAG => {
480                     if let Ok(s) = get_lit_str(cx, TAG, &m.lit) {
481                         match &item.data {
482                             syn::Data::Enum(_) => {
483                                 internal_tag.set(&m.path, s.value());
484                             }
485                             syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
486                                 syn::Fields::Named(_) => {
487                                     internal_tag.set(&m.path, s.value());
488                                 }
489                                 syn::Fields::Unnamed(_) | syn::Fields::Unit => {
490                                     cx.error_spanned_by(
491                                             fields,
492                                             "#[serde(tag = \"...\")] can only be used on enums and structs with named fields",
493                                         );
494                                 }
495                             },
496                             syn::Data::Union(syn::DataUnion { union_token, .. }) => {
497                                 cx.error_spanned_by(
498                                     union_token,
499                                     "#[serde(tag = \"...\")] can only be used on enums and structs with named fields",
500                                 );
501                             }
502                         }
503                     }
504                 }
505 
506                 // Parse `#[serde(content = "c")]`
507                 Meta(NameValue(m)) if m.path == CONTENT => {
508                     if let Ok(s) = get_lit_str(cx, CONTENT, &m.lit) {
509                         match &item.data {
510                             syn::Data::Enum(_) => {
511                                 content.set(&m.path, s.value());
512                             }
513                             syn::Data::Struct(syn::DataStruct { struct_token, .. }) => {
514                                 cx.error_spanned_by(
515                                     struct_token,
516                                     "#[serde(content = \"...\")] can only be used on enums",
517                                 );
518                             }
519                             syn::Data::Union(syn::DataUnion { union_token, .. }) => {
520                                 cx.error_spanned_by(
521                                     union_token,
522                                     "#[serde(content = \"...\")] can only be used on enums",
523                                 );
524                             }
525                         }
526                     }
527                 }
528 
529                 // Parse `#[serde(from = "Type")]
530                 Meta(NameValue(m)) if m.path == FROM => {
531                     if let Ok(from_ty) = parse_lit_into_ty(cx, FROM, &m.lit) {
532                         type_from.set_opt(&m.path, Some(from_ty));
533                     }
534                 }
535 
536                 // Parse `#[serde(try_from = "Type")]
537                 Meta(NameValue(m)) if m.path == TRY_FROM => {
538                     if let Ok(try_from_ty) = parse_lit_into_ty(cx, TRY_FROM, &m.lit) {
539                         type_try_from.set_opt(&m.path, Some(try_from_ty));
540                     }
541                 }
542 
543                 // Parse `#[serde(into = "Type")]
544                 Meta(NameValue(m)) if m.path == INTO => {
545                     if let Ok(into_ty) = parse_lit_into_ty(cx, INTO, &m.lit) {
546                         type_into.set_opt(&m.path, Some(into_ty));
547                     }
548                 }
549 
550                 // Parse `#[serde(remote = "...")]`
551                 Meta(NameValue(m)) if m.path == REMOTE => {
552                     if let Ok(path) = parse_lit_into_path(cx, REMOTE, &m.lit) {
553                         if is_primitive_path(&path, "Self") {
554                             remote.set(&m.path, item.ident.clone().into());
555                         } else {
556                             remote.set(&m.path, path);
557                         }
558                     }
559                 }
560 
561                 // Parse `#[serde(field_identifier)]`
562                 Meta(Path(word)) if word == FIELD_IDENTIFIER => {
563                     field_identifier.set_true(word);
564                 }
565 
566                 // Parse `#[serde(variant_identifier)]`
567                 Meta(Path(word)) if word == VARIANT_IDENTIFIER => {
568                     variant_identifier.set_true(word);
569                 }
570 
571                 // Parse `#[serde(crate = "foo")]`
572                 Meta(NameValue(m)) if m.path == CRATE => {
573                     if let Ok(path) = parse_lit_into_path(cx, CRATE, &m.lit) {
574                         serde_path.set(&m.path, path)
575                     }
576                 }
577 
578                 Meta(meta_item) => {
579                     let path = meta_item
580                         .path()
581                         .into_token_stream()
582                         .to_string()
583                         .replace(' ', "");
584                     cx.error_spanned_by(
585                         meta_item.path(),
586                         format!("unknown serde container attribute `{}`", path),
587                     );
588                 }
589 
590                 Lit(lit) => {
591                     cx.error_spanned_by(lit, "unexpected literal in serde container attribute");
592                 }
593             }
594         }
595 
596         let mut is_packed = false;
597         for attr in &item.attrs {
598             if attr.path.is_ident("repr") {
599                 let _ = attr.parse_args_with(|input: ParseStream| {
600                     is_packed |= input.parse::<Ident>()? == "packed";
601                     Ok(())
602                 });
603             }
604         }
605 
606         Container {
607             name: Name::from_attrs(unraw(&item.ident), ser_name, de_name, None),
608             transparent: transparent.get(),
609             deny_unknown_fields: deny_unknown_fields.get(),
610             default: default.get().unwrap_or(Default::None),
611             rename_all_rules: RenameAllRules {
612                 serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None),
613                 deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None),
614             },
615             ser_bound: ser_bound.get(),
616             de_bound: de_bound.get(),
617             tag: decide_tag(cx, item, untagged, internal_tag, content),
618             type_from: type_from.get(),
619             type_try_from: type_try_from.get(),
620             type_into: type_into.get(),
621             remote: remote.get(),
622             identifier: decide_identifier(cx, item, field_identifier, variant_identifier),
623             has_flatten: false,
624             serde_path: serde_path.get(),
625             is_packed,
626         }
627     }
628 
name(&self) -> &Name629     pub fn name(&self) -> &Name {
630         &self.name
631     }
632 
rename_all_rules(&self) -> &RenameAllRules633     pub fn rename_all_rules(&self) -> &RenameAllRules {
634         &self.rename_all_rules
635     }
636 
transparent(&self) -> bool637     pub fn transparent(&self) -> bool {
638         self.transparent
639     }
640 
deny_unknown_fields(&self) -> bool641     pub fn deny_unknown_fields(&self) -> bool {
642         self.deny_unknown_fields
643     }
644 
default(&self) -> &Default645     pub fn default(&self) -> &Default {
646         &self.default
647     }
648 
ser_bound(&self) -> Option<&[syn::WherePredicate]>649     pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
650         self.ser_bound.as_ref().map(|vec| &vec[..])
651     }
652 
de_bound(&self) -> Option<&[syn::WherePredicate]>653     pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
654         self.de_bound.as_ref().map(|vec| &vec[..])
655     }
656 
tag(&self) -> &TagType657     pub fn tag(&self) -> &TagType {
658         &self.tag
659     }
660 
type_from(&self) -> Option<&syn::Type>661     pub fn type_from(&self) -> Option<&syn::Type> {
662         self.type_from.as_ref()
663     }
664 
type_try_from(&self) -> Option<&syn::Type>665     pub fn type_try_from(&self) -> Option<&syn::Type> {
666         self.type_try_from.as_ref()
667     }
668 
type_into(&self) -> Option<&syn::Type>669     pub fn type_into(&self) -> Option<&syn::Type> {
670         self.type_into.as_ref()
671     }
672 
remote(&self) -> Option<&syn::Path>673     pub fn remote(&self) -> Option<&syn::Path> {
674         self.remote.as_ref()
675     }
676 
is_packed(&self) -> bool677     pub fn is_packed(&self) -> bool {
678         self.is_packed
679     }
680 
identifier(&self) -> Identifier681     pub fn identifier(&self) -> Identifier {
682         self.identifier
683     }
684 
has_flatten(&self) -> bool685     pub fn has_flatten(&self) -> bool {
686         self.has_flatten
687     }
688 
mark_has_flatten(&mut self)689     pub fn mark_has_flatten(&mut self) {
690         self.has_flatten = true;
691     }
692 
custom_serde_path(&self) -> Option<&syn::Path>693     pub fn custom_serde_path(&self) -> Option<&syn::Path> {
694         self.serde_path.as_ref()
695     }
696 
serde_path(&self) -> Cow<syn::Path>697     pub fn serde_path(&self) -> Cow<syn::Path> {
698         self.custom_serde_path()
699             .map_or_else(|| Cow::Owned(parse_quote!(_serde)), Cow::Borrowed)
700     }
701 }
702 
decide_tag( cx: &Ctxt, item: &syn::DeriveInput, untagged: BoolAttr, internal_tag: Attr<String>, content: Attr<String>, ) -> TagType703 fn decide_tag(
704     cx: &Ctxt,
705     item: &syn::DeriveInput,
706     untagged: BoolAttr,
707     internal_tag: Attr<String>,
708     content: Attr<String>,
709 ) -> TagType {
710     match (
711         untagged.0.get_with_tokens(),
712         internal_tag.get_with_tokens(),
713         content.get_with_tokens(),
714     ) {
715         (None, None, None) => TagType::External,
716         (Some(_), None, None) => TagType::None,
717         (None, Some((_, tag)), None) => {
718             // Check that there are no tuple variants.
719             if let syn::Data::Enum(data) = &item.data {
720                 for variant in &data.variants {
721                     match &variant.fields {
722                         syn::Fields::Named(_) | syn::Fields::Unit => {}
723                         syn::Fields::Unnamed(fields) => {
724                             if fields.unnamed.len() != 1 {
725                                 cx.error_spanned_by(
726                                     variant,
727                                     "#[serde(tag = \"...\")] cannot be used with tuple variants",
728                                 );
729                                 break;
730                             }
731                         }
732                     }
733                 }
734             }
735             TagType::Internal { tag }
736         }
737         (Some((untagged_tokens, _)), Some((tag_tokens, _)), None) => {
738             cx.error_spanned_by(
739                 untagged_tokens,
740                 "enum cannot be both untagged and internally tagged",
741             );
742             cx.error_spanned_by(
743                 tag_tokens,
744                 "enum cannot be both untagged and internally tagged",
745             );
746             TagType::External // doesn't matter, will error
747         }
748         (None, None, Some((content_tokens, _))) => {
749             cx.error_spanned_by(
750                 content_tokens,
751                 "#[serde(tag = \"...\", content = \"...\")] must be used together",
752             );
753             TagType::External
754         }
755         (Some((untagged_tokens, _)), None, Some((content_tokens, _))) => {
756             cx.error_spanned_by(
757                 untagged_tokens,
758                 "untagged enum cannot have #[serde(content = \"...\")]",
759             );
760             cx.error_spanned_by(
761                 content_tokens,
762                 "untagged enum cannot have #[serde(content = \"...\")]",
763             );
764             TagType::External
765         }
766         (None, Some((_, tag)), Some((_, content))) => TagType::Adjacent { tag, content },
767         (Some((untagged_tokens, _)), Some((tag_tokens, _)), Some((content_tokens, _))) => {
768             cx.error_spanned_by(
769                 untagged_tokens,
770                 "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]",
771             );
772             cx.error_spanned_by(
773                 tag_tokens,
774                 "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]",
775             );
776             cx.error_spanned_by(
777                 content_tokens,
778                 "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]",
779             );
780             TagType::External
781         }
782     }
783 }
784 
decide_identifier( cx: &Ctxt, item: &syn::DeriveInput, field_identifier: BoolAttr, variant_identifier: BoolAttr, ) -> Identifier785 fn decide_identifier(
786     cx: &Ctxt,
787     item: &syn::DeriveInput,
788     field_identifier: BoolAttr,
789     variant_identifier: BoolAttr,
790 ) -> Identifier {
791     match (
792         &item.data,
793         field_identifier.0.get_with_tokens(),
794         variant_identifier.0.get_with_tokens(),
795     ) {
796         (_, None, None) => Identifier::No,
797         (_, Some((field_identifier_tokens, _)), Some((variant_identifier_tokens, _))) => {
798             cx.error_spanned_by(
799                 field_identifier_tokens,
800                 "#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set",
801             );
802             cx.error_spanned_by(
803                 variant_identifier_tokens,
804                 "#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set",
805             );
806             Identifier::No
807         }
808         (syn::Data::Enum(_), Some(_), None) => Identifier::Field,
809         (syn::Data::Enum(_), None, Some(_)) => Identifier::Variant,
810         (syn::Data::Struct(syn::DataStruct { struct_token, .. }), Some(_), None) => {
811             cx.error_spanned_by(
812                 struct_token,
813                 "#[serde(field_identifier)] can only be used on an enum",
814             );
815             Identifier::No
816         }
817         (syn::Data::Union(syn::DataUnion { union_token, .. }), Some(_), None) => {
818             cx.error_spanned_by(
819                 union_token,
820                 "#[serde(field_identifier)] can only be used on an enum",
821             );
822             Identifier::No
823         }
824         (syn::Data::Struct(syn::DataStruct { struct_token, .. }), None, Some(_)) => {
825             cx.error_spanned_by(
826                 struct_token,
827                 "#[serde(variant_identifier)] can only be used on an enum",
828             );
829             Identifier::No
830         }
831         (syn::Data::Union(syn::DataUnion { union_token, .. }), None, Some(_)) => {
832             cx.error_spanned_by(
833                 union_token,
834                 "#[serde(variant_identifier)] can only be used on an enum",
835             );
836             Identifier::No
837         }
838     }
839 }
840 
841 /// Represents variant attribute information
842 pub struct Variant {
843     name: Name,
844     rename_all_rules: RenameAllRules,
845     ser_bound: Option<Vec<syn::WherePredicate>>,
846     de_bound: Option<Vec<syn::WherePredicate>>,
847     skip_deserializing: bool,
848     skip_serializing: bool,
849     other: bool,
850     serialize_with: Option<syn::ExprPath>,
851     deserialize_with: Option<syn::ExprPath>,
852     borrow: Option<syn::Meta>,
853 }
854 
855 impl Variant {
from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self856     pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self {
857         let mut ser_name = Attr::none(cx, RENAME);
858         let mut de_name = Attr::none(cx, RENAME);
859         let mut de_aliases = VecAttr::none(cx, RENAME);
860         let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING);
861         let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING);
862         let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL);
863         let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL);
864         let mut ser_bound = Attr::none(cx, BOUND);
865         let mut de_bound = Attr::none(cx, BOUND);
866         let mut other = BoolAttr::none(cx, OTHER);
867         let mut serialize_with = Attr::none(cx, SERIALIZE_WITH);
868         let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH);
869         let mut borrow = Attr::none(cx, BORROW);
870 
871         for meta_item in variant
872             .attrs
873             .iter()
874             .flat_map(|attr| get_serde_meta_items(cx, attr))
875             .flatten()
876         {
877             match &meta_item {
878                 // Parse `#[serde(rename = "foo")]`
879                 Meta(NameValue(m)) if m.path == RENAME => {
880                     if let Ok(s) = get_lit_str(cx, RENAME, &m.lit) {
881                         ser_name.set(&m.path, s.value());
882                         de_name.set_if_none(s.value());
883                         de_aliases.insert(&m.path, s.value());
884                     }
885                 }
886 
887                 // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]`
888                 Meta(List(m)) if m.path == RENAME => {
889                     if let Ok((ser, de)) = get_multiple_renames(cx, &m.nested) {
890                         ser_name.set_opt(&m.path, ser.map(syn::LitStr::value));
891                         for de_value in de {
892                             de_name.set_if_none(de_value.value());
893                             de_aliases.insert(&m.path, de_value.value());
894                         }
895                     }
896                 }
897 
898                 // Parse `#[serde(alias = "foo")]`
899                 Meta(NameValue(m)) if m.path == ALIAS => {
900                     if let Ok(s) = get_lit_str(cx, ALIAS, &m.lit) {
901                         de_aliases.insert(&m.path, s.value());
902                     }
903                 }
904 
905                 // Parse `#[serde(rename_all = "foo")]`
906                 Meta(NameValue(m)) if m.path == RENAME_ALL => {
907                     if let Ok(s) = get_lit_str(cx, RENAME_ALL, &m.lit) {
908                         match RenameRule::from_str(&s.value()) {
909                             Ok(rename_rule) => {
910                                 rename_all_ser_rule.set(&m.path, rename_rule);
911                                 rename_all_de_rule.set(&m.path, rename_rule);
912                             }
913                             Err(()) => cx.error_spanned_by(
914                                 s,
915                                 format!(
916                                     "unknown rename rule for #[serde(rename_all = {:?})]",
917                                     s.value()
918                                 ),
919                             ),
920                         }
921                     }
922                 }
923 
924                 // Parse `#[serde(rename_all(serialize = "foo", deserialize = "bar"))]`
925                 Meta(List(m)) if m.path == RENAME_ALL => {
926                     if let Ok((ser, de)) = get_renames(cx, &m.nested) {
927                         if let Some(ser) = ser {
928                             match RenameRule::from_str(&ser.value()) {
929                                 Ok(rename_rule) => rename_all_ser_rule.set(&m.path, rename_rule),
930                                 Err(()) => cx.error_spanned_by(
931                                     ser,
932                                     format!(
933                                         "unknown rename rule for #[serde(rename_all = {:?})]",
934                                         ser.value(),
935                                     ),
936                                 ),
937                             }
938                         }
939                         if let Some(de) = de {
940                             match RenameRule::from_str(&de.value()) {
941                                 Ok(rename_rule) => rename_all_de_rule.set(&m.path, rename_rule),
942                                 Err(()) => cx.error_spanned_by(
943                                     de,
944                                     format!(
945                                         "unknown rename rule for #[serde(rename_all = {:?})]",
946                                         de.value(),
947                                     ),
948                                 ),
949                             }
950                         }
951                     }
952                 }
953 
954                 // Parse `#[serde(skip)]`
955                 Meta(Path(word)) if word == SKIP => {
956                     skip_serializing.set_true(word);
957                     skip_deserializing.set_true(word);
958                 }
959 
960                 // Parse `#[serde(skip_deserializing)]`
961                 Meta(Path(word)) if word == SKIP_DESERIALIZING => {
962                     skip_deserializing.set_true(word);
963                 }
964 
965                 // Parse `#[serde(skip_serializing)]`
966                 Meta(Path(word)) if word == SKIP_SERIALIZING => {
967                     skip_serializing.set_true(word);
968                 }
969 
970                 // Parse `#[serde(other)]`
971                 Meta(Path(word)) if word == OTHER => {
972                     other.set_true(word);
973                 }
974 
975                 // Parse `#[serde(bound = "T: SomeBound")]`
976                 Meta(NameValue(m)) if m.path == BOUND => {
977                     if let Ok(where_predicates) = parse_lit_into_where(cx, BOUND, BOUND, &m.lit) {
978                         ser_bound.set(&m.path, where_predicates.clone());
979                         de_bound.set(&m.path, where_predicates);
980                     }
981                 }
982 
983                 // Parse `#[serde(bound(serialize = "...", deserialize = "..."))]`
984                 Meta(List(m)) if m.path == BOUND => {
985                     if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) {
986                         ser_bound.set_opt(&m.path, ser);
987                         de_bound.set_opt(&m.path, de);
988                     }
989                 }
990 
991                 // Parse `#[serde(with = "...")]`
992                 Meta(NameValue(m)) if m.path == WITH => {
993                     if let Ok(path) = parse_lit_into_expr_path(cx, WITH, &m.lit) {
994                         let mut ser_path = path.clone();
995                         ser_path
996                             .path
997                             .segments
998                             .push(Ident::new("serialize", Span::call_site()).into());
999                         serialize_with.set(&m.path, ser_path);
1000                         let mut de_path = path;
1001                         de_path
1002                             .path
1003                             .segments
1004                             .push(Ident::new("deserialize", Span::call_site()).into());
1005                         deserialize_with.set(&m.path, de_path);
1006                     }
1007                 }
1008 
1009                 // Parse `#[serde(serialize_with = "...")]`
1010                 Meta(NameValue(m)) if m.path == SERIALIZE_WITH => {
1011                     if let Ok(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &m.lit) {
1012                         serialize_with.set(&m.path, path);
1013                     }
1014                 }
1015 
1016                 // Parse `#[serde(deserialize_with = "...")]`
1017                 Meta(NameValue(m)) if m.path == DESERIALIZE_WITH => {
1018                     if let Ok(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &m.lit) {
1019                         deserialize_with.set(&m.path, path);
1020                     }
1021                 }
1022 
1023                 // Defer `#[serde(borrow)]` and `#[serde(borrow = "'a + 'b")]`
1024                 Meta(m) if m.path() == BORROW => match &variant.fields {
1025                     syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
1026                         borrow.set(m.path(), m.clone());
1027                     }
1028                     _ => {
1029                         cx.error_spanned_by(
1030                             variant,
1031                             "#[serde(borrow)] may only be used on newtype variants",
1032                         );
1033                     }
1034                 },
1035 
1036                 Meta(meta_item) => {
1037                     let path = meta_item
1038                         .path()
1039                         .into_token_stream()
1040                         .to_string()
1041                         .replace(' ', "");
1042                     cx.error_spanned_by(
1043                         meta_item.path(),
1044                         format!("unknown serde variant attribute `{}`", path),
1045                     );
1046                 }
1047 
1048                 Lit(lit) => {
1049                     cx.error_spanned_by(lit, "unexpected literal in serde variant attribute");
1050                 }
1051             }
1052         }
1053 
1054         Variant {
1055             name: Name::from_attrs(unraw(&variant.ident), ser_name, de_name, Some(de_aliases)),
1056             rename_all_rules: RenameAllRules {
1057                 serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None),
1058                 deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None),
1059             },
1060             ser_bound: ser_bound.get(),
1061             de_bound: de_bound.get(),
1062             skip_deserializing: skip_deserializing.get(),
1063             skip_serializing: skip_serializing.get(),
1064             other: other.get(),
1065             serialize_with: serialize_with.get(),
1066             deserialize_with: deserialize_with.get(),
1067             borrow: borrow.get(),
1068         }
1069     }
1070 
name(&self) -> &Name1071     pub fn name(&self) -> &Name {
1072         &self.name
1073     }
1074 
aliases(&self) -> Vec<String>1075     pub fn aliases(&self) -> Vec<String> {
1076         self.name.deserialize_aliases()
1077     }
1078 
rename_by_rules(&mut self, rules: &RenameAllRules)1079     pub fn rename_by_rules(&mut self, rules: &RenameAllRules) {
1080         if !self.name.serialize_renamed {
1081             self.name.serialize = rules.serialize.apply_to_variant(&self.name.serialize);
1082         }
1083         if !self.name.deserialize_renamed {
1084             self.name.deserialize = rules.deserialize.apply_to_variant(&self.name.deserialize);
1085         }
1086     }
1087 
rename_all_rules(&self) -> &RenameAllRules1088     pub fn rename_all_rules(&self) -> &RenameAllRules {
1089         &self.rename_all_rules
1090     }
1091 
ser_bound(&self) -> Option<&[syn::WherePredicate]>1092     pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
1093         self.ser_bound.as_ref().map(|vec| &vec[..])
1094     }
1095 
de_bound(&self) -> Option<&[syn::WherePredicate]>1096     pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
1097         self.de_bound.as_ref().map(|vec| &vec[..])
1098     }
1099 
skip_deserializing(&self) -> bool1100     pub fn skip_deserializing(&self) -> bool {
1101         self.skip_deserializing
1102     }
1103 
skip_serializing(&self) -> bool1104     pub fn skip_serializing(&self) -> bool {
1105         self.skip_serializing
1106     }
1107 
other(&self) -> bool1108     pub fn other(&self) -> bool {
1109         self.other
1110     }
1111 
serialize_with(&self) -> Option<&syn::ExprPath>1112     pub fn serialize_with(&self) -> Option<&syn::ExprPath> {
1113         self.serialize_with.as_ref()
1114     }
1115 
deserialize_with(&self) -> Option<&syn::ExprPath>1116     pub fn deserialize_with(&self) -> Option<&syn::ExprPath> {
1117         self.deserialize_with.as_ref()
1118     }
1119 }
1120 
1121 /// Represents field attribute information
1122 pub struct Field {
1123     name: Name,
1124     skip_serializing: bool,
1125     skip_deserializing: bool,
1126     skip_serializing_if: Option<syn::ExprPath>,
1127     default: Default,
1128     serialize_with: Option<syn::ExprPath>,
1129     deserialize_with: Option<syn::ExprPath>,
1130     ser_bound: Option<Vec<syn::WherePredicate>>,
1131     de_bound: Option<Vec<syn::WherePredicate>>,
1132     borrowed_lifetimes: BTreeSet<syn::Lifetime>,
1133     getter: Option<syn::ExprPath>,
1134     flatten: bool,
1135     transparent: bool,
1136 }
1137 
1138 /// Represents the default to use for a field when deserializing.
1139 pub enum Default {
1140     /// Field must always be specified because it does not have a default.
1141     None,
1142     /// The default is given by `std::default::Default::default()`.
1143     Default,
1144     /// The default is given by this function.
1145     Path(syn::ExprPath),
1146 }
1147 
1148 impl Default {
is_none(&self) -> bool1149     pub fn is_none(&self) -> bool {
1150         match self {
1151             Default::None => true,
1152             Default::Default | Default::Path(_) => false,
1153         }
1154     }
1155 }
1156 
1157 impl Field {
1158     /// Extract out the `#[serde(...)]` attributes from a struct field.
from_ast( cx: &Ctxt, index: usize, field: &syn::Field, attrs: Option<&Variant>, container_default: &Default, ) -> Self1159     pub fn from_ast(
1160         cx: &Ctxt,
1161         index: usize,
1162         field: &syn::Field,
1163         attrs: Option<&Variant>,
1164         container_default: &Default,
1165     ) -> Self {
1166         let mut ser_name = Attr::none(cx, RENAME);
1167         let mut de_name = Attr::none(cx, RENAME);
1168         let mut de_aliases = VecAttr::none(cx, RENAME);
1169         let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING);
1170         let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING);
1171         let mut skip_serializing_if = Attr::none(cx, SKIP_SERIALIZING_IF);
1172         let mut default = Attr::none(cx, DEFAULT);
1173         let mut serialize_with = Attr::none(cx, SERIALIZE_WITH);
1174         let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH);
1175         let mut ser_bound = Attr::none(cx, BOUND);
1176         let mut de_bound = Attr::none(cx, BOUND);
1177         let mut borrowed_lifetimes = Attr::none(cx, BORROW);
1178         let mut getter = Attr::none(cx, GETTER);
1179         let mut flatten = BoolAttr::none(cx, FLATTEN);
1180 
1181         let ident = match &field.ident {
1182             Some(ident) => unraw(ident),
1183             None => index.to_string(),
1184         };
1185 
1186         let variant_borrow = attrs
1187             .and_then(|variant| variant.borrow.as_ref())
1188             .map(|borrow| Meta(borrow.clone()));
1189 
1190         for meta_item in field
1191             .attrs
1192             .iter()
1193             .flat_map(|attr| get_serde_meta_items(cx, attr))
1194             .flatten()
1195             .chain(variant_borrow)
1196         {
1197             match &meta_item {
1198                 // Parse `#[serde(rename = "foo")]`
1199                 Meta(NameValue(m)) if m.path == RENAME => {
1200                     if let Ok(s) = get_lit_str(cx, RENAME, &m.lit) {
1201                         ser_name.set(&m.path, s.value());
1202                         de_name.set_if_none(s.value());
1203                         de_aliases.insert(&m.path, s.value());
1204                     }
1205                 }
1206 
1207                 // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]`
1208                 Meta(List(m)) if m.path == RENAME => {
1209                     if let Ok((ser, de)) = get_multiple_renames(cx, &m.nested) {
1210                         ser_name.set_opt(&m.path, ser.map(syn::LitStr::value));
1211                         for de_value in de {
1212                             de_name.set_if_none(de_value.value());
1213                             de_aliases.insert(&m.path, de_value.value());
1214                         }
1215                     }
1216                 }
1217 
1218                 // Parse `#[serde(alias = "foo")]`
1219                 Meta(NameValue(m)) if m.path == ALIAS => {
1220                     if let Ok(s) = get_lit_str(cx, ALIAS, &m.lit) {
1221                         de_aliases.insert(&m.path, s.value());
1222                     }
1223                 }
1224 
1225                 // Parse `#[serde(default)]`
1226                 Meta(Path(word)) if word == DEFAULT => {
1227                     default.set(word, Default::Default);
1228                 }
1229 
1230                 // Parse `#[serde(default = "...")]`
1231                 Meta(NameValue(m)) if m.path == DEFAULT => {
1232                     if let Ok(path) = parse_lit_into_expr_path(cx, DEFAULT, &m.lit) {
1233                         default.set(&m.path, Default::Path(path));
1234                     }
1235                 }
1236 
1237                 // Parse `#[serde(skip_serializing)]`
1238                 Meta(Path(word)) if word == SKIP_SERIALIZING => {
1239                     skip_serializing.set_true(word);
1240                 }
1241 
1242                 // Parse `#[serde(skip_deserializing)]`
1243                 Meta(Path(word)) if word == SKIP_DESERIALIZING => {
1244                     skip_deserializing.set_true(word);
1245                 }
1246 
1247                 // Parse `#[serde(skip)]`
1248                 Meta(Path(word)) if word == SKIP => {
1249                     skip_serializing.set_true(word);
1250                     skip_deserializing.set_true(word);
1251                 }
1252 
1253                 // Parse `#[serde(skip_serializing_if = "...")]`
1254                 Meta(NameValue(m)) if m.path == SKIP_SERIALIZING_IF => {
1255                     if let Ok(path) = parse_lit_into_expr_path(cx, SKIP_SERIALIZING_IF, &m.lit) {
1256                         skip_serializing_if.set(&m.path, path);
1257                     }
1258                 }
1259 
1260                 // Parse `#[serde(serialize_with = "...")]`
1261                 Meta(NameValue(m)) if m.path == SERIALIZE_WITH => {
1262                     if let Ok(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &m.lit) {
1263                         serialize_with.set(&m.path, path);
1264                     }
1265                 }
1266 
1267                 // Parse `#[serde(deserialize_with = "...")]`
1268                 Meta(NameValue(m)) if m.path == DESERIALIZE_WITH => {
1269                     if let Ok(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &m.lit) {
1270                         deserialize_with.set(&m.path, path);
1271                     }
1272                 }
1273 
1274                 // Parse `#[serde(with = "...")]`
1275                 Meta(NameValue(m)) if m.path == WITH => {
1276                     if let Ok(path) = parse_lit_into_expr_path(cx, WITH, &m.lit) {
1277                         let mut ser_path = path.clone();
1278                         ser_path
1279                             .path
1280                             .segments
1281                             .push(Ident::new("serialize", Span::call_site()).into());
1282                         serialize_with.set(&m.path, ser_path);
1283                         let mut de_path = path;
1284                         de_path
1285                             .path
1286                             .segments
1287                             .push(Ident::new("deserialize", Span::call_site()).into());
1288                         deserialize_with.set(&m.path, de_path);
1289                     }
1290                 }
1291 
1292                 // Parse `#[serde(bound = "T: SomeBound")]`
1293                 Meta(NameValue(m)) if m.path == BOUND => {
1294                     if let Ok(where_predicates) = parse_lit_into_where(cx, BOUND, BOUND, &m.lit) {
1295                         ser_bound.set(&m.path, where_predicates.clone());
1296                         de_bound.set(&m.path, where_predicates);
1297                     }
1298                 }
1299 
1300                 // Parse `#[serde(bound(serialize = "...", deserialize = "..."))]`
1301                 Meta(List(m)) if m.path == BOUND => {
1302                     if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) {
1303                         ser_bound.set_opt(&m.path, ser);
1304                         de_bound.set_opt(&m.path, de);
1305                     }
1306                 }
1307 
1308                 // Parse `#[serde(borrow)]`
1309                 Meta(Path(word)) if word == BORROW => {
1310                     if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, field) {
1311                         borrowed_lifetimes.set(word, borrowable);
1312                     }
1313                 }
1314 
1315                 // Parse `#[serde(borrow = "'a + 'b")]`
1316                 Meta(NameValue(m)) if m.path == BORROW => {
1317                     if let Ok(lifetimes) = parse_lit_into_lifetimes(cx, BORROW, &m.lit) {
1318                         if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, field) {
1319                             for lifetime in &lifetimes {
1320                                 if !borrowable.contains(lifetime) {
1321                                     cx.error_spanned_by(
1322                                         field,
1323                                         format!(
1324                                             "field `{}` does not have lifetime {}",
1325                                             ident, lifetime
1326                                         ),
1327                                     );
1328                                 }
1329                             }
1330                             borrowed_lifetimes.set(&m.path, lifetimes);
1331                         }
1332                     }
1333                 }
1334 
1335                 // Parse `#[serde(getter = "...")]`
1336                 Meta(NameValue(m)) if m.path == GETTER => {
1337                     if let Ok(path) = parse_lit_into_expr_path(cx, GETTER, &m.lit) {
1338                         getter.set(&m.path, path);
1339                     }
1340                 }
1341 
1342                 // Parse `#[serde(flatten)]`
1343                 Meta(Path(word)) if word == FLATTEN => {
1344                     flatten.set_true(word);
1345                 }
1346 
1347                 Meta(meta_item) => {
1348                     let path = meta_item
1349                         .path()
1350                         .into_token_stream()
1351                         .to_string()
1352                         .replace(' ', "");
1353                     cx.error_spanned_by(
1354                         meta_item.path(),
1355                         format!("unknown serde field attribute `{}`", path),
1356                     );
1357                 }
1358 
1359                 Lit(lit) => {
1360                     cx.error_spanned_by(lit, "unexpected literal in serde field attribute");
1361                 }
1362             }
1363         }
1364 
1365         // Is skip_deserializing, initialize the field to Default::default() unless a
1366         // different default is specified by `#[serde(default = "...")]` on
1367         // ourselves or our container (e.g. the struct we are in).
1368         if let Default::None = *container_default {
1369             if skip_deserializing.0.value.is_some() {
1370                 default.set_if_none(Default::Default);
1371             }
1372         }
1373 
1374         let mut borrowed_lifetimes = borrowed_lifetimes.get().unwrap_or_default();
1375         if !borrowed_lifetimes.is_empty() {
1376             // Cow<str> and Cow<[u8]> never borrow by default:
1377             //
1378             //     impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>
1379             //
1380             // A #[serde(borrow)] attribute enables borrowing that corresponds
1381             // roughly to these impls:
1382             //
1383             //     impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str>
1384             //     impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]>
1385             if is_cow(&field.ty, is_str) {
1386                 let mut path = syn::Path {
1387                     leading_colon: None,
1388                     segments: Punctuated::new(),
1389                 };
1390                 let span = Span::call_site();
1391                 path.segments.push(Ident::new("_serde", span).into());
1392                 path.segments.push(Ident::new("private", span).into());
1393                 path.segments.push(Ident::new("de", span).into());
1394                 path.segments
1395                     .push(Ident::new("borrow_cow_str", span).into());
1396                 let expr = syn::ExprPath {
1397                     attrs: Vec::new(),
1398                     qself: None,
1399                     path,
1400                 };
1401                 deserialize_with.set_if_none(expr);
1402             } else if is_cow(&field.ty, is_slice_u8) {
1403                 let mut path = syn::Path {
1404                     leading_colon: None,
1405                     segments: Punctuated::new(),
1406                 };
1407                 let span = Span::call_site();
1408                 path.segments.push(Ident::new("_serde", span).into());
1409                 path.segments.push(Ident::new("private", span).into());
1410                 path.segments.push(Ident::new("de", span).into());
1411                 path.segments
1412                     .push(Ident::new("borrow_cow_bytes", span).into());
1413                 let expr = syn::ExprPath {
1414                     attrs: Vec::new(),
1415                     qself: None,
1416                     path,
1417                 };
1418                 deserialize_with.set_if_none(expr);
1419             }
1420         } else if is_implicitly_borrowed(&field.ty) {
1421             // Types &str and &[u8] are always implicitly borrowed. No need for
1422             // a #[serde(borrow)].
1423             collect_lifetimes(&field.ty, &mut borrowed_lifetimes);
1424         }
1425 
1426         Field {
1427             name: Name::from_attrs(ident, ser_name, de_name, Some(de_aliases)),
1428             skip_serializing: skip_serializing.get(),
1429             skip_deserializing: skip_deserializing.get(),
1430             skip_serializing_if: skip_serializing_if.get(),
1431             default: default.get().unwrap_or(Default::None),
1432             serialize_with: serialize_with.get(),
1433             deserialize_with: deserialize_with.get(),
1434             ser_bound: ser_bound.get(),
1435             de_bound: de_bound.get(),
1436             borrowed_lifetimes,
1437             getter: getter.get(),
1438             flatten: flatten.get(),
1439             transparent: false,
1440         }
1441     }
1442 
name(&self) -> &Name1443     pub fn name(&self) -> &Name {
1444         &self.name
1445     }
1446 
aliases(&self) -> Vec<String>1447     pub fn aliases(&self) -> Vec<String> {
1448         self.name.deserialize_aliases()
1449     }
1450 
rename_by_rules(&mut self, rules: &RenameAllRules)1451     pub fn rename_by_rules(&mut self, rules: &RenameAllRules) {
1452         if !self.name.serialize_renamed {
1453             self.name.serialize = rules.serialize.apply_to_field(&self.name.serialize);
1454         }
1455         if !self.name.deserialize_renamed {
1456             self.name.deserialize = rules.deserialize.apply_to_field(&self.name.deserialize);
1457         }
1458     }
1459 
skip_serializing(&self) -> bool1460     pub fn skip_serializing(&self) -> bool {
1461         self.skip_serializing
1462     }
1463 
skip_deserializing(&self) -> bool1464     pub fn skip_deserializing(&self) -> bool {
1465         self.skip_deserializing
1466     }
1467 
skip_serializing_if(&self) -> Option<&syn::ExprPath>1468     pub fn skip_serializing_if(&self) -> Option<&syn::ExprPath> {
1469         self.skip_serializing_if.as_ref()
1470     }
1471 
default(&self) -> &Default1472     pub fn default(&self) -> &Default {
1473         &self.default
1474     }
1475 
serialize_with(&self) -> Option<&syn::ExprPath>1476     pub fn serialize_with(&self) -> Option<&syn::ExprPath> {
1477         self.serialize_with.as_ref()
1478     }
1479 
deserialize_with(&self) -> Option<&syn::ExprPath>1480     pub fn deserialize_with(&self) -> Option<&syn::ExprPath> {
1481         self.deserialize_with.as_ref()
1482     }
1483 
ser_bound(&self) -> Option<&[syn::WherePredicate]>1484     pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
1485         self.ser_bound.as_ref().map(|vec| &vec[..])
1486     }
1487 
de_bound(&self) -> Option<&[syn::WherePredicate]>1488     pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
1489         self.de_bound.as_ref().map(|vec| &vec[..])
1490     }
1491 
borrowed_lifetimes(&self) -> &BTreeSet<syn::Lifetime>1492     pub fn borrowed_lifetimes(&self) -> &BTreeSet<syn::Lifetime> {
1493         &self.borrowed_lifetimes
1494     }
1495 
getter(&self) -> Option<&syn::ExprPath>1496     pub fn getter(&self) -> Option<&syn::ExprPath> {
1497         self.getter.as_ref()
1498     }
1499 
flatten(&self) -> bool1500     pub fn flatten(&self) -> bool {
1501         self.flatten
1502     }
1503 
transparent(&self) -> bool1504     pub fn transparent(&self) -> bool {
1505         self.transparent
1506     }
1507 
mark_transparent(&mut self)1508     pub fn mark_transparent(&mut self) {
1509         self.transparent = true;
1510     }
1511 }
1512 
1513 type SerAndDe<T> = (Option<T>, Option<T>);
1514 
get_ser_and_de<'a, 'b, T, F>( cx: &'b Ctxt, attr_name: Symbol, metas: &'a Punctuated<syn::NestedMeta, Token![,]>, f: F, ) -> Result<(VecAttr<'b, T>, VecAttr<'b, T>), ()> where T: 'a, F: Fn(&Ctxt, Symbol, Symbol, &'a syn::Lit) -> Result<T, ()>,1515 fn get_ser_and_de<'a, 'b, T, F>(
1516     cx: &'b Ctxt,
1517     attr_name: Symbol,
1518     metas: &'a Punctuated<syn::NestedMeta, Token![,]>,
1519     f: F,
1520 ) -> Result<(VecAttr<'b, T>, VecAttr<'b, T>), ()>
1521 where
1522     T: 'a,
1523     F: Fn(&Ctxt, Symbol, Symbol, &'a syn::Lit) -> Result<T, ()>,
1524 {
1525     let mut ser_meta = VecAttr::none(cx, attr_name);
1526     let mut de_meta = VecAttr::none(cx, attr_name);
1527 
1528     for meta in metas {
1529         match meta {
1530             Meta(NameValue(meta)) if meta.path == SERIALIZE => {
1531                 if let Ok(v) = f(cx, attr_name, SERIALIZE, &meta.lit) {
1532                     ser_meta.insert(&meta.path, v);
1533                 }
1534             }
1535 
1536             Meta(NameValue(meta)) if meta.path == DESERIALIZE => {
1537                 if let Ok(v) = f(cx, attr_name, DESERIALIZE, &meta.lit) {
1538                     de_meta.insert(&meta.path, v);
1539                 }
1540             }
1541 
1542             _ => {
1543                 cx.error_spanned_by(
1544                     meta,
1545                     format!(
1546                         "malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`",
1547                         attr_name
1548                     ),
1549                 );
1550                 return Err(());
1551             }
1552         }
1553     }
1554 
1555     Ok((ser_meta, de_meta))
1556 }
1557 
get_renames<'a>( cx: &Ctxt, items: &'a Punctuated<syn::NestedMeta, Token![,]>, ) -> Result<SerAndDe<&'a syn::LitStr>, ()>1558 fn get_renames<'a>(
1559     cx: &Ctxt,
1560     items: &'a Punctuated<syn::NestedMeta, Token![,]>,
1561 ) -> Result<SerAndDe<&'a syn::LitStr>, ()> {
1562     let (ser, de) = get_ser_and_de(cx, RENAME, items, get_lit_str2)?;
1563     Ok((ser.at_most_one()?, de.at_most_one()?))
1564 }
1565 
get_multiple_renames<'a>( cx: &Ctxt, items: &'a Punctuated<syn::NestedMeta, Token![,]>, ) -> Result<(Option<&'a syn::LitStr>, Vec<&'a syn::LitStr>), ()>1566 fn get_multiple_renames<'a>(
1567     cx: &Ctxt,
1568     items: &'a Punctuated<syn::NestedMeta, Token![,]>,
1569 ) -> Result<(Option<&'a syn::LitStr>, Vec<&'a syn::LitStr>), ()> {
1570     let (ser, de) = get_ser_and_de(cx, RENAME, items, get_lit_str2)?;
1571     Ok((ser.at_most_one()?, de.get()))
1572 }
1573 
get_where_predicates( cx: &Ctxt, items: &Punctuated<syn::NestedMeta, Token![,]>, ) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()>1574 fn get_where_predicates(
1575     cx: &Ctxt,
1576     items: &Punctuated<syn::NestedMeta, Token![,]>,
1577 ) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
1578     let (ser, de) = get_ser_and_de(cx, BOUND, items, parse_lit_into_where)?;
1579     Ok((ser.at_most_one()?, de.at_most_one()?))
1580 }
1581 
get_serde_meta_items(cx: &Ctxt, attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()>1582 pub fn get_serde_meta_items(cx: &Ctxt, attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()> {
1583     if attr.path != SERDE {
1584         return Ok(Vec::new());
1585     }
1586 
1587     match attr.parse_meta() {
1588         Ok(List(meta)) => Ok(meta.nested.into_iter().collect()),
1589         Ok(other) => {
1590             cx.error_spanned_by(other, "expected #[serde(...)]");
1591             Err(())
1592         }
1593         Err(err) => {
1594             cx.syn_error(err);
1595             Err(())
1596         }
1597     }
1598 }
1599 
get_lit_str<'a>(cx: &Ctxt, attr_name: Symbol, lit: &'a syn::Lit) -> Result<&'a syn::LitStr, ()>1600 fn get_lit_str<'a>(cx: &Ctxt, attr_name: Symbol, lit: &'a syn::Lit) -> Result<&'a syn::LitStr, ()> {
1601     get_lit_str2(cx, attr_name, attr_name, lit)
1602 }
1603 
get_lit_str2<'a>( cx: &Ctxt, attr_name: Symbol, meta_item_name: Symbol, lit: &'a syn::Lit, ) -> Result<&'a syn::LitStr, ()>1604 fn get_lit_str2<'a>(
1605     cx: &Ctxt,
1606     attr_name: Symbol,
1607     meta_item_name: Symbol,
1608     lit: &'a syn::Lit,
1609 ) -> Result<&'a syn::LitStr, ()> {
1610     if let syn::Lit::Str(lit) = lit {
1611         Ok(lit)
1612     } else {
1613         cx.error_spanned_by(
1614             lit,
1615             format!(
1616                 "expected serde {} attribute to be a string: `{} = \"...\"`",
1617                 attr_name, meta_item_name
1618             ),
1619         );
1620         Err(())
1621     }
1622 }
1623 
parse_lit_into_path(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::Path, ()>1624 fn parse_lit_into_path(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::Path, ()> {
1625     let string = get_lit_str(cx, attr_name, lit)?;
1626     parse_lit_str(string).map_err(|_| {
1627         cx.error_spanned_by(lit, format!("failed to parse path: {:?}", string.value()))
1628     })
1629 }
1630 
parse_lit_into_expr_path( cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit, ) -> Result<syn::ExprPath, ()>1631 fn parse_lit_into_expr_path(
1632     cx: &Ctxt,
1633     attr_name: Symbol,
1634     lit: &syn::Lit,
1635 ) -> Result<syn::ExprPath, ()> {
1636     let string = get_lit_str(cx, attr_name, lit)?;
1637     parse_lit_str(string).map_err(|_| {
1638         cx.error_spanned_by(lit, format!("failed to parse path: {:?}", string.value()))
1639     })
1640 }
1641 
parse_lit_into_where( cx: &Ctxt, attr_name: Symbol, meta_item_name: Symbol, lit: &syn::Lit, ) -> Result<Vec<syn::WherePredicate>, ()>1642 fn parse_lit_into_where(
1643     cx: &Ctxt,
1644     attr_name: Symbol,
1645     meta_item_name: Symbol,
1646     lit: &syn::Lit,
1647 ) -> Result<Vec<syn::WherePredicate>, ()> {
1648     let string = get_lit_str2(cx, attr_name, meta_item_name, lit)?;
1649     if string.value().is_empty() {
1650         return Ok(Vec::new());
1651     }
1652 
1653     let where_string = syn::LitStr::new(&format!("where {}", string.value()), string.span());
1654 
1655     parse_lit_str::<syn::WhereClause>(&where_string)
1656         .map(|wh| wh.predicates.into_iter().collect())
1657         .map_err(|err| cx.error_spanned_by(lit, err))
1658 }
1659 
parse_lit_into_ty(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::Type, ()>1660 fn parse_lit_into_ty(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::Type, ()> {
1661     let string = get_lit_str(cx, attr_name, lit)?;
1662 
1663     parse_lit_str(string).map_err(|_| {
1664         cx.error_spanned_by(
1665             lit,
1666             format!("failed to parse type: {} = {:?}", attr_name, string.value()),
1667         )
1668     })
1669 }
1670 
1671 // Parses a string literal like "'a + 'b + 'c" containing a nonempty list of
1672 // lifetimes separated by `+`.
parse_lit_into_lifetimes( cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit, ) -> Result<BTreeSet<syn::Lifetime>, ()>1673 fn parse_lit_into_lifetimes(
1674     cx: &Ctxt,
1675     attr_name: Symbol,
1676     lit: &syn::Lit,
1677 ) -> Result<BTreeSet<syn::Lifetime>, ()> {
1678     let string = get_lit_str(cx, attr_name, lit)?;
1679     if string.value().is_empty() {
1680         cx.error_spanned_by(lit, "at least one lifetime must be borrowed");
1681         return Err(());
1682     }
1683 
1684     struct BorrowedLifetimes(Punctuated<syn::Lifetime, Token![+]>);
1685 
1686     impl Parse for BorrowedLifetimes {
1687         fn parse(input: ParseStream) -> parse::Result<Self> {
1688             Punctuated::parse_separated_nonempty(input).map(BorrowedLifetimes)
1689         }
1690     }
1691 
1692     if let Ok(BorrowedLifetimes(lifetimes)) = parse_lit_str(string) {
1693         let mut set = BTreeSet::new();
1694         for lifetime in lifetimes {
1695             if !set.insert(lifetime.clone()) {
1696                 cx.error_spanned_by(lit, format!("duplicate borrowed lifetime `{}`", lifetime));
1697             }
1698         }
1699         return Ok(set);
1700     }
1701 
1702     cx.error_spanned_by(
1703         lit,
1704         format!("failed to parse borrowed lifetimes: {:?}", string.value()),
1705     );
1706     Err(())
1707 }
1708 
is_implicitly_borrowed(ty: &syn::Type) -> bool1709 fn is_implicitly_borrowed(ty: &syn::Type) -> bool {
1710     is_implicitly_borrowed_reference(ty) || is_option(ty, is_implicitly_borrowed_reference)
1711 }
1712 
is_implicitly_borrowed_reference(ty: &syn::Type) -> bool1713 fn is_implicitly_borrowed_reference(ty: &syn::Type) -> bool {
1714     is_reference(ty, is_str) || is_reference(ty, is_slice_u8)
1715 }
1716 
1717 // Whether the type looks like it might be `std::borrow::Cow<T>` where elem="T".
1718 // This can have false negatives and false positives.
1719 //
1720 // False negative:
1721 //
1722 //     use std::borrow::Cow as Pig;
1723 //
1724 //     #[derive(Deserialize)]
1725 //     struct S<'a> {
1726 //         #[serde(borrow)]
1727 //         pig: Pig<'a, str>,
1728 //     }
1729 //
1730 // False positive:
1731 //
1732 //     type str = [i16];
1733 //
1734 //     #[derive(Deserialize)]
1735 //     struct S<'a> {
1736 //         #[serde(borrow)]
1737 //         cow: Cow<'a, str>,
1738 //     }
is_cow(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool1739 fn is_cow(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool {
1740     let path = match ungroup(ty) {
1741         syn::Type::Path(ty) => &ty.path,
1742         _ => {
1743             return false;
1744         }
1745     };
1746     let seg = match path.segments.last() {
1747         Some(seg) => seg,
1748         None => {
1749             return false;
1750         }
1751     };
1752     let args = match &seg.arguments {
1753         syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args,
1754         _ => {
1755             return false;
1756         }
1757     };
1758     seg.ident == "Cow"
1759         && args.len() == 2
1760         && match (&args[0], &args[1]) {
1761             (syn::GenericArgument::Lifetime(_), syn::GenericArgument::Type(arg)) => elem(arg),
1762             _ => false,
1763         }
1764 }
1765 
is_option(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool1766 fn is_option(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool {
1767     let path = match ungroup(ty) {
1768         syn::Type::Path(ty) => &ty.path,
1769         _ => {
1770             return false;
1771         }
1772     };
1773     let seg = match path.segments.last() {
1774         Some(seg) => seg,
1775         None => {
1776             return false;
1777         }
1778     };
1779     let args = match &seg.arguments {
1780         syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args,
1781         _ => {
1782             return false;
1783         }
1784     };
1785     seg.ident == "Option"
1786         && args.len() == 1
1787         && match &args[0] {
1788             syn::GenericArgument::Type(arg) => elem(arg),
1789             _ => false,
1790         }
1791 }
1792 
1793 // Whether the type looks like it might be `&T` where elem="T". This can have
1794 // false negatives and false positives.
1795 //
1796 // False negative:
1797 //
1798 //     type Yarn = str;
1799 //
1800 //     #[derive(Deserialize)]
1801 //     struct S<'a> {
1802 //         r: &'a Yarn,
1803 //     }
1804 //
1805 // False positive:
1806 //
1807 //     type str = [i16];
1808 //
1809 //     #[derive(Deserialize)]
1810 //     struct S<'a> {
1811 //         r: &'a str,
1812 //     }
is_reference(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool1813 fn is_reference(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool {
1814     match ungroup(ty) {
1815         syn::Type::Reference(ty) => ty.mutability.is_none() && elem(&ty.elem),
1816         _ => false,
1817     }
1818 }
1819 
is_str(ty: &syn::Type) -> bool1820 fn is_str(ty: &syn::Type) -> bool {
1821     is_primitive_type(ty, "str")
1822 }
1823 
is_slice_u8(ty: &syn::Type) -> bool1824 fn is_slice_u8(ty: &syn::Type) -> bool {
1825     match ungroup(ty) {
1826         syn::Type::Slice(ty) => is_primitive_type(&ty.elem, "u8"),
1827         _ => false,
1828     }
1829 }
1830 
is_primitive_type(ty: &syn::Type, primitive: &str) -> bool1831 fn is_primitive_type(ty: &syn::Type, primitive: &str) -> bool {
1832     match ungroup(ty) {
1833         syn::Type::Path(ty) => ty.qself.is_none() && is_primitive_path(&ty.path, primitive),
1834         _ => false,
1835     }
1836 }
1837 
is_primitive_path(path: &syn::Path, primitive: &str) -> bool1838 fn is_primitive_path(path: &syn::Path, primitive: &str) -> bool {
1839     path.leading_colon.is_none()
1840         && path.segments.len() == 1
1841         && path.segments[0].ident == primitive
1842         && path.segments[0].arguments.is_empty()
1843 }
1844 
1845 // All lifetimes that this type could borrow from a Deserializer.
1846 //
1847 // For example a type `S<'a, 'b>` could borrow `'a` and `'b`. On the other hand
1848 // a type `for<'a> fn(&'a str)` could not borrow `'a` from the Deserializer.
1849 //
1850 // This is used when there is an explicit or implicit `#[serde(borrow)]`
1851 // attribute on the field so there must be at least one borrowable lifetime.
borrowable_lifetimes( cx: &Ctxt, name: &str, field: &syn::Field, ) -> Result<BTreeSet<syn::Lifetime>, ()>1852 fn borrowable_lifetimes(
1853     cx: &Ctxt,
1854     name: &str,
1855     field: &syn::Field,
1856 ) -> Result<BTreeSet<syn::Lifetime>, ()> {
1857     let mut lifetimes = BTreeSet::new();
1858     collect_lifetimes(&field.ty, &mut lifetimes);
1859     if lifetimes.is_empty() {
1860         cx.error_spanned_by(
1861             field,
1862             format!("field `{}` has no lifetimes to borrow", name),
1863         );
1864         Err(())
1865     } else {
1866         Ok(lifetimes)
1867     }
1868 }
1869 
collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>)1870 fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>) {
1871     match ty {
1872         syn::Type::Slice(ty) => {
1873             collect_lifetimes(&ty.elem, out);
1874         }
1875         syn::Type::Array(ty) => {
1876             collect_lifetimes(&ty.elem, out);
1877         }
1878         syn::Type::Ptr(ty) => {
1879             collect_lifetimes(&ty.elem, out);
1880         }
1881         syn::Type::Reference(ty) => {
1882             out.extend(ty.lifetime.iter().cloned());
1883             collect_lifetimes(&ty.elem, out);
1884         }
1885         syn::Type::Tuple(ty) => {
1886             for elem in &ty.elems {
1887                 collect_lifetimes(elem, out);
1888             }
1889         }
1890         syn::Type::Path(ty) => {
1891             if let Some(qself) = &ty.qself {
1892                 collect_lifetimes(&qself.ty, out);
1893             }
1894             for seg in &ty.path.segments {
1895                 if let syn::PathArguments::AngleBracketed(bracketed) = &seg.arguments {
1896                     for arg in &bracketed.args {
1897                         match arg {
1898                             syn::GenericArgument::Lifetime(lifetime) => {
1899                                 out.insert(lifetime.clone());
1900                             }
1901                             syn::GenericArgument::Type(ty) => {
1902                                 collect_lifetimes(ty, out);
1903                             }
1904                             syn::GenericArgument::Binding(binding) => {
1905                                 collect_lifetimes(&binding.ty, out);
1906                             }
1907                             syn::GenericArgument::Constraint(_)
1908                             | syn::GenericArgument::Const(_) => {}
1909                         }
1910                     }
1911                 }
1912             }
1913         }
1914         syn::Type::Paren(ty) => {
1915             collect_lifetimes(&ty.elem, out);
1916         }
1917         syn::Type::Group(ty) => {
1918             collect_lifetimes(&ty.elem, out);
1919         }
1920         syn::Type::BareFn(_)
1921         | syn::Type::Never(_)
1922         | syn::Type::TraitObject(_)
1923         | syn::Type::ImplTrait(_)
1924         | syn::Type::Infer(_)
1925         | syn::Type::Macro(_)
1926         | syn::Type::Verbatim(_)
1927         | _ => {}
1928     }
1929 }
1930 
parse_lit_str<T>(s: &syn::LitStr) -> parse::Result<T> where T: Parse,1931 fn parse_lit_str<T>(s: &syn::LitStr) -> parse::Result<T>
1932 where
1933     T: Parse,
1934 {
1935     let tokens = spanned_tokens(s)?;
1936     syn::parse2(tokens)
1937 }
1938 
spanned_tokens(s: &syn::LitStr) -> parse::Result<TokenStream>1939 fn spanned_tokens(s: &syn::LitStr) -> parse::Result<TokenStream> {
1940     let stream = syn::parse_str(&s.value())?;
1941     Ok(respan_token_stream(stream, s.span()))
1942 }
1943 
respan_token_stream(stream: TokenStream, span: Span) -> TokenStream1944 fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream {
1945     stream
1946         .into_iter()
1947         .map(|token| respan_token_tree(token, span))
1948         .collect()
1949 }
1950 
respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree1951 fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree {
1952     if let TokenTree::Group(g) = &mut token {
1953         *g = Group::new(g.delimiter(), respan_token_stream(g.stream(), span));
1954     }
1955     token.set_span(span);
1956     token
1957 }
1958