Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Field serialization proxy via newtypes #198

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
6 changes: 3 additions & 3 deletions serde_codegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ with-syntex = ["quasi/with-syntex", "quasi_codegen", "quasi_codegen/with-syntex"

[build-dependencies]
quasi_codegen = { version = "^0.3.9", optional = true }
syntex = { version = "^0.22.0", optional = true }
syntex = { version = "^0.24.0", optional = true }

[dependencies]
aster = { version = "^0.9.0", default-features = false }
quasi = { version = "^0.3.9", default-features = false }
quasi_macros = { version = "^0.3.9", optional = true }
syntex = { version = "^0.22.0", optional = true }
syntex_syntax = { version = "^0.23.0", optional = true }
syntex = { version = "^0.24.0", optional = true }
syntex_syntax = { version = "^0.24.0", optional = true }
42 changes: 42 additions & 0 deletions serde_codegen/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pub struct FieldAttrs {
skip_serializing_field_if_empty: bool,
skip_serializing_field_if_none: bool,
names: FieldNames,
serializer: Option<String>,
deserializer: Option<String>,
use_default: bool,
}

Expand All @@ -43,6 +45,16 @@ impl FieldAttrs {
}
}

/// Return the serializer for the field
pub fn serializer(&self) -> Option<&str> {
self.serializer.as_ref().map(AsRef::as_ref)
}

/// Return the deserializer for the field
pub fn deserializer(&self) -> Option<&str> {
self.deserializer.as_ref().map(AsRef::as_ref)
}

/// Return an expression for the field key name for serialisation.
///
/// The resulting expression assumes that `S` refers to a type
Expand Down Expand Up @@ -108,6 +120,8 @@ pub struct FieldAttrsBuilder<'a> {
skip_serializing_field: bool,
skip_serializing_field_if_empty: bool,
skip_serializing_field_if_none: bool,
serializer: Option<String>,
deserializer: Option<String>,
name: Option<P<ast::Expr>>,
format_rename: HashMap<P<ast::Expr>, P<ast::Expr>>,
use_default: bool,
Expand All @@ -120,6 +134,8 @@ impl<'a> FieldAttrsBuilder<'a> {
skip_serializing_field: false,
skip_serializing_field_if_empty: false,
skip_serializing_field_if_none: false,
serializer: None,
deserializer: None,
name: None,
format_rename: HashMap::new(),
use_default: false,
Expand Down Expand Up @@ -174,6 +190,20 @@ impl<'a> FieldAttrsBuilder<'a> {
}
self
}
ast::MetaNameValue(ref name, ref lit) if name == &"serializer" => {
if let ast::Lit_::LitStr(ref lit, _) = lit.node {
self.serializer(lit[..].into())
} else {
unreachable!()
}
}
ast::MetaNameValue(ref name, ref lit) if name == &"deserializer" => {
if let ast::Lit_::LitStr(ref lit, _) = lit.node {
self.deserializer(lit[..].into())
} else {
unreachable!()
}
}
ast::MetaWord(ref name) if name == &"default" => {
self.default()
}
Expand Down Expand Up @@ -208,6 +238,16 @@ impl<'a> FieldAttrsBuilder<'a> {
self
}

pub fn serializer(mut self, value: String) -> FieldAttrsBuilder<'a> {
self.serializer = Some(value);
self
}

pub fn deserializer(mut self, value: String) -> FieldAttrsBuilder<'a> {
self.deserializer = Some(value);
self
}

pub fn name(mut self, name: P<ast::Expr>) -> FieldAttrsBuilder<'a> {
self.name = Some(name);
self
Expand Down Expand Up @@ -238,6 +278,8 @@ impl<'a> FieldAttrsBuilder<'a> {
skip_serializing_field: self.skip_serializing_field,
skip_serializing_field_if_empty: self.skip_serializing_field_if_empty,
skip_serializing_field_if_none: self.skip_serializing_field_if_none,
serializer: self.serializer,
deserializer: self.deserializer,
names: names,
use_default: self.use_default,
}
Expand Down
12 changes: 10 additions & 2 deletions serde_codegen/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::owned_slice::OwnedSlice;
use syntax::ptr::P;
use quasi::ExtParseUtils;

