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