#[derive_deserialize] for generic tuple structs

This commit is contained in:
Erick Tryzelaar 2015-03-08 11:39:20 -07:00
parent 8bcdd7afe8
commit 9134cff155
2 changed files with 107 additions and 26 deletions

View File

@ -120,10 +120,12 @@ fn expand_derive_serialize(
trait_def.expand(cx, mitem, item, |item| push(item)) trait_def.expand(cx, mitem, item, |item| push(item))
} }
fn serialize_substructure(cx: &ExtCtxt, fn serialize_substructure(
span: Span, cx: &ExtCtxt,
substr: &Substructure, span: Span,
item: &Item) -> P<Expr> { substr: &Substructure,
item: &Item,
) -> P<Expr> {
let ctx = aster::Ctx::new(); let ctx = aster::Ctx::new();
let builder = aster::AstBuilder::new(&ctx).span(span); let builder = aster::AstBuilder::new(&ctx).span(span);
@ -635,7 +637,7 @@ pub fn expand_derive_deserialize(
), ),
attributes: attrs, attributes: attrs,
combine_substructure: combine_substructure(Box::new(|a, b, c| { combine_substructure: combine_substructure(Box::new(|a, b, c| {
deserialize_substructure(a, b, c) deserialize_substructure(a, b, c, item)
})), })),
}) })
}; };
@ -643,11 +645,16 @@ pub fn expand_derive_deserialize(
trait_def.expand(cx, mitem, item, |item| push(item)) trait_def.expand(cx, mitem, item, |item| push(item))
} }
fn deserialize_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> { fn deserialize_substructure(
cx: &ExtCtxt,
span: Span,
substr: &Substructure,
item: &Item,
) -> P<Expr> {
let state = substr.nonself_args[0].clone(); let state = substr.nonself_args[0].clone();
match *substr.fields { match (&item.node, &*substr.fields) {
StaticStruct(ref struct_def, ref fields) => { (&ast::ItemStruct(_, ref generics), &StaticStruct(ref struct_def, ref fields)) => {
deserialize_struct( deserialize_struct(
cx, cx,
span, span,
@ -656,16 +663,20 @@ fn deserialize_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) ->
cx.path(span, vec![substr.type_ident]), cx.path(span, vec![substr.type_ident]),
fields, fields,
state, state,
struct_def) struct_def,
generics,
)
} }
StaticEnum(ref enum_def, ref fields) => { (&ast::ItemEnum(_, ref generics), &StaticEnum(ref enum_def, ref fields)) => {
deserialize_enum( deserialize_enum(
cx, cx,
span, span,
substr.type_ident, substr.type_ident,
&fields, &fields,
state, state,
enum_def) enum_def,
generics,
)
} }
_ => cx.bug("expected StaticEnum or StaticStruct in derive(Deserialize)") _ => cx.bug("expected StaticEnum or StaticStruct in derive(Deserialize)")
} }
@ -679,7 +690,8 @@ fn deserialize_struct(
struct_path: ast::Path, struct_path: ast::Path,
fields: &StaticFields, fields: &StaticFields,
state: P<ast::Expr>, state: P<ast::Expr>,
struct_def: &StructDef struct_def: &StructDef,
generics: &ast::Generics,
) -> P<ast::Expr> { ) -> P<ast::Expr> {
match *fields { match *fields {
Unnamed(ref fields) => { Unnamed(ref fields) => {
@ -699,7 +711,9 @@ fn deserialize_struct(
struct_ident, struct_ident,
struct_path, struct_path,
&fields, &fields,
state) state,
generics,
)
} }
} }
Named(ref fields) => { Named(ref fields) => {
@ -774,11 +788,21 @@ fn deserialize_struct_unnamed_fields(
struct_path: ast::Path, struct_path: ast::Path,
fields: &[Span], fields: &[Span],
state: P<ast::Expr>, state: P<ast::Expr>,
generics: &ast::Generics,
) -> P<ast::Expr> { ) -> P<ast::Expr> {
let struct_name = cx.expr_str(span, token::get_ident(struct_ident)); let ctx = aster::Ctx::new();
let builder = aster::AstBuilder::new(&ctx).span(span);
let visitor_impl_generics = builder.from_generics(generics.clone())
.add_ty_param_bound(
builder.path().global().ids(&["serde2", "de", "Deserialize"]).build()
)
.build();
let struct_name = builder.expr().str(struct_ident);
let field_names: Vec<ast::Ident> = (0 .. fields.len()) let field_names: Vec<ast::Ident> = (0 .. fields.len())
.map(|i| token::str_to_ident(&format!("__field{}", i))) .map(|i| builder.id(&format!("__field{}", i)))
.collect(); .collect();
let visit_seq_expr = declare_visit_seq( let visit_seq_expr = declare_visit_seq(
@ -788,13 +812,48 @@ fn deserialize_struct_unnamed_fields(
&field_names, &field_names,
); );
// Build `__Visitor<A, B, ...>(PhantomData<A>, PhantomData<B>, ...)`
let (visitor_struct, visitor_expr) = if generics.ty_params.is_empty() {
(
builder.item().tuple_struct("__Visitor")
.build(),
builder.expr().id("__Visitor"),
)
} else {
(
builder.item().tuple_struct("__Visitor")
.with_generics(generics.clone())
.with_tys(
generics.ty_params.iter().map(|ty_param| {
builder.ty().phantom_data().id(ty_param.ident)
})
)
.build(),
builder.expr().call().id("__Visitor")
.with_args(
generics.ty_params.iter().map(|_| {
builder.expr().phantom_data()
})
)
.build(),
)
};
let visitor_ty = builder.ty().path()
.segment("__Visitor").with_generics(generics.clone()).build()
.build();
let value_ty = builder.ty().path()
.segment(type_ident).with_generics(generics.clone()).build()
.build();
quote_expr!(cx, { quote_expr!(cx, {
struct __Visitor; $visitor_struct;
impl ::serde2::de::Visitor for __Visitor { impl $visitor_impl_generics ::serde2::de::Visitor for $visitor_ty {
type Value = $type_ident; type Value = $value_ty;
fn visit_seq<__V>(&mut self, mut visitor: __V) -> Result<$type_ident, __V::Error> fn visit_seq<__V>(&mut self, mut visitor: __V) -> Result<$value_ty, __V::Error>
where __V: ::serde2::de::SeqVisitor, where __V: ::serde2::de::SeqVisitor,
{ {
$visit_seq_expr $visit_seq_expr
@ -802,7 +861,7 @@ fn deserialize_struct_unnamed_fields(
fn visit_named_seq<__V>(&mut self, fn visit_named_seq<__V>(&mut self,
name: &str, name: &str,
visitor: __V) -> Result<$type_ident, __V::Error> visitor: __V) -> Result<$value_ty, __V::Error>
where __V: ::serde2::de::SeqVisitor, where __V: ::serde2::de::SeqVisitor,
{ {
if name == $struct_name { if name == $struct_name {
@ -813,7 +872,7 @@ fn deserialize_struct_unnamed_fields(
} }
} }
$state.visit(__Visitor) $state.visit($visitor_expr)
}) })
} }
@ -1132,6 +1191,7 @@ fn deserialize_enum(
fields: &[(Ident, Span, StaticFields)], fields: &[(Ident, Span, StaticFields)],
state: P<ast::Expr>, state: P<ast::Expr>,
enum_def: &EnumDef, enum_def: &EnumDef,
_generics: &ast::Generics,
) -> P<ast::Expr> { ) -> P<ast::Expr> {
let type_name = cx.expr_str(span, token::get_ident(type_ident)); let type_name = cx.expr_str(span, token::get_ident(type_ident));

View File

@ -30,10 +30,6 @@ trait Trait {
#[derive_deserialize] #[derive_deserialize]
struct NamedUnit; struct NamedUnit;
#[derive(Debug, PartialEq)]
#[derive_serialize]
struct NamedTuple<'a, 'b, A: 'a, B: 'b, C>(&'a A, &'b mut B, C);
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
#[derive_serialize] #[derive_serialize]
struct NamedMap<'a, 'b, A: 'a, B: 'b, C> { struct NamedMap<'a, 'b, A: 'a, B: 'b, C> {
@ -87,7 +83,11 @@ fn test_named_unit() {
} }
#[test] #[test]
fn test_named_tuple() { fn test_ser_named_tuple() {
#[derive(Debug, PartialEq)]
#[derive_serialize]
struct NamedTuple<'a, 'b, A: 'a, B: 'b, C>(&'a A, &'b mut B, C);
let a = 5; let a = 5;
let mut b = 6; let mut b = 6;
let c = 7; let c = 7;
@ -104,6 +104,27 @@ fn test_named_tuple() {
); );
} }
#[test]
fn test_de_named_tuple() {
#[derive(Debug, PartialEq)]
#[derive_deserialize]
struct NamedTuple<A, B, C>(A, B, C);
assert_eq!(
json::from_str("[1,2,3]").unwrap(),
NamedTuple(1, 2, 3)
);
assert_eq!(
json::from_str("[1,2,3]").unwrap(),
Value::Array(vec![
Value::I64(1),
Value::I64(2),
Value::I64(3),
])
);
}
#[test] #[test]
fn test_named_map() { fn test_named_map() {
let a = 5; let a = 5;