serde_derive/internals/
attr.rs

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