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