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