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