1 use internals
::respan
::respan
;
2 use internals
::symbol
::*;
3 use internals
::{ungroup, Ctxt}
;
4 use proc_macro2
::{Spacing, Span, TokenStream, TokenTree}
;
7 use std
::collections
::BTreeSet
;
9 use syn
::parse
::{self, Parse, ParseStream}
;
10 use syn
::punctuated
::Punctuated
;
12 use syn
::Meta
::{List, NameValue, Path}
;
13 use syn
::NestedMeta
::{Lit, Meta}
;
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.
23 pub use internals
::case
::RenameRule
;
32 impl<'c
, T
> Attr
<'c
, T
> {
33 fn none(cx
: &'c Ctxt
, name
: Symbol
) -> Self {
37 tokens
: TokenStream
::new(),
42 fn set
<A
: ToTokens
>(&mut self, obj
: A
, value
: T
) {
43 let tokens
= obj
.into_token_stream();
45 if self.value
.is_some() {
47 .error_spanned_by(tokens
, format
!("duplicate serde attribute `{}`", self.name
));
50 self.value
= Some(value
);
54 fn set_opt
<A
: ToTokens
>(&mut self, obj
: A
, value
: Option
<T
>) {
55 if let Some(value
) = value
{
60 fn set_if_none(&mut self, value
: T
) {
61 if self.value
.is_none() {
62 self.value
= Some(value
);
66 fn get(self) -> Option
<T
> {
70 fn get_with_tokens(self) -> Option
<(TokenStream
, T
)> {
72 Some(v
) => Some((self.tokens
, v
)),
78 struct BoolAttr
<'c
>(Attr
<'c
, ()>);
80 impl<'c
> BoolAttr
<'c
> {
81 fn none(cx
: &'c Ctxt
, name
: Symbol
) -> Self {
82 BoolAttr(Attr
::none(cx
, name
))
85 fn set_true
<A
: ToTokens
>(&mut self, obj
: A
) {
89 fn get(&self) -> bool
{
90 self.0.value
.is_some()
94 struct VecAttr
<'c
, T
> {
97 first_dup_tokens
: TokenStream
,
101 impl<'c
, T
> VecAttr
<'c
, T
> {
102 fn none(cx
: &'c Ctxt
, name
: Symbol
) -> Self {
106 first_dup_tokens
: TokenStream
::new(),
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();
115 self.values
.push(value
);
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(
123 format
!("duplicate serde attribute `{}`", self.name
),
127 Ok(self.values
.pop())
131 fn get(self) -> Vec
<T
> {
138 serialize_renamed
: bool
,
140 deserialize_renamed
: bool
,
141 deserialize_aliases
: Vec
<String
>,
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()
155 ser_name
: Attr
<String
>,
156 de_name
: Attr
<String
>,
157 de_aliases
: Option
<VecAttr
<String
>>,
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
);
165 alias_list
.into_iter().collect()
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();
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
,
183 /// Return the container name for the container when serializing.
184 pub fn serialize_name(&self) -> String
{
185 self.serialize
.clone()
188 /// Return the container name for the container when deserializing.
189 pub fn deserialize_name(&self) -> String
{
190 self.deserialize
.clone()
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
);
203 pub struct RenameAllRules
{
204 serialize
: RenameRule
,
205 deserialize
: RenameRule
,
208 /// Represents struct or enum attribute information.
209 pub struct Container
{
212 deny_unknown_fields
: bool
,
214 rename_all_rules
: RenameAllRules
,
215 ser_bound
: Option
<Vec
<syn
::WherePredicate
>>,
216 de_bound
: Option
<Vec
<syn
::WherePredicate
>>,
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
,
224 serde_path
: Option
<syn
::Path
>,
226 /// Error message generated when type can't be deserialized
227 expecting
: Option
<String
>,
230 /// Styles of representing an enum.
235 /// {"variant1": {"key1": "value1", "key2": "value2"}}
239 /// `#[serde(tag = "type")]`
242 /// {"type": "variant1", "key1": "value1", "key2": "value2"}
244 Internal { tag: String }
,
246 /// `#[serde(tag = "t", content = "c")]`
249 /// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}}
251 Adjacent { tag: String, content: String }
,
253 /// `#[serde(untagged)]`
256 /// {"key1": "value1", "key2": "value2"}
261 /// Whether this enum represents the fields of a struct or the variants of an
263 #[derive(Copy, Clone)]
264 pub enum Identifier
{
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.
273 /// This enum represents the variants of an enum. All of the variants must
274 /// be unit variants.
279 #[cfg(feature = "deserialize_in_place")]
280 pub fn is_some(self) -> bool
{
282 Identifier
::No
=> false,
283 Identifier
::Field
| Identifier
::Variant
=> true,
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
);
312 for meta_item
in item
315 .flat_map(|attr
| get_serde_meta_items(cx
, attr
))
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());
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
));
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()) {
340 rename_all_ser_rule
.set(&m
.path
, rename_rule
);
341 rename_all_de_rule
.set(&m
.path
, rename_rule
);
343 Err(err
) => cx
.error_spanned_by(s
, err
),
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
),
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
),
366 // Parse `#[serde(transparent)]`
367 Meta(Path(word
)) if word
== TRANSPARENT
=> {
368 transparent
.set_true(word
);
371 // Parse `#[serde(deny_unknown_fields)]`
372 Meta(Path(word
)) if word
== DENY_UNKNOWN_FIELDS
=> {
373 deny_unknown_fields
.set_true(word
);
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
);
382 syn
::Fields
::Unnamed(_
) | syn
::Fields
::Unit
=> cx
.error_spanned_by(
384 "#[serde(default)] can only be used on structs with named fields",
387 syn
::Data
::Enum(syn
::DataEnum { enum_token, .. }
) => cx
.error_spanned_by(
389 "#[serde(default)] can only be used on structs with named fields",
391 syn
::Data
::Union(syn
::DataUnion { union_token, .. }
) => cx
.error_spanned_by(
393 "#[serde(default)] can only be used on structs with named fields",
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
) {
401 syn
::Data
::Struct(syn
::DataStruct { fields, .. }
) => {
403 syn
::Fields
::Named(_
) => {
404 default.set(&m
.path
, Default
::Path(path
));
406 syn
::Fields
::Unnamed(_
) | syn
::Fields
::Unit
=> cx
409 "#[serde(default = \"...\")] can only be used on structs with named fields",
413 syn
::Data
::Enum(syn
::DataEnum { enum_token, .. }
) => cx
416 "#[serde(default = \"...\")] can only be used on structs with named fields",
418 syn
::Data
::Union(syn
::DataUnion
{
420 }) => cx
.error_spanned_by(
422 "#[serde(default = \"...\")] can only be used on structs with named fields",
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
);
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
);
444 // Parse `#[serde(untagged)]`
445 Meta(Path(word
)) if word
== UNTAGGED
=> match item
.data
{
446 syn
::Data
::Enum(_
) => {
447 untagged
.set_true(word
);
449 syn
::Data
::Struct(syn
::DataStruct { struct_token, .. }
) => {
452 "#[serde(untagged)] can only be used on enums",
455 syn
::Data
::Union(syn
::DataUnion { union_token, .. }
) => {
458 "#[serde(untagged)] can only be used on enums",
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
) {
467 syn
::Data
::Enum(_
) => {
468 internal_tag
.set(&m
.path
, s
.value());
470 syn
::Data
::Struct(syn
::DataStruct { fields, .. }
) => match fields
{
471 syn
::Fields
::Named(_
) => {
472 internal_tag
.set(&m
.path
, s
.value());
474 syn
::Fields
::Unnamed(_
) | syn
::Fields
::Unit
=> {
477 "#[serde(tag = \"...\")] can only be used on enums and structs with named fields",
481 syn
::Data
::Union(syn
::DataUnion { union_token, .. }
) => {
484 "#[serde(tag = \"...\")] can only be used on enums and structs with named fields",
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
) {
495 syn
::Data
::Enum(_
) => {
496 content
.set(&m
.path
, s
.value());
498 syn
::Data
::Struct(syn
::DataStruct { struct_token, .. }
) => {
501 "#[serde(content = \"...\")] can only be used on enums",
504 syn
::Data
::Union(syn
::DataUnion { union_token, .. }
) => {
507 "#[serde(content = \"...\")] can only be used on enums",
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
));
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
));
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
));
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());
541 remote
.set(&m
.path
, path
);
546 // Parse `#[serde(field_identifier)]`
547 Meta(Path(word
)) if word
== FIELD_IDENTIFIER
=> {
548 field_identifier
.set_true(word
);
551 // Parse `#[serde(variant_identifier)]`
552 Meta(Path(word
)) if word
== VARIANT_IDENTIFIER
=> {
553 variant_identifier
.set_true(word
);
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
);
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());
578 format
!("unknown serde container attribute `{}`", path
),
583 cx
.error_spanned_by(lit
, "unexpected literal in serde container attribute");
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";
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
),
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
),
620 serde_path
: serde_path
.get(),
622 expecting
: expecting
.get(),
626 pub fn name(&self) -> &Name
{
630 pub fn rename_all_rules(&self) -> &RenameAllRules
{
631 &self.rename_all_rules
634 pub fn transparent(&self) -> bool
{
638 pub fn deny_unknown_fields(&self) -> bool
{
639 self.deny_unknown_fields
642 pub fn default(&self) -> &Default
{
646 pub fn ser_bound(&self) -> Option
<&[syn
::WherePredicate
]> {
647 self.ser_bound
.as_ref().map(|vec
| &vec
[..])
650 pub fn de_bound(&self) -> Option
<&[syn
::WherePredicate
]> {
651 self.de_bound
.as_ref().map(|vec
| &vec
[..])
654 pub fn tag(&self) -> &TagType
{
658 pub fn type_from(&self) -> Option
<&syn
::Type
> {
659 self.type_from
.as_ref()
662 pub fn type_try_from(&self) -> Option
<&syn
::Type
> {
663 self.type_try_from
.as_ref()
666 pub fn type_into(&self) -> Option
<&syn
::Type
> {
667 self.type_into
.as_ref()
670 pub fn remote(&self) -> Option
<&syn
::Path
> {
674 pub fn is_packed(&self) -> bool
{
678 pub fn identifier(&self) -> Identifier
{
682 pub fn has_flatten(&self) -> bool
{
686 pub fn mark_has_flatten(&mut self) {
687 self.has_flatten
= true;
690 pub fn custom_serde_path(&self) -> Option
<&syn
::Path
> {
691 self.serde_path
.as_ref()
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
)
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
)
708 item
: &syn
::DeriveInput
,
710 internal_tag
: Attr
<String
>,
711 content
: Attr
<String
>,
714 untagged
.0.get_with_tokens(),
715 internal_tag
.get_with_tokens(),
716 content
.get_with_tokens(),
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 {
730 "#[serde(tag = \"...\")] cannot be used with tuple variants",
738 TagType
::Internal { tag }
740 (Some((untagged_tokens
, _
)), Some((tag_tokens
, _
)), None
) => {
743 "enum cannot be both untagged and internally tagged",
747 "enum cannot be both untagged and internally tagged",
749 TagType
::External
// doesn't matter, will error
751 (None
, None
, Some((content_tokens
, _
))) => {
754 "#[serde(tag = \"...\", content = \"...\")] must be used together",
758 (Some((untagged_tokens
, _
)), None
, Some((content_tokens
, _
))) => {
761 "untagged enum cannot have #[serde(content = \"...\")]",
765 "untagged enum cannot have #[serde(content = \"...\")]",
769 (None
, Some((_
, tag
)), Some((_
, content
))) => TagType
::Adjacent { tag, content }
,
770 (Some((untagged_tokens
, _
)), Some((tag_tokens
, _
)), Some((content_tokens
, _
))) => {
773 "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]",
777 "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]",
781 "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]",
788 fn decide_identifier(
790 item
: &syn
::DeriveInput
,
791 field_identifier
: BoolAttr
,
792 variant_identifier
: BoolAttr
,
796 field_identifier
.0.get_with_tokens(),
797 variant_identifier
.0.get_with_tokens(),
799 (_
, None
, None
) => Identifier
::No
,
800 (_
, Some((field_identifier_tokens
, _
)), Some((variant_identifier_tokens
, _
))) => {
802 field_identifier_tokens
,
803 "#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set",
806 variant_identifier_tokens
,
807 "#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set",
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
) => {
816 "#[serde(field_identifier)] can only be used on an enum",
820 (syn
::Data
::Union(syn
::DataUnion { union_token, .. }
), Some(_
), None
) => {
823 "#[serde(field_identifier)] can only be used on an enum",
827 (syn
::Data
::Struct(syn
::DataStruct { struct_token, .. }
), None
, Some(_
)) => {
830 "#[serde(variant_identifier)] can only be used on an enum",
834 (syn
::Data
::Union(syn
::DataUnion { union_token, .. }
), None
, Some(_
)) => {
837 "#[serde(variant_identifier)] can only be used on an enum",
844 /// Represents variant attribute information
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
,
853 serialize_with
: Option
<syn
::ExprPath
>,
854 deserialize_with
: Option
<syn
::ExprPath
>,
855 borrow
: Option
<syn
::Meta
>,
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
);
874 for meta_item
in variant
877 .flat_map(|attr
| get_serde_meta_items(cx
, attr
))
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());
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
));
895 de_name
.set_if_none(de_value
.value());
896 de_aliases
.insert(&m
.path
, de_value
.value());
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());
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()) {
913 rename_all_ser_rule
.set(&m
.path
, rename_rule
);
914 rename_all_de_rule
.set(&m
.path
, rename_rule
);
916 Err(err
) => cx
.error_spanned_by(s
, err
),
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
),
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
),
939 // Parse `#[serde(skip)]`
940 Meta(Path(word
)) if word
== SKIP
=> {
941 skip_serializing
.set_true(word
);
942 skip_deserializing
.set_true(word
);
945 // Parse `#[serde(skip_deserializing)]`
946 Meta(Path(word
)) if word
== SKIP_DESERIALIZING
=> {
947 skip_deserializing
.set_true(word
);
950 // Parse `#[serde(skip_serializing)]`
951 Meta(Path(word
)) if word
== SKIP_SERIALIZING
=> {
952 skip_serializing
.set_true(word
);
955 // Parse `#[serde(other)]`
956 Meta(Path(word
)) if word
== OTHER
=> {
957 other
.set_true(word
);
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
);
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
);
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();
983 .push(Ident
::new("serialize", Span
::call_site()).into());
984 serialize_with
.set(&m
.path
, ser_path
);
985 let mut de_path
= path
;
989 .push(Ident
::new("deserialize", Span
::call_site()).into());
990 deserialize_with
.set(&m
.path
, de_path
);
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
);
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
);
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());
1014 cx
.error_spanned_by(
1016 "#[serde(borrow)] may only be used on newtype variants",
1021 Meta(meta_item
) => {
1022 let path
= meta_item
1024 .into_token_stream()
1027 cx
.error_spanned_by(
1029 format
!("unknown serde variant attribute `{}`", path
),
1034 cx
.error_spanned_by(lit
, "unexpected literal in serde variant attribute");
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
),
1045 ser_bound
: ser_bound
.get(),
1046 de_bound
: de_bound
.get(),
1047 skip_deserializing
: skip_deserializing
.get(),
1048 skip_serializing
: skip_serializing
.get(),
1050 serialize_with
: serialize_with
.get(),
1051 deserialize_with
: deserialize_with
.get(),
1052 borrow
: borrow
.get(),
1056 pub fn name(&self) -> &Name
{
1060 pub fn aliases(&self) -> Vec
<String
> {
1061 self.name
.deserialize_aliases()
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
);
1068 if !self.name
.deserialize_renamed
{
1069 self.name
.deserialize
= rules
.deserialize
.apply_to_variant(&self.name
.deserialize
);
1073 pub fn rename_all_rules(&self) -> &RenameAllRules
{
1074 &self.rename_all_rules
1077 pub fn ser_bound(&self) -> Option
<&[syn
::WherePredicate
]> {
1078 self.ser_bound
.as_ref().map(|vec
| &vec
[..])
1081 pub fn de_bound(&self) -> Option
<&[syn
::WherePredicate
]> {
1082 self.de_bound
.as_ref().map(|vec
| &vec
[..])
1085 pub fn skip_deserializing(&self) -> bool
{
1086 self.skip_deserializing
1089 pub fn skip_serializing(&self) -> bool
{
1090 self.skip_serializing
1093 pub fn other(&self) -> bool
{
1097 pub fn serialize_with(&self) -> Option
<&syn
::ExprPath
> {
1098 self.serialize_with
.as_ref()
1101 pub fn deserialize_with(&self) -> Option
<&syn
::ExprPath
> {
1102 self.deserialize_with
.as_ref()
1106 /// Represents field attribute information
1109 skip_serializing
: bool
,
1110 skip_deserializing
: bool
,
1111 skip_serializing_if
: Option
<syn
::ExprPath
>,
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
>,
1123 /// Represents the default to use for a field when deserializing.
1125 /// Field must always be specified because it does not have a default.
1127 /// The default is given by `std::default::Default::default()`.
1129 /// The default is given by this function.
1130 Path(syn
::ExprPath
),
1134 pub fn is_none(&self) -> bool
{
1136 Default
::None
=> true,
1137 Default
::Default
| Default
::Path(_
) => false,
1143 /// Extract out the `#[serde(...)]` attributes from a struct field.
1148 attrs
: Option
<&Variant
>,
1149 container_default
: &Default
,
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
);
1166 let ident
= match &field
.ident
{
1167 Some(ident
) => unraw(ident
),
1168 None
=> index
.to_string(),
1171 let variant_borrow
= attrs
1172 .and_then(|variant
| variant
.borrow
.as_ref())
1173 .map(|borrow
| Meta(borrow
.clone()));
1175 for meta_item
in field
1178 .flat_map(|attr
| get_serde_meta_items(cx
, attr
))
1180 .chain(variant_borrow
)
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());
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());
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());
1210 // Parse `#[serde(default)]`
1211 Meta(Path(word
)) if word
== DEFAULT
=> {
1212 default.set(word
, Default
::Default
);
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
));
1222 // Parse `#[serde(skip_serializing)]`
1223 Meta(Path(word
)) if word
== SKIP_SERIALIZING
=> {
1224 skip_serializing
.set_true(word
);
1227 // Parse `#[serde(skip_deserializing)]`
1228 Meta(Path(word
)) if word
== SKIP_DESERIALIZING
=> {
1229 skip_deserializing
.set_true(word
);
1232 // Parse `#[serde(skip)]`
1233 Meta(Path(word
)) if word
== SKIP
=> {
1234 skip_serializing
.set_true(word
);
1235 skip_deserializing
.set_true(word
);
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
);
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
);
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
);
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();
1266 .push(Ident
::new("serialize", Span
::call_site()).into());
1267 serialize_with
.set(&m
.path
, ser_path
);
1268 let mut de_path
= path
;
1272 .push(Ident
::new("deserialize", Span
::call_site()).into());
1273 deserialize_with
.set(&m
.path
, de_path
);
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
);
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
);
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
);
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(
1309 "field `{}` does not have lifetime {}",
1315 borrowed_lifetimes
.set(&m
.path
, lifetimes
);
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
);
1327 // Parse `#[serde(flatten)]`
1328 Meta(Path(word
)) if word
== FLATTEN
=> {
1329 flatten
.set_true(word
);
1332 Meta(meta_item
) => {
1333 let path
= meta_item
1335 .into_token_stream()
1338 cx
.error_spanned_by(
1340 format
!("unknown serde field attribute `{}`", path
),
1345 cx
.error_spanned_by(lit
, "unexpected literal in serde field attribute");
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
);
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:
1363 // impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>
1365 // A #[serde(borrow)] attribute enables borrowing that corresponds
1366 // roughly to these impls:
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(),
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());
1380 .push(Ident
::new("borrow_cow_str", span
).into());
1381 let expr
= syn
::ExprPath
{
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(),
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());
1397 .push(Ident
::new("borrow_cow_bytes", span
).into());
1398 let expr
= syn
::ExprPath
{
1403 deserialize_with
.set_if_none(expr
);
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
);
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(),
1422 getter
: getter
.get(),
1423 flatten
: flatten
.get(),
1428 pub fn name(&self) -> &Name
{
1432 pub fn aliases(&self) -> Vec
<String
> {
1433 self.name
.deserialize_aliases()
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
);
1440 if !self.name
.deserialize_renamed
{
1441 self.name
.deserialize
= rules
.deserialize
.apply_to_field(&self.name
.deserialize
);
1445 pub fn skip_serializing(&self) -> bool
{
1446 self.skip_serializing
1449 pub fn skip_deserializing(&self) -> bool
{
1450 self.skip_deserializing
1453 pub fn skip_serializing_if(&self) -> Option
<&syn
::ExprPath
> {
1454 self.skip_serializing_if
.as_ref()
1457 pub fn default(&self) -> &Default
{
1461 pub fn serialize_with(&self) -> Option
<&syn
::ExprPath
> {
1462 self.serialize_with
.as_ref()
1465 pub fn deserialize_with(&self) -> Option
<&syn
::ExprPath
> {
1466 self.deserialize_with
.as_ref()
1469 pub fn ser_bound(&self) -> Option
<&[syn
::WherePredicate
]> {
1470 self.ser_bound
.as_ref().map(|vec
| &vec
[..])
1473 pub fn de_bound(&self) -> Option
<&[syn
::WherePredicate
]> {
1474 self.de_bound
.as_ref().map(|vec
| &vec
[..])
1477 pub fn borrowed_lifetimes(&self) -> &BTreeSet
<syn
::Lifetime
> {
1478 &self.borrowed_lifetimes
1481 pub fn getter(&self) -> Option
<&syn
::ExprPath
> {
1482 self.getter
.as_ref()
1485 pub fn flatten(&self) -> bool
{
1489 pub fn transparent(&self) -> bool
{
1493 pub fn mark_transparent(&mut self) {
1494 self.transparent
= true;
1498 type SerAndDe
<T
> = (Option
<T
>, Option
<T
>);
1500 fn get_ser_and_de
<'a
, 'b
, T
, F
>(
1503 metas
: &'a Punctuated
<syn
::NestedMeta
, Token
![,]>,
1505 ) -> Result
<(VecAttr
<'b
, T
>, VecAttr
<'b
, T
>), ()>
1508 F
: Fn(&Ctxt
, Symbol
, Symbol
, &'a syn
::Lit
) -> Result
<T
, ()>,
1510 let mut ser_meta
= VecAttr
::none(cx
, attr_name
);
1511 let mut de_meta
= VecAttr
::none(cx
, attr_name
);
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
);
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
);
1528 cx
.error_spanned_by(
1531 "malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`",
1540 Ok((ser_meta
, de_meta
))
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()?
))
1551 fn get_multiple_renames
<'a
>(
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()))
1559 fn get_where_predicates(
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()?
))
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());
1572 match attr
.parse_meta() {
1573 Ok(List(meta
)) => Ok(meta
.nested
.into_iter().collect()),
1575 cx
.error_spanned_by(other
, "expected #[serde(...)]");
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
)
1589 fn get_lit_str2
<'a
>(
1592 meta_item_name
: Symbol
,
1594 ) -> Result
<&'a syn
::LitStr
, ()> {
1595 if let syn
::Lit
::Str(lit
) = lit
{
1598 cx
.error_spanned_by(
1601 "expected serde {} attribute to be a string: `{} = \"...\"`",
1602 attr_name
, meta_item_name
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()));
1616 fn parse_lit_into_expr_path(
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()));
1627 fn parse_lit_into_where(
1630 meta_item_name
: Symbol
,
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());
1638 let where_string
= syn
::LitStr
::new(&format
!("where {}", string
.value()), string
.span());
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
))
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
)?
;
1648 parse_lit_str(string
).map_err(|_
| {
1649 cx
.error_spanned_by(
1651 format
!("failed to parse type: {} = {:?}", attr_name
, string
.value()),
1656 // Parses a string literal like "'a + 'b + 'c" containing a nonempty list of
1657 // lifetimes separated by `+`.
1658 fn parse_lit_into_lifetimes(
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");
1669 struct BorrowedLifetimes(Punctuated
<syn
::Lifetime
, Token
![+]>);
1671 impl Parse
for BorrowedLifetimes
{
1672 fn parse(input
: ParseStream
) -> parse
::Result
<Self> {
1673 Punctuated
::parse_separated_nonempty(input
).map(BorrowedLifetimes
)
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
));
1687 cx
.error_spanned_by(
1689 format
!("failed to parse borrowed lifetimes: {:?}", string
.value()),
1694 fn is_implicitly_borrowed(ty
: &syn
::Type
) -> bool
{
1695 is_implicitly_borrowed_reference(ty
) || is_option(ty
, is_implicitly_borrowed_reference
)
1698 fn is_implicitly_borrowed_reference(ty
: &syn
::Type
) -> bool
{
1699 is_reference(ty
, is_str
) || is_reference(ty
, is_slice_u8
)
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.
1707 // use std::borrow::Cow as Pig;
1709 // #[derive(Deserialize)]
1712 // pig: Pig<'a, str>,
1717 // type str = [i16];
1719 // #[derive(Deserialize)]
1722 // cow: Cow<'a, str>,
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
,
1731 let seg
= match path
.segments
.last() {
1737 let args
= match &seg
.arguments
{
1738 syn
::PathArguments
::AngleBracketed(bracketed
) => &bracketed
.args
,
1745 && match (&args
[0], &args
[1]) {
1746 (syn
::GenericArgument
::Lifetime(_
), syn
::GenericArgument
::Type(arg
)) => elem(arg
),
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
,
1758 let seg
= match path
.segments
.last() {
1764 let args
= match &seg
.arguments
{
1765 syn
::PathArguments
::AngleBracketed(bracketed
) => &bracketed
.args
,
1770 seg
.ident
== "Option"
1773 syn
::GenericArgument
::Type(arg
) => elem(arg
),
1778 // Whether the type looks like it might be `&T` where elem="T". This can have
1779 // false negatives and false positives.
1785 // #[derive(Deserialize)]
1792 // type str = [i16];
1794 // #[derive(Deserialize)]
1798 fn is_reference(ty
: &syn
::Type
, elem
: fn(&syn
::Type
) -> bool
) -> bool
{
1800 syn
::Type
::Reference(ty
) => ty
.mutability
.is_none() && elem(&ty
.elem
),
1805 fn is_str(ty
: &syn
::Type
) -> bool
{
1806 is_primitive_type(ty
, "str")
1809 fn is_slice_u8(ty
: &syn
::Type
) -> bool
{
1811 syn
::Type
::Slice(ty
) => is_primitive_type(&ty
.elem
, "u8"),
1816 fn is_primitive_type(ty
: &syn
::Type
, primitive
: &str) -> bool
{
1818 syn
::Type
::Path(ty
) => ty
.qself
.is_none() && is_primitive_path(&ty
.path
, primitive
),
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()
1830 // All lifetimes that this type could borrow from a Deserializer.
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.
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(
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(
1847 format
!("field `{}` has no lifetimes to borrow", name
),
1855 fn collect_lifetimes(ty
: &syn
::Type
, out
: &mut BTreeSet
<syn
::Lifetime
>) {
1857 syn
::Type
::Slice(ty
) => {
1858 collect_lifetimes(&ty
.elem
, out
);
1860 syn
::Type
::Array(ty
) => {
1861 collect_lifetimes(&ty
.elem
, out
);
1863 syn
::Type
::Ptr(ty
) => {
1864 collect_lifetimes(&ty
.elem
, out
);
1866 syn
::Type
::Reference(ty
) => {
1867 out
.extend(ty
.lifetime
.iter().cloned());
1868 collect_lifetimes(&ty
.elem
, out
);
1870 syn
::Type
::Tuple(ty
) => {
1871 for elem
in &ty
.elems
{
1872 collect_lifetimes(elem
, out
);
1875 syn
::Type
::Path(ty
) => {
1876 if let Some(qself
) = &ty
.qself
{
1877 collect_lifetimes(&qself
.ty
, out
);
1879 for seg
in &ty
.path
.segments
{
1880 if let syn
::PathArguments
::AngleBracketed(bracketed
) = &seg
.arguments
{
1881 for arg
in &bracketed
.args
{
1883 syn
::GenericArgument
::Lifetime(lifetime
) => {
1884 out
.insert(lifetime
.clone());
1886 syn
::GenericArgument
::Type(ty
) => {
1887 collect_lifetimes(ty
, out
);
1889 syn
::GenericArgument
::Binding(binding
) => {
1890 collect_lifetimes(&binding
.ty
, out
);
1892 syn
::GenericArgument
::Constraint(_
)
1893 | syn
::GenericArgument
::Const(_
) => {}
1899 syn
::Type
::Paren(ty
) => {
1900 collect_lifetimes(&ty
.elem
, out
);
1902 syn
::Type
::Group(ty
) => {
1903 collect_lifetimes(&ty
.elem
, out
);
1905 syn
::Type
::Macro(ty
) => {
1906 collect_lifetimes_from_tokens(ty
.mac
.tokens
.clone(), out
);
1908 syn
::Type
::BareFn(_
)
1909 | syn
::Type
::Never(_
)
1910 | syn
::Type
::TraitObject(_
)
1911 | syn
::Type
::ImplTrait(_
)
1912 | syn
::Type
::Infer(_
)
1913 | syn
::Type
::Verbatim(_
) => {}
1915 #[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
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() {
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(),
1932 TokenTree
::Group(group
) => {
1933 let tokens
= group
.stream();
1934 collect_lifetimes_from_tokens(tokens
, out
);
1941 fn parse_lit_str
<T
>(s
: &syn
::LitStr
) -> parse
::Result
<T
>
1945 let tokens
= spanned_tokens(s
)?
;
1949 fn spanned_tokens(s
: &syn
::LitStr
) -> parse
::Result
<TokenStream
> {
1950 let stream
= syn
::parse_str(&s
.value())?
;
1951 Ok(respan(stream
, s
.span()))