use aster; use syntax::ast::{ Ident, MetaItem, Item, }; use syntax::ast; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; use attr; use error::Error; pub fn expand_derive_serialize( cx: &mut ExtCtxt, span: Span, meta_item: &MetaItem, annotatable: &Annotatable, push: &mut FnMut(Annotatable) ) { let item = match *annotatable { Annotatable::Item(ref item) => item, _ => { cx.span_err( meta_item.span, "`#[derive(Serialize)]` may only be applied to structs and enums"); return; } }; let builder = aster::AstBuilder::new().span(span); let impl_item = match serialize_item(cx, &builder, &item) { Ok(item) => item, Err(Error) => { // An error occured, but it should have been reported already. return; } }; push(Annotatable::Item(impl_item)) } fn serialize_item( cx: &ExtCtxt, builder: &aster::AstBuilder, item: &Item, ) -> Result
, Error> {
let generics = match item.node {
ast::ItemKind::Struct(_, ref generics) => generics,
ast::ItemKind::Enum(_, ref generics) => generics,
_ => {
cx.span_err(
item.span,
"`#[derive(Serialize)]` may only be applied to structs and enums");
return Err(Error);
}
};
let impl_generics = builder.from_generics(generics.clone())
.add_ty_param_bound(
builder.path().global().ids(&["serde", "ser", "Serialize"]).build()
)
.build();
let ty = builder.ty().path()
.segment(item.ident).with_generics(impl_generics.clone()).build()
.build();
let body = try!(serialize_body(cx,
&builder,
&item,
&impl_generics,
ty.clone()));
let where_clause = &impl_generics.where_clause;
Ok(quote_item!(cx,
impl $impl_generics ::serde::ser::Serialize for $ty $where_clause {
fn serialize<__S>(&self, _serializer: &mut __S) -> ::std::result::Result<(), __S::Error>
where __S: ::serde::ser::Serializer,
{
$body
}
}
).unwrap())
}
fn serialize_body(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item: &Item,
impl_generics: &ast::Generics,
ty: P , Error> {
let container_attrs = try!(attr::ContainerAttrs::from_item(cx, item));
match item.node {
ast::ItemKind::Struct(ref variant_data, _) => {
serialize_item_struct(
cx,
builder,
impl_generics,
ty,
item.span,
variant_data,
&container_attrs,
)
}
ast::ItemKind::Enum(ref enum_def, _) => {
serialize_item_enum(
cx,
builder,
item.ident,
impl_generics,
ty,
enum_def,
&container_attrs,
)
}
_ => {
cx.span_bug(item.span,
"expected ItemStruct or ItemEnum in #[derive(Serialize)]");
}
}
}
fn serialize_item_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
ty: P , Error> {
match *variant_data {
ast::VariantData::Unit(_) => {
serialize_unit_struct(
cx,
container_attrs,
)
}
ast::VariantData::Tuple(ref fields, _) if fields.len() == 1 => {
serialize_newtype_struct(
cx,
container_attrs,
)
}
ast::VariantData::Tuple(ref fields, _) => {
if fields.iter().any(|field| field.ident.is_some()) {
cx.span_bug(span, "tuple struct has named fields")
}
serialize_tuple_struct(
cx,
&builder,
impl_generics,
ty,
fields.len(),
container_attrs,
)
}
ast::VariantData::Struct(ref fields, _) => {
if fields.iter().any(|field| field.ident.is_none()) {
cx.span_bug(span, "struct has unnamed fields")
}
serialize_struct(
cx,
&builder,
impl_generics,
ty,
fields,
container_attrs,
)
}
}
}
fn serialize_unit_struct(
cx: &ExtCtxt,
container_attrs: &attr::ContainerAttrs,
) -> Result , Error> {
let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx,
_serializer.serialize_unit_struct($type_name)
))
}
fn serialize_newtype_struct(
cx: &ExtCtxt,
container_attrs: &attr::ContainerAttrs,
) -> Result , Error> {
let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx,
_serializer.serialize_newtype_struct($type_name, &self.0)
))
}
fn serialize_tuple_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
ty: P , Error> {
let (visitor_struct, visitor_impl) = serialize_tuple_struct_visitor(
cx,
builder,
ty.clone(),
builder.ty()
.ref_()
.lifetime("'__a")
.build_ty(ty.clone()),
builder.id("serialize_tuple_struct_elt"),
fields,
impl_generics,
);
let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, {
$visitor_struct
$visitor_impl
_serializer.serialize_tuple_struct($type_name, Visitor {
value: self,
state: 0,
_structure_ty: ::std::marker::PhantomData::<&$ty>,
})
}))
}
fn serialize_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
ty: P , Error> {
let (visitor_struct, visitor_impl) = try!(serialize_struct_visitor(
cx,
builder,
ty.clone(),
builder.ty()
.ref_()
.lifetime("'__a")
.build_ty(ty.clone()),
builder.id("serialize_struct_elt"),
fields,
impl_generics,
false,
));
let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, {
$visitor_struct
$visitor_impl
_serializer.serialize_struct($type_name, Visitor {
value: self,
state: 0,
_structure_ty: ::std::marker::PhantomData::<&$ty>,
})
}))
}
fn serialize_item_enum(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_ident: Ident,
impl_generics: &ast::Generics,
ty: P , Error> {
let arms: Vec<_> = try!(
enum_def.variants.iter()
.enumerate()
.map(|(variant_index, variant)| {
serialize_variant(
cx,
builder,
type_ident,
impl_generics,
ty.clone(),
variant,
variant_index,
container_attrs,
)
})
.collect()
);
Ok(quote_expr!(cx,
match *self {
$arms
}
))
}
fn serialize_variant(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_ident: Ident,
generics: &ast::Generics,
ty: P , Error> {
let variant_generics = builder.generics()
.with(generics.clone())
.add_lifetime_bound("'__serde_variant")
.lifetime_name("'__serde_variant")
.build();
let variant_struct = builder.item().struct_("__VariantStruct")
.with_generics(variant_generics.clone())
.with_fields(
fields.iter().map(|field| {
builder.struct_field(field.ident.expect("struct has unnamed fields"))
.with_attrs(field.attrs.iter().cloned())
.ty()
.ref_()
.lifetime("'__serde_variant")
.build_ty(field.ty.clone())
})
)
.field("__serde_container_ty")
.ty().phantom_data().build(ty.clone())
.build();
let variant_expr = builder.expr().struct_id("__VariantStruct")
.with_id_exprs(
fields.iter()
.zip(field_names.iter())
.map(|(field, field_name)| {
(
field.ident.expect("struct has unnamed fields"),
builder.expr().id(field_name),
)
})
)
.field("__serde_container_ty").path()
.global()
.id("std").id("marker")
.segment("PhantomData")
.with_ty(ty.clone())
.build()
.build()
.build();
let variant_ty = builder.ty().path()
.segment("__VariantStruct")
.with_generics(variant_generics.clone())
.build()
.build();
let (visitor_struct, visitor_impl) = try!(serialize_struct_visitor(
cx,
builder,
variant_ty.clone(),
variant_ty.clone(),
builder.id("serialize_struct_variant_elt"),
fields,
&variant_generics,
true,
));
let container_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, {
$variant_struct
$visitor_struct
$visitor_impl
_serializer.serialize_struct_variant(
$container_name,
$variant_index,
$variant_name,
Visitor {
value: $variant_expr,
state: 0,
_structure_ty: ::std::marker::PhantomData,
},
)
}))
}
fn serialize_tuple_struct_visitor(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
structure_ty: P(&mut self, _serializer: &mut S) -> ::std::result::Result