use attr;
use field;
Expand Down Expand Up @@ -973,10 +974,17 @@ fn deserialize_map(

// Match arms to extract a value for a field.
let value_arms: Vec<ast::Arm> = field_names.iter()
.map(|field_name| {
.zip(field::struct_field_attrs(cx, builder, fields).iter())
.map(|(field_name, field_attr)| {
let visit_value = if let Some(deserializer) = field_attr.deserializer() {
let deserializer = cx.parse_expr(deserializer.into());
quote_expr!(cx, ::std::convert::Into::into(try!(visitor.visit_value::<$deserializer>())))
} else {
quote_expr!(cx, try!(visitor.visit_value()))
};
quote_arm!(cx,
__Field::$field_name => {
$field_name = Some(try!(visitor.visit_value()));
$field_name = Some($visit_value);
}
)
})
Expand Down
37 changes: 37 additions & 0 deletions serde_codegen/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ptr::P;
use quasi::ExtParseUtils;

use field::struct_field_attrs;

Expand Down Expand Up @@ -587,6 +588,42 @@ fn serialize_struct_visitor<I>(
.enumerate()
.map(|(i, (ref field, value_expr))| {
let key_expr = field.serializer_key_expr(cx);
let value_expr = if let Some(serializer) = field.serializer() {
use aster::invoke::Invoke;
use syntax::parse::token::keywords::Keyword;
use syntax::fold::{noop_fold_expr, Folder};

struct SelfFolder<'a>(&'a ExtCtxt<'a>, &'a aster::AstBuilder);
impl<'a> Folder for SelfFolder<'a> {
fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
let self_path = if let ast::Expr_::ExprPath(None, ref path) = e.node {
if path.segments.len() == 1 && path.segments[0].identifier == self.0.ident_of("self") {
true
} else {
false
}
} else {
false
};

if self_path {
if let ast::Expr_::ExprPath(None, path) = e.and_then(|e| e.node) {
self.1.expr().field("value").invoke(path)
} else {
unreachable!()
}
} else {
e.map(|e| noop_fold_expr(e, self))
}
}
}

let serializer = cx.parse_expr(serializer.into());
let serializer = SelfFolder(cx, builder).fold_expr(serializer);
quote_expr!(cx, ($serializer)($value_expr))
} else {
value_expr.clone()
};

let stmt = if field.skip_serializing_field_if_empty() {
quote_stmt!(cx, if ($value_expr).is_empty() { continue; })
Expand Down
6 changes: 3 additions & 3 deletions serde_tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ keywords = ["serialization"]
build = "build.rs"

[build-dependencies]
syntex = { version = "^0.22.0" }
syntex_syntax = { version = "^0.23.0" }
syntex = { version = "^0.24.0" }
syntex_syntax = { version = "^0.24.0" }
serde_codegen = { version = "*", path = "../serde_codegen", features = ["with-syntex"] }

[dev-dependencies]
num = "^0.1.27"
rustc-serialize = "^0.3.16"
serde = { version = "*", path = "../serde", features = ["num-impls"] }
syntex = "^0.22.0"
syntex = "^0.24.0"

[[test]]
name = "test"
Expand Down
64 changes: 64 additions & 0 deletions serde_tests/tests/test_annotations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,25 @@ struct SkipSerializingIfNoneFields<A: default::Default> {
b: Option<A>,
}

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct AddSerializer(i8);
impl AddSerializer {
fn new(v: &i8) -> Self { AddSerializer(*v + 1) }
}

impl Into<i8> for AddSerializer {
fn into(self) -> i8 {
self.0 - 1
}
}

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct SerializerFields {
a: i8,
#[serde(serializer="AddSerializer::new", deserializer="AddSerializer")]
b: i8,
}

#[test]
fn test_default() {
assert_de_tokens(
Expand Down Expand Up @@ -106,6 +125,51 @@ fn test_rename() {
);
}

#[test]
fn test_serializer() {
assert_ser_tokens(
&SerializerFields {
a: 1,
b: 2,
},
&[
Token::StructStart("SerializerFields", Some(2)),

Token::MapSep,
Token::Str("a"),
Token::I8(1),

Token::MapSep,
Token::Str("b"),
Token::StructNewtype("AddSerializer"),
Token::I8(3),

Token::MapEnd,
]
);

assert_de_tokens(
&SerializerFields {
a: 1,
b: 2,
},
vec![
Token::StructStart("SerializerFields", Some(2)),

Token::MapSep,
Token::Str("a"),
Token::I8(1),

Token::MapSep,
Token::Str("b"),
Token::StructNewtype("AddSerializer"),
Token::I8(3),

Token::MapEnd,
]
);
}

#[test]
fn test_format_rename() {
assert_tokens(
Expand Down