Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions serde/src/private/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -805,16 +805,22 @@ mod content {
/// Not public API.
pub struct TaggedContentVisitor<'de, T> {
tag_name: &'static str,
default_variant: Option<T>,
expecting: &'static str,
value: PhantomData<TaggedContent<'de, T>>,
}

impl<'de, T> TaggedContentVisitor<'de, T> {
/// Visitor for the content of an internally tagged enum with the given
/// tag name.
pub fn new(name: &'static str, expecting: &'static str) -> Self {
pub fn new(
name: &'static str,
default_variant: Option<T>,
expecting: &'static str,
) -> Self {
TaggedContentVisitor {
tag_name: name,
default_variant,
expecting,
value: PhantomData,
}
Expand Down Expand Up @@ -851,11 +857,12 @@ mod content {
where
S: SeqAccess<'de>,
{
let tag = match try!(seq.next_element()) {
let tag = match seq.next_element()? {
Some(tag) => tag,
None => {
return Err(de::Error::missing_field(self.tag_name));
}
None => match self.default_variant {
Some(variant) => variant,
None => return Err(de::Error::missing_field(self.tag_name)),
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think, it is better to use .or(self.default_variant)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, that's much nicer :)

};
let rest = de::value::SeqAccessDeserializer::new(seq);
Ok(TaggedContent {
Expand Down Expand Up @@ -885,7 +892,13 @@ mod content {
}
}
match tag {
None => Err(de::Error::missing_field(self.tag_name)),
None => match self.default_variant {
Some(default) => Ok(TaggedContent {
tag: default,
content: Content::Map(vec),
}),
None => Err(de::Error::missing_field(self.tag_name)),
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here. tag.or(self.default_variant)

Some(tag) => Ok(TaggedContent {
tag,
content: Content::Map(vec),
Expand Down
18 changes: 17 additions & 1 deletion serde_derive/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1366,6 +1366,10 @@ fn deserialize_internally_tagged_enum(
}
});

let default_variant = get_default_variant(variants).unwrap_or(quote! {
std::option::Option::None
});

let expecting = format!("internally tagged enum {}", params.type_name());
let expecting = cattrs.expecting().unwrap_or(&expecting);

Expand All @@ -1376,14 +1380,26 @@ fn deserialize_internally_tagged_enum(

let __tagged = try!(_serde::Deserializer::deserialize_any(
__deserializer,
_serde::__private::de::TaggedContentVisitor::<__Field>::new(#tag, #expecting)));
_serde::__private::de::TaggedContentVisitor::<__Field>::new(#tag, #default_variant, #expecting)));

match __tagged.tag {
#(#variant_arms)*
}
}
}

fn get_default_variant(variants: &[Variant]) -> Option<TokenStream> {
for (i, variant) in variants.iter().enumerate() {
if variant.attrs.default() {
let variant_name = field_i(i);
return Some(quote! {
std::option::Option::Some(__Field::#variant_name)
});
}
}
None
}

fn deserialize_adjacently_tagged_enum(
params: &Parameters,
variants: &[Variant],
Expand Down
12 changes: 12 additions & 0 deletions serde_derive/src/internals/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,18 @@ fn enum_from_ast<'a>(
})
.collect();

let mut has_default = false;
for variant in &variants {
if !variant.attrs.default() {
continue;
}
if has_default {
cx.error_spanned_by(&variant.ident, "only one variant can be marked as default");
break;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not break after the first error so all errors can be found at once

has_default = true;
}

let index_of_last_tagged_variant = variants
.iter()
.rposition(|variant| !variant.attrs.untagged());
Expand Down
9 changes: 9 additions & 0 deletions serde_derive/src/internals/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -736,6 +736,7 @@ pub struct Variant {
de_bound: Option<Vec<syn::WherePredicate>>,
skip_deserializing: bool,
skip_serializing: bool,
default: bool,
other: bool,
serialize_with: Option<syn::ExprPath>,
deserialize_with: Option<syn::ExprPath>,
Expand All @@ -755,6 +756,7 @@ impl Variant {
let mut de_aliases = VecAttr::none(cx, RENAME);
let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING);
let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING);
let mut default = BoolAttr::none(cx, DEFAULT);
let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL);
let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL);
let mut ser_bound = Attr::none(cx, BOUND);
Expand Down Expand Up @@ -812,6 +814,8 @@ impl Variant {
}
}
}
} else if meta.path == DEFAULT {
default.set_true(&meta.path);
} else if meta.path == SKIP {
// #[serde(skip)]
skip_serializing.set_true(&meta.path);
Expand Down Expand Up @@ -905,6 +909,7 @@ impl Variant {
de_bound: de_bound.get(),
skip_deserializing: skip_deserializing.get(),
skip_serializing: skip_serializing.get(),
default: default.get(),
other: other.get(),
serialize_with: serialize_with.get(),
deserialize_with: deserialize_with.get(),
Expand Down Expand Up @@ -950,6 +955,10 @@ impl Variant {
self.skip_serializing
}

pub fn default(&self) -> bool {
self.default
}

pub fn other(&self) -> bool {
self.other
}
Expand Down
111 changes: 111 additions & 0 deletions test_suite/tests/test_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,117 @@ fn test_internally_tagged_enum() {
);
}

#[test]
fn test_internally_tagged_enum_with_default_variant() {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the best way to test the macro?

I had a dig around the codebase, and I felt it made sense, but unsure.

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Newtype(BTreeMap<String, String>);

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Struct {
f: u8,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
enum InternallyTaggedWithDefaultStructVariant {
#[serde(default)]
A {
a: u8,
},
E(Struct),
B,
C(BTreeMap<String, String>),
D(Newtype),
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
enum InternallyTaggedWithDefaultTupleVariant {
A {
a: u8,
},
#[serde(default)]
E(Struct),
B,
C(BTreeMap<String, String>),
D(Newtype),
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
enum InternallyTaggedWithDefaultUnitVariant {
A {
a: u8,
},
E(Struct),
#[serde(default)]
B,
C(BTreeMap<String, String>),
D(Newtype),
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
enum InternallyTaggedWithDefaultMapVariant {
A {
a: u8,
},
E(Struct),
B,
#[serde(default)]
C(BTreeMap<String, String>),
D(Newtype),
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
enum InternallyTaggedWithDefaultNewtypeVariant {
A {
a: u8,
},
E(Struct),
B,
C(BTreeMap<String, String>),
#[serde(default)]
D(Newtype),
}

assert_de_tokens(
&InternallyTaggedWithDefaultStructVariant::A { a: 1 },
&[
Token::Map { len: Some(1) },
Token::Str("a"),
Token::U8(1),
Token::MapEnd,
],
);

assert_de_tokens(
&InternallyTaggedWithDefaultTupleVariant::E(Struct { f: 1 }),
&[
Token::Map { len: Some(1) },
Token::Str("f"),
Token::U8(1),
Token::MapEnd,
],
);

assert_de_tokens(
&InternallyTaggedWithDefaultUnitVariant::B,
&[Token::Map { len: Some(0) }, Token::MapEnd],
);

assert_de_tokens(
&InternallyTaggedWithDefaultMapVariant::C(BTreeMap::new()),
&[Token::Map { len: Some(0) }, Token::MapEnd],
);

assert_de_tokens(
&InternallyTaggedWithDefaultNewtypeVariant::D(Newtype(BTreeMap::new())),
&[Token::Map { len: Some(0) }, Token::MapEnd],
);
}

#[test]
fn test_internally_tagged_bytes() {
#[derive(Debug, PartialEq, Deserialize)]
Expand Down