Compare commits

...

27 Commits

Author SHA1 Message Date
David Tolnay 6ab508a93c Release 0.7.11 2016-06-23 19:58:31 -07:00
David Tolnay 9f38c2ab59 Merge pull request #409 from knsd/patch-1
Fix typo
2016-06-23 09:52:50 -07:00
Fedor Gogolev 021ce5be88 Fix typo 2016-06-23 20:50:27 +04:00
Homu f1f8b4622b Auto merge of #402 - erickt:clippy, r=erickt
Update link to clippy lint report
2016-06-23 12:52:36 +09:00
Erick Tryzelaar 1fb2172a25 Merge pull request #405 from erickt/rustup
Version bump the syntex stack
2016-06-22 20:34:15 -07:00
Erick Tryzelaar 5941f1d071 Version bump the syntex stack 2016-06-22 20:19:47 -07:00
Erick Tryzelaar 8d6cc4dfa5 Update link to clippy lint report 2016-06-22 10:13:28 -07:00
Homu c9e2e518ba Auto merge of #397 - dtolnay:item, r=oli-obk
Factor attr parsing into serde_item crate

Fixes #396. @KodrAus [let me know whether this fits the bill.](https://github.com/dtolnay/serde/tree/5c6a0e12e95974e3c131386e8e0528b6b9cfa6fa/serde_item/src)

a few other changes to make the API a little more presentable:

- Rename attr::{ContainerAttrs,VariantAttrs,FieldAttrs} to remove the "Attrs" (I see you worked on the corresponding [clippy lint](https://github.com/Manishearth/rust-clippy/issues/904)).
- Rename attr::Container* to attr::Item to correspond with item::Item and ast::Item. The others already had a correspondence (attr::Variant/item::Variant/ast::Variant, attr::Field/item::Field/ast::Field). Also a unit struct isn't much of a "container."
- Change item::Item::from_ast to return a meaningful error enum instead of printing a message that was hard to generalize to other uses.
- Add item::Variant.span for consistency because Item and Field already had span.
- Remove the "ident" field from attr::Name because we can just fold it into the other two fields.
- Remove attr::Name::(de)serialize_name_expr because it wasn't using the right AstBuilder in the first place.
- Rename the attr:: constructors from_item/from_variant/from_field to from_ast to line up with the item:: constructors; the signatures match.
- Remove attr's dependency on aster because we were only using it for two very simple things.
2016-06-20 16:45:25 +09:00
David Tolnay 51042bde50 Remove ident from Name struct 2016-06-19 20:31:12 -07:00
David Tolnay 5c6a0e12e9 Factor attr parsing into serde_item crate 2016-06-19 20:15:49 -07:00
Homu d4e1ef659a Auto merge of #389 - dtolnay:rule, r=oli-obk
Remove unused macro rule
2016-06-17 16:52:37 +09:00
David Tolnay f5f35677f0 Remove unused macro rule 2016-06-17 00:06:11 -07:00
David Tolnay 90d9c77186 Merge pull request #385 from dtolnay/dup
Error on duplicate attributes
2016-06-17 00:02:04 -07:00
David Tolnay 882d130e19 Test duplicates within a single attribute 2016-06-16 23:45:34 -07:00
David Tolnay 5f84e601b6 Add explanation of ignored errors in attr.rs 2016-06-16 23:25:46 -07:00
David Tolnay 0bf6a17428 Merge pull request #387 from erickt/master
Extend tuple impls up to 16 elements
2016-06-16 09:47:58 -07:00
Erick Tryzelaar db8881d845 Extend tuple impls up to 16 elements 2016-06-16 11:22:15 +01:00
David Tolnay 3403352749 Merge pull request #377 from dtolnay/travis
Remove some low-risk travis builds
2016-06-15 08:54:04 -07:00
David Tolnay ac69524258 Gather attrs at the beginning 2016-06-15 02:38:47 -07:00
David Tolnay 28589620f6 Error on duplicate attributes 2016-06-14 20:39:21 -07:00
David Tolnay 8e4da7f36b Merge pull request #383 from oli-obk/compile-fail
more cfail tests
2016-06-13 10:46:35 -07:00
Oliver Schneider 4c4a27f53c more cfail tests 2016-06-13 18:56:45 +02:00
Homu b838651ac9 Auto merge of #378 - dtolnay:str, r=oli-obk
Better error when deriving Deserialize for struct containing &str

Fixes #360. The error looks like this:

```rust
#[derive(Serialize, Deserialize)]
struct Test<'a> {
    s: &'a str,
}
```

```
src/main.rs:6:5: 6:15 error: Serde does not support deserializing fields of type &str; consider using String instead
src/main.rs:6     s: &'a str,
                  ^~~~~~~~~~
```
2016-06-14 00:49:26 +09:00
David Tolnay 5cd8212a61 Merge pull request #381 from dtolnay/nosyntex
Remove unnecessary Syntexes
2016-06-12 22:25:50 -07:00
David Tolnay c5f606f10f Remove unnecessary Syntexes 2016-06-12 15:50:45 -07:00
David Tolnay c21bea8b30 Better error when deriving Deserialize for struct containing &str 2016-06-11 21:32:53 -07:00
David Tolnay 22a26a33f4 Remove some low-risk travis builds 2016-06-11 16:21:20 -07:00
24 changed files with 1032 additions and 829 deletions
+6 -12
View File
@@ -1,3 +1,4 @@
sudo: false
language: rust
rust:
- stable
@@ -11,32 +12,25 @@ addons:
- libcurl4-openssl-dev
- libelf-dev
- libdw-dev
- binutils-dev
before_script:
- pip install 'travis-cargo<0.2' --user
- export PATH=$HOME/.local/bin:$PATH
script:
- (cd serde && travis-cargo build)
- (cd serde && travis-cargo test)
- (cd serde && travis-cargo --skip nightly test)
- (cd serde && travis-cargo --only nightly test -- --features nightly-testing)
- (cd serde && travis-cargo build -- --no-default-features)
- (cd serde && travis-cargo --only nightly build -- --no-default-features)
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features alloc)
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features collections)
- (cd serde_tests && travis-cargo test)
- (cd serde_tests && travis-cargo --skip nightly test)
- (cd serde_tests && travis-cargo --only nightly test -- --features nightly-testing)
- (cd serde_macros && travis-cargo --only nightly test -- --features nightly-testing)
- (cd serde_macros && travis-cargo --only nightly bench -- --features nightly-testing)
- (cd examples/serde-syntex-example && travis-cargo run)
- (cd examples/serde-syntex-example && travis-cargo --only nightly run -- --features nightly --no-default-features)
- (cd examples/serde-syntex-example && travis-cargo --skip nightly run)
- (cd examples/serde-syntex-example && travis-cargo --only nightly run -- --no-default-features --features nightly)
- (cd serde && travis-cargo --only stable doc)
- (cd serde_codegen && travis-cargo --only stable doc)
- (cd serde_macros && travis-cargo --only nightly doc)
after_success:
- (cd serde && travis-cargo --only stable doc-upload)
#- (cd serde_codegen && travis-cargo --only stable doc-upload)
#- (cd serde_macros && travis-cargo --only nightly doc-upload)
- (cd serde_tests && travis-cargo coveralls --no-sudo)
- (cd serde_tests && travis-cargo --only stable coveralls --no-sudo)
env:
global:
- TRAVIS_CARGO_NIGHTLY_FEATURE=""
+5 -9
View File
@@ -4,7 +4,7 @@ Serde Rust Serialization Framework
[![Build Status](https://api.travis-ci.org/serde-rs/serde.svg?branch=master)](https://travis-ci.org/serde-rs/serde)
[![Coverage Status](https://coveralls.io/repos/serde-rs/serde/badge.svg?branch=master&service=github)](https://coveralls.io/github/serde-rs/serde?branch=master)
[![Latest Version](https://img.shields.io/crates/v/serde.svg)](https://crates.io/crates/serde)
[![Clippy Linting Result](http://clippy.bashy.io/github/serde-rs/serde/master/badge.svg)](http://clippy.bashy.io/github/serde-rs/serde/master/log)
[![Clippy Linting Result](https://clippy.bashy.io/github/serde-rs/serde/master/badge.svg)](https://clippy.bashy.io/github/serde-rs/serde/master/log)
Serde is a powerful framework that enables serialization libraries to
generically serialize Rust data structures without the overhead of runtime type
@@ -74,12 +74,12 @@ When run, it produces:
Point { x: 1, y: 2 }
```
Using Serde with Stable Rust, syntex, and serde\_codegen
========================================================
Using Serde with Stable Rust and serde\_codegen
===============================================
Stable Rust is a little more complicated because it does not yet support
compiler plugins. Instead we need to use the code generation library
[syntex](https://github.com/serde-rs/syntex) for this:
compiler plugins. Instead we need to use `serde_codegen` which is based on the
code generation library [syntex](https://github.com/serde-rs/syntex):
```toml
[package]
@@ -90,7 +90,6 @@ build = "build.rs"
[build-dependencies]
serde_codegen = "*"
syntex = "*"
[dependencies]
serde = "*"
@@ -130,7 +129,6 @@ fn main() {
`build.rs`
```rust,ignore
extern crate syntex;
extern crate serde_codegen;
use std::env;
@@ -175,7 +173,6 @@ nightly = ["serde_macros"]
[build-dependencies]
serde_codegen = { version = "*", optional = true }
syntex = "*"
[dependencies]
serde = "*"
@@ -188,7 +185,6 @@ serde_macros = { version = "*", optional = true }
```rust,ignore
#[cfg(not(feature = "serde_macros"))]
mod inner {
extern crate syntex;
extern crate serde_codegen;
use std::env;
+3 -4
View File
@@ -9,10 +9,9 @@ default = ["serde_codegen"]
nightly = ["serde_macros"]
[build-dependencies]
serde_codegen = { version = "^0.7.10", optional = true }
syntex = "^0.33.0"
serde_codegen = { version = "^0.7.11", optional = true }
[dependencies]
serde = "^0.7.10"
serde = "^0.7.11"
serde_json = "^0.7.0"
serde_macros = { version = "^0.7.10", optional = true }
serde_macros = { version = "^0.7.11", optional = true }
-1
View File
@@ -1,6 +1,5 @@
#[cfg(not(feature = "serde_macros"))]
mod inner {
extern crate syntex;
extern crate serde_codegen;
use std::env;
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "serde"
version = "0.7.10"
version = "0.7.11"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
+4 -1
View File
@@ -646,7 +646,6 @@ array_impls! {
///////////////////////////////////////////////////////////////////////////////
macro_rules! tuple_impls {
() => {};
($($len:expr => $visitor:ident => ($($name:ident),+),)+) => {
$(
/// Construct a tuple visitor.
@@ -714,6 +713,10 @@ tuple_impls! {
10 => TupleVisitor10 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9),
11 => TupleVisitor11 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10),
12 => TupleVisitor12 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11),
13 => TupleVisitor13 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12),
14 => TupleVisitor14 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13),
15 => TupleVisitor15 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14),
16 => TupleVisitor16 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15),
}
///////////////////////////////////////////////////////////////////////////////
+1 -1
View File
@@ -635,7 +635,7 @@ pub trait Visitor {
Err(Error::invalid_type(Type::NewtypeStruct))
}
/// `visit_bool` deserializes a `SeqVisitor` into a `Value`.
/// `visit_seq` deserializes a `SeqVisitor` into a `Value`.
fn visit_seq<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor,
{
+66
View File
@@ -568,6 +568,72 @@ tuple_impls! {
10 => 10,
11 => 11,
}
TupleVisitor13 (13, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) {
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5,
6 => 6,
7 => 7,
8 => 8,
9 => 9,
10 => 10,
11 => 11,
12 => 12,
}
TupleVisitor14 (14, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) {
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5,
6 => 6,
7 => 7,
8 => 8,
9 => 9,
10 => 10,
11 => 11,
12 => 12,
13 => 13,
}
TupleVisitor15 (15, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) {
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5,
6 => 6,
7 => 7,
8 => 8,
9 => 9,
10 => 10,
11 => 11,
12 => 12,
13 => 13,
14 => 14,
}
TupleVisitor16 (16, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) {
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5,
6 => 6,
7 => 7,
8 => 8,
9 => 9,
10 => 10,
11 => 11,
12 => 12,
13 => 13,
14 => 14,
15 => 15,
}
}
///////////////////////////////////////////////////////////////////////////////
+17 -9
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen"
version = "0.7.10"
version = "0.7.11"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
@@ -14,16 +14,24 @@ include = ["Cargo.toml", "build.rs", "src/**/*.rs", "src/lib.rs.in"]
default = ["with-syntex"]
nightly = ["quasi_macros"]
nightly-testing = ["clippy"]
with-syntex = ["quasi/with-syntex", "quasi_codegen", "quasi_codegen/with-syntex", "syntex", "syntex_syntax"]
with-syntex = [
"quasi/with-syntex",
"quasi_codegen",
"quasi_codegen/with-syntex",
"serde_item/with-syntex",
"syntex",
"syntex_syntax",
]
[build-dependencies]
quasi_codegen = { version = "^0.12.0", optional = true }
syntex = { version = "^0.33.0", optional = true }
quasi_codegen = { version = "^0.13.0", optional = true }
syntex = { version = "^0.36.0", optional = true }
[dependencies]
aster = { version = "^0.18.0", default-features = false }
aster = { version = "^0.19.0", default-features = false }
clippy = { version = "^0.*", optional = true }
quasi = { version = "^0.12.0", default-features = false }
quasi_macros = { version = "^0.12.0", optional = true }
syntex = { version = "^0.35.0", optional = true }
syntex_syntax = { version = "^0.35.0", optional = true }
quasi = { version = "^0.13.0", default-features = false }
quasi_macros = { version = "^0.13.0", optional = true }
serde_item = { version = "^0.2.0", path = "../serde_item", default-features = false }
syntex = { version = "^0.36.0", optional = true }
syntex_syntax = { version = "^0.36.0", optional = true }
-1
View File
@@ -1,6 +1,5 @@
#[cfg(feature = "with-syntex")]
mod inner {
extern crate syntex;
extern crate quasi_codegen;
use std::env;
+16 -63
View File
@@ -3,12 +3,10 @@ use std::collections::HashSet;
use aster::AstBuilder;
use syntax::ast;
use syntax::ext::base::ExtCtxt;
use syntax::ptr::P;
use syntax::visit;
use attr;
use error::Error;
use item::{attr, Item};
// Remove the default from every type parameter because in the generated impls
// they look like associated types: "error: associated type bindings are not
@@ -35,39 +33,35 @@ pub fn with_where_predicates(
}
pub fn with_where_predicates_from_fields<F>(
cx: &ExtCtxt,
builder: &AstBuilder,
item: &ast::Item,
item: &Item,
generics: &ast::Generics,
from_field: F,
) -> Result<ast::Generics, Error>
where F: Fn(&attr::FieldAttrs) -> Option<&[ast::WherePredicate]>,
) -> ast::Generics
where F: Fn(&attr::Field) -> Option<&[ast::WherePredicate]>,
{
Ok(builder.from_generics(generics.clone())
builder.from_generics(generics.clone())
.with_predicates(
try!(all_fields_with_attrs(cx, item))
.iter()
.flat_map(|&(_, ref attrs)| from_field(attrs))
item.body.all_fields()
.flat_map(|field| from_field(&field.attrs))
.flat_map(|predicates| predicates.to_vec()))
.build())
.build()
}
pub fn with_bound<F>(
cx: &ExtCtxt,
builder: &AstBuilder,
item: &ast::Item,
item: &Item,
generics: &ast::Generics,
filter: F,
bound: &ast::Path,
) -> Result<ast::Generics, Error>
where F: Fn(&attr::FieldAttrs) -> bool,
) -> ast::Generics
where F: Fn(&attr::Field) -> bool,
{
Ok(builder.from_generics(generics.clone())
builder.from_generics(generics.clone())
.with_predicates(
try!(all_fields_with_attrs(cx, item))
.iter()
.filter(|&&(_, ref attrs)| filter(attrs))
.map(|&(ref field, _)| &field.ty)
item.body.all_fields()
.filter(|&field| filter(&field.attrs))
.map(|field| &field.ty)
// TODO this filter can be removed later, see comment on function
.filter(|ty| contains_generic(ty, generics))
.filter(|ty| !contains_recursion(ty, item.ident))
@@ -78,48 +72,7 @@ pub fn with_bound<F>(
// the bound e.g. Serialize
.bound().trait_(bound.clone()).build()
.build()))
.build())
}
fn all_fields_with_attrs(
cx: &ExtCtxt,
item: &ast::Item,
) -> Result<Vec<(ast::StructField, attr::FieldAttrs)>, Error> {
let fields: Vec<ast::StructField> =
all_variants(cx, item).iter()
.flat_map(|variant_data| all_struct_fields(variant_data))
.cloned()
.collect();
attr::fields_with_attrs(cx, &fields)
}
fn all_variants<'a>(cx: &ExtCtxt, item: &'a ast::Item) -> Vec<&'a ast::VariantData> {
match item.node {
ast::ItemKind::Struct(ref variant_data, _) => {
vec![variant_data]
}
ast::ItemKind::Enum(ref enum_def, _) => {
enum_def.variants.iter()
.map(|variant| &variant.node.data)
.collect()
}
_ => {
cx.span_bug(item.span, "expected Item to be Struct or Enum");
}
}
}
fn all_struct_fields(variant_data: &ast::VariantData) -> &[ast::StructField] {
match *variant_data {
ast::VariantData::Struct(ref fields, _) |
ast::VariantData::Tuple(ref fields, _) => {
fields
}
ast::VariantData::Unit(_) => {
&[]
}
}
.build()
}
// Rust <1.7 enforces that `where` clauses involve generic type parameters. The
+250 -279
View File
File diff suppressed because it is too large Load Diff
+2 -3
View File
@@ -7,6 +7,7 @@
extern crate aster;
extern crate quasi;
extern crate serde_item as item;
#[cfg(feature = "with-syntex")]
extern crate syntex;
@@ -22,8 +23,6 @@ extern crate syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_plugin;
#[cfg(feature = "with-syntex")]
use std::io;
#[cfg(feature = "with-syntex")]
use std::path::Path;
@@ -37,7 +36,7 @@ include!(concat!(env!("OUT_DIR"), "/lib.rs"));
include!("lib.rs.in");
#[cfg(feature = "with-syntex")]
pub fn expand<S, D>(src: S, dst: D) -> io::Result<()>
pub fn expand<S, D>(src: S, dst: D) -> Result<(), syntex::Error>
where S: AsRef<Path>,
D: AsRef<Path>,
{
-1
View File
@@ -1,4 +1,3 @@
mod attr;
mod bound;
mod de;
mod error;
+195 -254
View File
@@ -1,18 +1,12 @@
use aster;
use syntax::ast::{
Ident,
MetaItem,
Item,
};
use syntax::ast;
use syntax::ast::{self, Ident, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ptr::P;
use attr;
use bound;
use error::Error;
use item::{self, attr};
pub fn expand_derive_serialize(
cx: &mut ExtCtxt,
@@ -31,55 +25,43 @@ pub fn expand_derive_serialize(
}
};
let builder = aster::AstBuilder::new().span(span);
let impl_item = match serialize_item(cx, &builder, &item) {
let item = match item::Item::from_ast(cx, item) {
Ok(item) => item,
Err(Error) => {
// An error occured, but it should have been reported already.
Err(item::Error::UnexpectedItemKind) => {
cx.span_err(item.span,
"`#[derive(Serialize)]` may only be applied to structs and enums");
return;
}
};
let builder = aster::AstBuilder::new().span(span);
let impl_item = serialize_item(cx, &builder, &item);
push(Annotatable::Item(impl_item))
}
fn serialize_item(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item: &Item,
) -> Result<P<ast::Item>, 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 container_attrs = try!(attr::ContainerAttrs::from_item(cx, item));
let impl_generics = try!(build_impl_generics(cx, builder, item, generics, &container_attrs));
item: &item::Item,
) -> P<ast::Item> {
let impl_generics = build_impl_generics(builder, &item);
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(),
&container_attrs));
let body = serialize_body(cx,
builder,
&item,
&impl_generics,
ty.clone());
let where_clause = &impl_generics.where_clause;
let dummy_const = builder.id(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
Ok(quote_item!(cx,
quote_item!(cx,
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const $dummy_const: () = {
extern crate serde as _serde;
@@ -92,34 +74,29 @@ fn serialize_item(
}
}
};
).unwrap())
).unwrap()
}
// All the generics in the input, plus a bound `T: Serialize` for each generic
// field type that will be serialized by us.
fn build_impl_generics(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item: &Item,
generics: &ast::Generics,
container_attrs: &attr::ContainerAttrs,
) -> Result<ast::Generics, Error> {
let generics = bound::without_defaults(generics);
item: &item::Item,
) -> ast::Generics {
let generics = bound::without_defaults(item.generics);
let generics = try!(bound::with_where_predicates_from_fields(
cx, builder, item, &generics,
|attrs| attrs.ser_bound()));
let generics = bound::with_where_predicates_from_fields(
builder, item, &generics,
|attrs| attrs.ser_bound());
match container_attrs.ser_bound() {
match item.attrs.ser_bound() {
Some(predicates) => {
let generics = bound::with_where_predicates(builder, &generics, predicates);
Ok(generics)
bound::with_where_predicates(builder, &generics, predicates)
}
None => {
let generics = try!(bound::with_bound(cx, builder, item, &generics,
bound::with_bound(builder, item, &generics,
needs_serialize_bound,
&builder.path().ids(&["_serde", "ser", "Serialize"]).build()));
Ok(generics)
&builder.path().ids(&["_serde", "ser", "Serialize"]).build())
}
}
}
@@ -128,8 +105,8 @@ fn build_impl_generics(
// serialized by us so we do not generate a bound. Fields with a `bound`
// attribute specify their own bound so we do not generate one. All other fields
// may need a `T: Serialize` bound where T is the type of the field.
fn needs_serialize_bound(attrs: &attr::FieldAttrs) -> bool {
!attrs.skip_serializing_field()
fn needs_serialize_bound(attrs: &attr::Field) -> bool {
!attrs.skip_serializing()
&& attrs.serialize_with().is_none()
&& attrs.ser_bound().is_none()
}
@@ -137,130 +114,96 @@ fn needs_serialize_bound(attrs: &attr::FieldAttrs) -> bool {
fn serialize_body(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item: &Item,
item: &item::Item,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
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, _) => {
) -> P<ast::Expr> {
match item.body {
item::Body::Enum(ref variants) => {
serialize_item_enum(
cx,
builder,
item.ident,
impl_generics,
ty,
enum_def,
container_attrs,
)
variants,
&item.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<ast::Ty>,
span: Span,
variant_data: &ast::VariantData,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, 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,
&builder,
impl_generics,
ty,
&fields[0],
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,
container_attrs,
)
}
ast::VariantData::Struct(ref fields, _) => {
item::Body::Struct(item::Style::Struct, ref fields) => {
if fields.iter().any(|field| field.ident.is_none()) {
cx.span_bug(span, "struct has unnamed fields")
cx.span_bug(item.span, "struct has unnamed fields")
}
serialize_struct(
cx,
&builder,
builder,
impl_generics,
ty,
fields,
container_attrs,
)
&item.attrs)
}
item::Body::Struct(item::Style::Tuple, ref fields) => {
if fields.iter().any(|field| field.ident.is_some()) {
cx.span_bug(item.span, "tuple struct has named fields")
}
serialize_tuple_struct(
cx,
builder,
impl_generics,
ty,
fields,
&item.attrs)
}
item::Body::Struct(item::Style::Newtype, ref fields) => {
serialize_newtype_struct(
cx,
builder,
impl_generics,
ty,
&fields[0],
&item.attrs)
}
item::Body::Struct(item::Style::Unit, _) => {
serialize_unit_struct(
cx,
builder,
&item.attrs)
}
}
}
fn serialize_unit_struct(
cx: &ExtCtxt,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
let type_name = container_attrs.name().serialize_name_expr();
builder: &aster::AstBuilder,
item_attrs: &attr::Item,
) -> P<ast::Expr> {
let type_name = name_expr(builder, item_attrs.name());
Ok(quote_expr!(cx,
quote_expr!(cx,
_serializer.serialize_unit_struct($type_name)
))
)
}
fn serialize_newtype_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
container_ty: P<ast::Ty>,
field: &ast::StructField,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
let type_name = container_attrs.name().serialize_name_expr();
let attrs = try!(attr::FieldAttrs::from_field(cx, 0, field));
item_ty: P<ast::Ty>,
field: &item::Field,
item_attrs: &attr::Item,
) -> P<ast::Expr> {
let type_name = name_expr(builder, item_attrs.name());
let mut field_expr = quote_expr!(cx, &self.0);
if let Some(path) = attrs.serialize_with() {
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&container_ty, impl_generics, &field.ty, path, field_expr);
&item_ty, impl_generics, &field.ty, path, field_expr);
}
Ok(quote_expr!(cx,
quote_expr!(cx,
_serializer.serialize_newtype_struct($type_name, $field_expr)
))
)
}
fn serialize_tuple_struct(
@@ -268,10 +211,10 @@ fn serialize_tuple_struct(
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
fields: &[ast::StructField],
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
let (visitor_struct, visitor_impl) = try!(serialize_tuple_struct_visitor(
fields: &[item::Field],
item_attrs: &attr::Item,
) -> P<ast::Expr> {
let (visitor_struct, visitor_impl) = serialize_tuple_struct_visitor(
cx,
builder,
ty.clone(),
@@ -283,11 +226,11 @@ fn serialize_tuple_struct(
fields,
impl_generics,
false,
));
);
let type_name = container_attrs.name().serialize_name_expr();
let type_name = name_expr(builder, item_attrs.name());
Ok(quote_expr!(cx, {
quote_expr!(cx, {
$visitor_struct
$visitor_impl
_serializer.serialize_tuple_struct($type_name, Visitor {
@@ -295,7 +238,7 @@ fn serialize_tuple_struct(
state: 0,
_structure_ty: ::std::marker::PhantomData::<&$ty>,
})
}))
})
}
fn serialize_struct(
@@ -303,10 +246,10 @@ fn serialize_struct(
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
fields: &[ast::StructField],
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
let (visitor_struct, visitor_impl) = try!(serialize_struct_visitor(
fields: &[item::Field],
item_attrs: &attr::Item,
) -> P<ast::Expr> {
let (visitor_struct, visitor_impl) = serialize_struct_visitor(
cx,
builder,
ty.clone(),
@@ -318,11 +261,11 @@ fn serialize_struct(
fields,
impl_generics,
false,
));
);
let type_name = container_attrs.name().serialize_name_expr();
let type_name = name_expr(builder, item_attrs.name());
Ok(quote_expr!(cx, {
quote_expr!(cx, {
$visitor_struct
$visitor_impl
_serializer.serialize_struct($type_name, Visitor {
@@ -330,7 +273,7 @@ fn serialize_struct(
state: 0,
_structure_ty: ::std::marker::PhantomData::<&$ty>,
})
}))
})
}
fn serialize_item_enum(
@@ -339,11 +282,11 @@ fn serialize_item_enum(
type_ident: Ident,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
enum_def: &ast::EnumDef,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
let arms: Vec<_> = try!(
enum_def.variants.iter()
variants: &[item::Variant],
item_attrs: &attr::Item,
) -> P<ast::Expr> {
let arms: Vec<_> =
variants.iter()
.enumerate()
.map(|(variant_index, variant)| {
serialize_variant(
@@ -354,17 +297,16 @@ fn serialize_item_enum(
ty.clone(),
variant,
variant_index,
container_attrs,
item_attrs,
)
})
.collect()
);
.collect();
Ok(quote_expr!(cx,
quote_expr!(cx,
match *self {
$arms
}
))
)
}
fn serialize_variant(
@@ -373,19 +315,18 @@ fn serialize_variant(
type_ident: Ident,
generics: &ast::Generics,
ty: P<ast::Ty>,
variant: &ast::Variant,
variant: &item::Variant,
variant_index: usize,
container_attrs: &attr::ContainerAttrs,
) -> Result<ast::Arm, Error> {
let type_name = container_attrs.name().serialize_name_expr();
item_attrs: &attr::Item,
) -> ast::Arm {
let type_name = name_expr(builder, item_attrs.name());
let variant_ident = variant.node.name;
let variant_attrs = try!(attr::VariantAttrs::from_variant(cx, variant));
let variant_name = variant_attrs.name().serialize_name_expr();
let variant_ident = variant.ident;
let variant_name = name_expr(builder, variant.attrs.name());
match variant.node.data {
ast::VariantData::Unit(_) => {
Ok(quote_arm!(cx,
match variant.style {
item::Style::Unit => {
quote_arm!(cx,
$type_ident::$variant_ident => {
_serde::ser::Serializer::serialize_unit_variant(
_serializer,
@@ -394,10 +335,10 @@ fn serialize_variant(
$variant_name,
)
}
))
)
},
ast::VariantData::Tuple(ref fields, _) if fields.len() == 1 => {
let expr = try!(serialize_newtype_variant(
item::Style::Newtype => {
let expr = serialize_newtype_variant(
cx,
builder,
type_name,
@@ -405,15 +346,15 @@ fn serialize_variant(
variant_name,
ty,
generics,
&fields[0],
));
&variant.fields[0],
);
Ok(quote_arm!(cx,
quote_arm!(cx,
$type_ident::$variant_ident(ref __simple_value) => { $expr }
))
)
},
ast::VariantData::Tuple(ref fields, _) => {
let field_names: Vec<ast::Ident> = (0 .. fields.len())
item::Style::Tuple => {
let field_names: Vec<ast::Ident> = (0 .. variant.fields.len())
.map(|i| builder.id(format!("__field{}", i)))
.collect();
@@ -425,7 +366,7 @@ fn serialize_variant(
)
.build();
let expr = try!(serialize_tuple_variant(
let expr = serialize_tuple_variant(
cx,
builder,
type_name,
@@ -433,16 +374,16 @@ fn serialize_variant(
variant_name,
generics,
ty,
fields,
&variant.fields,
field_names,
));
);
Ok(quote_arm!(cx,
quote_arm!(cx,
$pat => { $expr }
))
)
}
ast::VariantData::Struct(ref fields, _) => {
let field_names: Vec<_> = (0 .. fields.len())
item::Style::Struct => {
let field_names: Vec<_> = (0 .. variant.fields.len())
.map(|i| builder.id(format!("__field{}", i)))
.collect();
@@ -450,7 +391,7 @@ fn serialize_variant(
.id(type_ident).id(variant_ident).build()
.with_pats(
field_names.iter()
.zip(fields.iter())
.zip(variant.fields.iter())
.map(|(id, field)| {
let name = match field.ident {
Some(name) => name,
@@ -464,21 +405,21 @@ fn serialize_variant(
)
.build();
let expr = try!(serialize_struct_variant(
let expr = serialize_struct_variant(
cx,
builder,
variant_index,
variant_name,
generics,
ty,
fields,
&variant.fields,
field_names,
container_attrs,
));
item_attrs,
);
Ok(quote_arm!(cx,
quote_arm!(cx,
$pat => { $expr }
))
)
}
}
}
@@ -489,19 +430,17 @@ fn serialize_newtype_variant(
type_name: P<ast::Expr>,
variant_index: usize,
variant_name: P<ast::Expr>,
container_ty: P<ast::Ty>,
item_ty: P<ast::Ty>,
generics: &ast::Generics,
field: &ast::StructField,
) -> Result<P<ast::Expr>, Error> {
let attrs = try!(attr::FieldAttrs::from_field(cx, 0, field));
field: &item::Field,
) -> P<ast::Expr> {
let mut field_expr = quote_expr!(cx, __simple_value);
if let Some(path) = attrs.serialize_with() {
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&container_ty, generics, &field.ty, path, field_expr);
&item_ty, generics, &field.ty, path, field_expr);
}
Ok(quote_expr!(cx,
quote_expr!(cx,
_serde::ser::Serializer::serialize_newtype_variant(
_serializer,
$type_name,
@@ -509,7 +448,7 @@ fn serialize_newtype_variant(
$variant_name,
$field_expr,
)
))
)
}
fn serialize_tuple_variant(
@@ -520,9 +459,9 @@ fn serialize_tuple_variant(
variant_name: P<ast::Expr>,
generics: &ast::Generics,
structure_ty: P<ast::Ty>,
fields: &[ast::StructField],
fields: &[item::Field],
field_names: Vec<Ident>,
) -> Result<P<ast::Expr>, Error> {
) -> P<ast::Expr> {
let variant_ty = builder.ty().tuple()
.with_tys(
fields.iter().map(|field| {
@@ -534,7 +473,7 @@ fn serialize_tuple_variant(
)
.build();
let (visitor_struct, visitor_impl) = try!(serialize_tuple_struct_visitor(
let (visitor_struct, visitor_impl) = serialize_tuple_struct_visitor(
cx,
builder,
structure_ty.clone(),
@@ -543,7 +482,7 @@ fn serialize_tuple_variant(
fields,
generics,
true,
));
);
let value_expr = builder.expr().tuple()
.with_exprs(
@@ -553,7 +492,7 @@ fn serialize_tuple_variant(
)
.build();
Ok(quote_expr!(cx, {
quote_expr!(cx, {
$visitor_struct
$visitor_impl
_serializer.serialize_tuple_variant($type_name, $variant_index, $variant_name, Visitor {
@@ -561,7 +500,7 @@ fn serialize_tuple_variant(
state: 0,
_structure_ty: ::std::marker::PhantomData::<&$structure_ty>,
})
}))
})
}
fn serialize_struct_variant(
@@ -571,10 +510,10 @@ fn serialize_struct_variant(
variant_name: P<ast::Expr>,
generics: &ast::Generics,
ty: P<ast::Ty>,
fields: &[ast::StructField],
fields: &[item::Field],
field_names: Vec<Ident>,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
item_attrs: &attr::Item,
) -> P<ast::Expr> {
let variant_generics = builder.generics()
.with(generics.clone())
.add_lifetime_bound("'__serde_variant")
@@ -586,7 +525,6 @@ fn serialize_struct_variant(
.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")
@@ -623,7 +561,7 @@ fn serialize_struct_variant(
.build()
.build();
let (visitor_struct, visitor_impl) = try!(serialize_struct_visitor(
let (visitor_struct, visitor_impl) = serialize_struct_visitor(
cx,
builder,
variant_ty.clone(),
@@ -632,16 +570,16 @@ fn serialize_struct_variant(
fields,
&variant_generics,
true,
));
);
let container_name = container_attrs.name().serialize_name_expr();
let item_name = name_expr(builder, item_attrs.name());
Ok(quote_expr!(cx, {
quote_expr!(cx, {
$variant_struct
$visitor_struct
$visitor_impl
_serializer.serialize_struct_variant(
$container_name,
$item_name,
$variant_index,
$variant_name,
Visitor {
@@ -650,7 +588,7 @@ fn serialize_struct_variant(
_structure_ty: ::std::marker::PhantomData,
},
)
}))
})
}
fn serialize_tuple_struct_visitor(
@@ -659,24 +597,22 @@ fn serialize_tuple_struct_visitor(
structure_ty: P<ast::Ty>,
variant_ty: P<ast::Ty>,
serializer_method: ast::Ident,
fields: &[ast::StructField],
fields: &[item::Field],
generics: &ast::Generics,
is_enum: bool,
) -> Result<(P<ast::Item>, P<ast::Item>), Error> {
let fields_with_attrs = try!(attr::fields_with_attrs(cx, fields));
let arms: Vec<_> = fields_with_attrs.iter()
) -> (P<ast::Item>, P<ast::Item>) {
let arms: Vec<_> = fields.iter()
.enumerate()
.map(|(i, &(ref field, ref attrs))| {
.map(|(i, field)| {
let mut field_expr = builder.expr().tup_field(i).field("value").self_();
if !is_enum {
field_expr = quote_expr!(cx, &$field_expr);
}
let continue_if_skip = attrs.skip_serializing_if()
let continue_if_skip = field.attrs.skip_serializing_if()
.map(|path| quote_stmt!(cx, if $path($field_expr) { continue }));
if let Some(path) = attrs.serialize_with() {
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&structure_ty, generics, &field.ty, path, field_expr);
}
@@ -704,7 +640,7 @@ fn serialize_tuple_struct_visitor(
let nfields = fields.len();
Ok((
(
quote_item!(cx,
struct Visitor $visitor_impl_generics $where_clause {
state: usize,
@@ -733,7 +669,7 @@ fn serialize_tuple_struct_visitor(
}
}
).unwrap(),
))
)
}
fn serialize_struct_visitor(
@@ -742,28 +678,26 @@ fn serialize_struct_visitor(
structure_ty: P<ast::Ty>,
variant_ty: P<ast::Ty>,
serializer_method: ast::Ident,
fields: &[ast::StructField],
fields: &[item::Field],
generics: &ast::Generics,
is_enum: bool,
) -> Result<(P<ast::Item>, P<ast::Item>), Error> {
let fields_with_attrs = try!(attr::fields_with_attrs(cx, fields));
let arms: Vec<ast::Arm> = fields_with_attrs.iter()
.filter(|&&(_, ref attrs)| !attrs.skip_serializing_field())
) -> (P<ast::Item>, P<ast::Item>) {
let arms: Vec<ast::Arm> = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.enumerate()
.map(|(i, &(ref field, ref attrs))| {
.map(|(i, field)| {
let ident = field.ident.expect("struct has unnamed field");
let mut field_expr = quote_expr!(cx, self.value.$ident);
if !is_enum {
field_expr = quote_expr!(cx, &$field_expr);
}
let key_expr = attrs.name().serialize_name_expr();
let key_expr = name_expr(builder, field.attrs.name());
let continue_if_skip = attrs.skip_serializing_if()
let continue_if_skip = field.attrs.skip_serializing_if()
.map(|path| quote_stmt!(cx, if $path($field_expr) { continue }));
if let Some(path) = attrs.serialize_with() {
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&structure_ty, generics, &field.ty, path, field_expr)
}
@@ -793,23 +727,23 @@ fn serialize_struct_visitor(
.strip_bounds()
.build();
let len = fields_with_attrs.iter()
.filter(|&&(_, ref attrs)| !attrs.skip_serializing_field())
.map(|&(ref field, ref attrs)| {
let len = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.map(|field| {
let ident = field.ident.expect("struct has unnamed fields");
let mut field_expr = quote_expr!(cx, self.value.$ident);
if !is_enum {
field_expr = quote_expr!(cx, &$field_expr);
}
match attrs.skip_serializing_if() {
match field.attrs.skip_serializing_if() {
Some(path) => quote_expr!(cx, if $path($field_expr) { 0 } else { 1 }),
None => quote_expr!(cx, 1),
}
})
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
Ok((
(
quote_item!(cx,
struct Visitor $visitor_impl_generics $where_clause {
state: usize,
@@ -841,13 +775,13 @@ fn serialize_struct_visitor(
}
}
).unwrap(),
))
)
}
fn wrap_serialize_with(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
container_ty: &P<ast::Ty>,
item_ty: &P<ast::Ty>,
generics: &ast::Generics,
field_ty: &P<ast::Ty>,
path: &ast::Path,
@@ -869,7 +803,7 @@ fn wrap_serialize_with(
quote_expr!(cx, {
struct __SerializeWith $wrapper_generics $where_clause {
value: &'__a $field_ty,
phantom: ::std::marker::PhantomData<$container_ty>,
phantom: ::std::marker::PhantomData<$item_ty>,
}
impl $wrapper_generics _serde::ser::Serialize for $wrapper_ty $where_clause {
@@ -882,7 +816,14 @@ fn wrap_serialize_with(
__SerializeWith {
value: $value,
phantom: ::std::marker::PhantomData::<$container_ty>,
phantom: ::std::marker::PhantomData::<$item_ty>,
}
})
}
fn name_expr(
builder: &aster::AstBuilder,
name: &attr::Name,
) -> P<ast::Expr> {
builder.expr().str(name.serialize_name())
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "serde_item"
version = "0.2.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "AST representation used by Serde codegen. Unstable."
repository = "https://github.com/serde-rs/serde"
documentation = "https://github.com/serde-rs/serde"
keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
[features]
default = ["with-syntex"]
nightly-testing = ["clippy"]
with-syntex = ["syntex_syntax"]
[dependencies]
clippy = { version = "^0.*", optional = true }
syntex_syntax = { version = "^0.36.0", optional = true }
@@ -1,7 +1,8 @@
use std::rc::Rc;
use syntax::ast::{self, TokenTree};
use syntax::attr;
use syntax::codemap::Span;
use syntax::codemap::{Span, Spanned, respan};
use syntax::ext::base::ExtCtxt;
use syntax::fold::Folder;
use syntax::parse::parser::{Parser, PathStyle};
@@ -10,113 +11,152 @@ use syntax::parse;
use syntax::print::pprust::{lit_to_string, meta_item_to_string};
use syntax::ptr::P;
use aster::AstBuilder;
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
// are `attr::Item::from_ast`, `attr::Variant::from_ast`, and
// `attr::Field::from_ast`. Each returns an instance of the corresponding
// struct. Note that none of them return a Result. Unrecognized, malformed, or
// duplicated attributes result in a span_err but otherwise are ignored. The
// user will see errors simultaneously for all bad attributes in the crate
// rather than just the first.
use error::Error;
struct Attr<'a, 'b: 'a, T> {
cx: &'a ExtCtxt<'b>,
name: &'static str,
value: Option<Spanned<T>>,
}
impl<'a, 'b, T> Attr<'a, 'b, T> {
fn none(cx: &'a ExtCtxt<'b>, name: &'static str) -> Self {
Attr {
cx: cx,
name: name,
value: None,
}
}
fn set(&mut self, span: Span, t: T) {
if let Some(Spanned { span: prev_span, .. }) = self.value {
let mut err = self.cx.struct_span_err(
span,
&format!("duplicate serde attribute `{}`", self.name));
err.span_help(prev_span, "previously set here");
err.emit();
} else {
self.value = Some(respan(span, t));
}
}
fn set_opt(&mut self, v: Option<Spanned<T>>) {
if let Some(v) = v {
self.set(v.span, v.node);
}
}
fn set_if_none(&mut self, span: Span, t: T) {
if self.value.is_none() {
self.value = Some(respan(span, t));
}
}
fn get(self) -> Option<T> {
self.value.map(|spanned| spanned.node)
}
fn get_spanned(self) -> Option<Spanned<T>> {
self.value
}
}
struct BoolAttr<'a, 'b: 'a>(Attr<'a, 'b, ()>);
impl<'a, 'b> BoolAttr<'a, 'b> {
fn none(cx: &'a ExtCtxt<'b>, name: &'static str) -> Self {
BoolAttr(Attr::none(cx, name))
}
fn set_true(&mut self, span: Span) {
self.0.set(span, ());
}
fn get(&self) -> bool {
self.0.value.is_some()
}
}
#[derive(Debug)]
pub struct Name {
ident: ast::Ident,
serialize_name: Option<InternedString>,
deserialize_name: Option<InternedString>,
serialize: InternedString,
deserialize: InternedString,
}
impl Name {
fn new(ident: ast::Ident) -> Self {
Name {
ident: ident,
serialize_name: None,
deserialize_name: None,
}
}
/// Return the container name for the container when serializing.
pub fn serialize_name(&self) -> InternedString {
match self.serialize_name {
Some(ref name) => name.clone(),
None => self.ident.name.as_str(),
}
}
/// Return the container name expression for the container when deserializing.
pub fn serialize_name_expr(&self) -> P<ast::Expr> {
AstBuilder::new().expr().str(self.serialize_name())
self.serialize.clone()
}
/// Return the container name for the container when deserializing.
pub fn deserialize_name(&self) -> InternedString {
match self.deserialize_name {
Some(ref name) => name.clone(),
None => self.ident.name.as_str(),
}
}
/// Return the container name expression for the container when deserializing.
pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
AstBuilder::new().expr().str(self.deserialize_name())
self.deserialize.clone()
}
}
/// Represents container (e.g. struct) attribute information
#[derive(Debug)]
pub struct ContainerAttrs {
pub struct Item {
name: Name,
deny_unknown_fields: bool,
ser_bound: Option<Vec<ast::WherePredicate>>,
de_bound: Option<Vec<ast::WherePredicate>>,
}
impl ContainerAttrs {
impl Item {
/// Extract out the `#[serde(...)]` attributes from an item.
pub fn from_item(cx: &ExtCtxt, item: &ast::Item) -> Result<Self, Error> {
let mut container_attrs = ContainerAttrs {
name: Name::new(item.ident),
deny_unknown_fields: false,
ser_bound: None,
de_bound: None,
};
pub fn from_ast(cx: &ExtCtxt, item: &ast::Item) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
let mut ser_bound = Attr::none(cx, "bound");
let mut de_bound = Attr::none(cx, "bound");
let ident = item.ident.name.as_str();
for meta_items in item.attrs().iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
let span = meta_item.span;
match meta_item.node {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
let s = try!(get_str_from_lit(cx, name, lit));
container_attrs.name.serialize_name = Some(s.clone());
container_attrs.name.deserialize_name = Some(s);
if let Ok(s) = get_str_from_lit(cx, name, lit) {
ser_name.set(span, s.clone());
de_name.set(span, s);
}
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items));
if ser_name.is_some() {
container_attrs.name.serialize_name = ser_name;
}
if de_name.is_some() {
container_attrs.name.deserialize_name = de_name;
if let Ok((ser, de)) = get_renames(cx, meta_items) {
ser_name.set_opt(ser);
de_name.set_opt(de);
}
}
// Parse `#[serde(deny_unknown_fields)]`
ast::MetaItemKind::Word(ref name) if name == &"deny_unknown_fields" => {
container_attrs.deny_unknown_fields = true;
deny_unknown_fields.set_true(span);
}
// Parse `#[serde(bound="D: Serialize")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"bound" => {
let where_predicates = try!(parse_lit_into_where(cx, name, lit));
container_attrs.ser_bound = Some(where_predicates.clone());
container_attrs.de_bound = Some(where_predicates);
if let Ok(where_predicates) = parse_lit_into_where(cx, name, lit) {
ser_bound.set(span, where_predicates.clone());
de_bound.set(span, where_predicates);
}
}
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"bound" => {
let (ser_bound, de_bound) = try!(get_where_predicates(cx, meta_items));
if ser_bound.is_some() {
container_attrs.ser_bound = ser_bound;
}
if de_bound.is_some() {
container_attrs.de_bound = de_bound;
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
ser_bound.set_opt(ser);
de_bound.set_opt(de);
}
}
@@ -125,14 +165,20 @@ impl ContainerAttrs {
meta_item.span,
&format!("unknown serde container attribute `{}`",
meta_item_to_string(meta_item)));
return Err(Error);
}
}
}
}
Ok(container_attrs)
Item {
name: Name {
serialize: ser_name.get().unwrap_or(ident.clone()),
deserialize: de_name.get().unwrap_or(ident),
},
deny_unknown_fields: deny_unknown_fields.get(),
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
}
}
pub fn name(&self) -> &Name {
@@ -154,34 +200,34 @@ impl ContainerAttrs {
/// Represents variant attribute information
#[derive(Debug)]
pub struct VariantAttrs {
pub struct Variant {
name: Name,
}
impl VariantAttrs {
pub fn from_variant(cx: &ExtCtxt, variant: &ast::Variant) -> Result<Self, Error> {
let mut variant_attrs = VariantAttrs {
name: Name::new(variant.node.name),
};
impl Variant {
pub fn from_ast(cx: &ExtCtxt, variant: &ast::Variant) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let ident = variant.node.name.name.as_str();
for meta_items in variant.node.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
let span = meta_item.span;
match meta_item.node {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
let s = try!(get_str_from_lit(cx, name, lit));
variant_attrs.name.serialize_name = Some(s.clone());
variant_attrs.name.deserialize_name = Some(s);
if let Ok(s) = get_str_from_lit(cx, name, lit) {
ser_name.set(span, s.clone());
de_name.set(span, s);
}
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items));
if ser_name.is_some() {
variant_attrs.name.serialize_name = ser_name;
}
if de_name.is_some() {
variant_attrs.name.deserialize_name = de_name;
if let Ok((ser, de)) = get_renames(cx, meta_items) {
ser_name.set_opt(ser);
de_name.set_opt(de);
}
}
@@ -190,14 +236,17 @@ impl VariantAttrs {
meta_item.span,
&format!("unknown serde variant attribute `{}`",
meta_item_to_string(meta_item)));
return Err(Error);
}
}
}
}
Ok(variant_attrs)
Variant {
name: Name {
serialize: ser_name.get().unwrap_or(ident.clone()),
deserialize: de_name.get().unwrap_or(ident),
},
}
}
pub fn name(&self) -> &Name {
@@ -207,10 +256,10 @@ impl VariantAttrs {
/// Represents field attribute information
#[derive(Debug)]
pub struct FieldAttrs {
pub struct Field {
name: Name,
skip_serializing_field: bool,
skip_deserializing_field: bool,
skip_serializing: bool,
skip_deserializing: bool,
skip_serializing_if: Option<ast::Path>,
default: FieldDefault,
serialize_with: Option<ast::Path>,
@@ -230,111 +279,103 @@ pub enum FieldDefault {
Path(ast::Path),
}
impl FieldAttrs {
impl Field {
/// Extract out the `#[serde(...)]` attributes from a struct field.
pub fn from_field(cx: &ExtCtxt,
index: usize,
field: &ast::StructField) -> Result<Self, Error> {
let builder = AstBuilder::new();
pub fn from_ast(cx: &ExtCtxt,
index: usize,
field: &ast::StructField) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing");
let mut skip_serializing_if = Attr::none(cx, "skip_serializing_if");
let mut default = Attr::none(cx, "default");
let mut serialize_with = Attr::none(cx, "serialize_with");
let mut deserialize_with = Attr::none(cx, "deserialize_with");
let mut ser_bound = Attr::none(cx, "bound");
let mut de_bound = Attr::none(cx, "bound");
let field_ident = match field.ident {
Some(ident) => ident,
None => builder.id(index.to_string()),
};
let mut field_attrs = FieldAttrs {
name: Name::new(field_ident),
skip_serializing_field: false,
skip_deserializing_field: false,
skip_serializing_if: None,
default: FieldDefault::None,
serialize_with: None,
deserialize_with: None,
ser_bound: None,
de_bound: None,
let ident = match field.ident {
Some(ident) => ident.name.as_str(),
None => token::intern_and_get_ident(&index.to_string()),
};
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
let span = meta_item.span;
match meta_item.node {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
let s = try!(get_str_from_lit(cx, name, lit));
field_attrs.name.serialize_name = Some(s.clone());
field_attrs.name.deserialize_name = Some(s);
if let Ok(s) = get_str_from_lit(cx, name, lit) {
ser_name.set(span, s.clone());
de_name.set(span, s);
}
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items));
if ser_name.is_some() {
field_attrs.name.serialize_name = ser_name;
}
if de_name.is_some() {
field_attrs.name.deserialize_name = de_name;
if let Ok((ser, de)) = get_renames(cx, meta_items) {
ser_name.set_opt(ser);
de_name.set_opt(de);
}
}
// Parse `#[serde(default)]`
ast::MetaItemKind::Word(ref name) if name == &"default" => {
field_attrs.default = FieldDefault::Default;
default.set(span, FieldDefault::Default);
}
// Parse `#[serde(default="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"default" => {
let path = try!(parse_lit_into_path(cx, name, lit));
field_attrs.default = FieldDefault::Path(path);
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
default.set(span, FieldDefault::Path(path));
}
}
// Parse `#[serde(skip_serializing)]`
ast::MetaItemKind::Word(ref name) if name == &"skip_serializing" => {
field_attrs.skip_serializing_field = true;
skip_serializing.set_true(span);
}
// Parse `#[serde(skip_deserializing)]`
ast::MetaItemKind::Word(ref name) if name == &"skip_deserializing" => {
field_attrs.skip_deserializing_field = true;
// Initialize field to Default::default() unless a different
// default is specified by `#[serde(default="...")]`
if field_attrs.default == FieldDefault::None {
field_attrs.default = FieldDefault::Default;
}
skip_deserializing.set_true(span);
}
// Parse `#[serde(skip_serializing_if="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"skip_serializing_if" => {
let path = try!(parse_lit_into_path(cx, name, lit));
field_attrs.skip_serializing_if = Some(path);
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
skip_serializing_if.set(span, path);
}
}
// Parse `#[serde(serialize_with="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize_with" => {
let path = try!(parse_lit_into_path(cx, name, lit));
field_attrs.serialize_with = Some(path);
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
serialize_with.set(span, path);
}
}
// Parse `#[serde(deserialize_with="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize_with" => {
let path = try!(parse_lit_into_path(cx, name, lit));
field_attrs.deserialize_with = Some(path);
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
deserialize_with.set(span, path);
}
}
// Parse `#[serde(bound="D: Serialize")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"bound" => {
let where_predicates = try!(parse_lit_into_where(cx, name, lit));
field_attrs.ser_bound = Some(where_predicates.clone());
field_attrs.de_bound = Some(where_predicates);
if let Ok(where_predicates) = parse_lit_into_where(cx, name, lit) {
ser_bound.set(span, where_predicates.clone());
de_bound.set(span, where_predicates);
}
}
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"bound" => {
let (ser_bound, de_bound) = try!(get_where_predicates(cx, meta_items));
if ser_bound.is_some() {
field_attrs.ser_bound = ser_bound;
}
if de_bound.is_some() {
field_attrs.de_bound = de_bound;
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
ser_bound.set_opt(ser);
de_bound.set_opt(de);
}
}
@@ -343,26 +384,43 @@ impl FieldAttrs {
meta_item.span,
&format!("unknown serde field attribute `{}`",
meta_item_to_string(meta_item)));
return Err(Error);
}
}
}
}
Ok(field_attrs)
// Is skip_deserializing, initialize the field to Default::default()
// unless a different default is specified by `#[serde(default="...")]`
if let Some(Spanned { span, .. }) = skip_deserializing.0.value {
default.set_if_none(span, FieldDefault::Default);
}
Field {
name: Name {
serialize: ser_name.get().unwrap_or(ident.clone()),
deserialize: de_name.get().unwrap_or(ident),
},
skip_serializing: skip_serializing.get(),
skip_deserializing: skip_deserializing.get(),
skip_serializing_if: skip_serializing_if.get(),
default: default.get().unwrap_or(FieldDefault::None),
serialize_with: serialize_with.get(),
deserialize_with: deserialize_with.get(),
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
}
}
pub fn name(&self) -> &Name {
&self.name
}
pub fn skip_serializing_field(&self) -> bool {
self.skip_serializing_field
pub fn skip_serializing(&self) -> bool {
self.skip_serializing
}
pub fn skip_deserializing_field(&self) -> bool {
self.skip_deserializing_field
pub fn skip_deserializing(&self) -> bool {
self.skip_deserializing
}
pub fn skip_serializing_if(&self) -> Option<&ast::Path> {
@@ -390,42 +448,29 @@ impl FieldAttrs {
}
}
/// Zip together fields and `#[serde(...)]` attributes on those fields.
pub fn fields_with_attrs(
cx: &ExtCtxt,
fields: &[ast::StructField],
) -> Result<Vec<(ast::StructField, FieldAttrs)>, Error> {
fields.iter()
.enumerate()
.map(|(i, field)| {
let attrs = try!(FieldAttrs::from_field(cx, i, field));
Ok((field.clone(), attrs))
})
.collect()
}
fn get_ser_and_de<T, F>(
cx: &ExtCtxt,
attribute: &str,
attribute: &'static str,
items: &[P<ast::MetaItem>],
f: F
) -> Result<(Option<T>, Option<T>), Error>
where F: Fn(&ExtCtxt, &str, &ast::Lit) -> Result<T, Error>,
) -> Result<(Option<Spanned<T>>, Option<Spanned<T>>), ()>
where F: Fn(&ExtCtxt, &str, &ast::Lit) -> Result<T, ()>,
{
let mut ser_item = None;
let mut de_item = None;
let mut ser_item = Attr::none(cx, attribute);
let mut de_item = Attr::none(cx, attribute);
for item in items {
match item.node {
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize" => {
let s = try!(f(cx, name, lit));
ser_item = Some(s);
if let Ok(v) = f(cx, name, lit) {
ser_item.set(item.span, v);
}
}
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => {
let s = try!(f(cx, name, lit));
de_item = Some(s);
if let Ok(v) = f(cx, name, lit) {
de_item.set(item.span, v);
}
}
_ => {
@@ -435,25 +480,25 @@ fn get_ser_and_de<T, F>(
attribute,
meta_item_to_string(item)));
return Err(Error);
return Err(());
}
}
}
Ok((ser_item, de_item))
Ok((ser_item.get_spanned(), de_item.get_spanned()))
}
fn get_renames(
cx: &ExtCtxt,
items: &[P<ast::MetaItem>],
) -> Result<(Option<InternedString>, Option<InternedString>), Error> {
) -> Result<(Option<Spanned<InternedString>>, Option<Spanned<InternedString>>), ()> {
get_ser_and_de(cx, "rename", items, get_str_from_lit)
}
fn get_where_predicates(
cx: &ExtCtxt,
items: &[P<ast::MetaItem>],
) -> Result<(Option<Vec<ast::WherePredicate>>, Option<Vec<ast::WherePredicate>>), Error> {
) -> Result<(Option<Spanned<Vec<ast::WherePredicate>>>, Option<Spanned<Vec<ast::WherePredicate>>>), ()> {
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
}
@@ -514,7 +559,7 @@ impl<'a, 'b> Folder for Respanner<'a, 'b> {
}
}
fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<InternedString, Error> {
fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<InternedString, ()> {
match lit.node {
ast::LitKind::Str(ref s, _) => Ok(s.clone()),
_ => {
@@ -524,7 +569,7 @@ fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<Interned
name,
lit_to_string(lit)));
return Err(Error);
return Err(());
}
}
}
@@ -535,7 +580,7 @@ fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<Interned
// into a token tree. Then we'll update those spans to say they're coming from a
// macro context that originally came from the attribnute, and then finally
// parse them into an expression or where-clause.
fn parse_string_via_tts<T, F>(cx: &ExtCtxt, name: &str, string: String, action: F) -> Result<T, Error>
fn parse_string_via_tts<T, F>(cx: &ExtCtxt, name: &str, string: String, action: F) -> Result<T, ()>
where F: for<'a> Fn(&'a mut Parser) -> parse::PResult<'a, T>,
{
let tts = panictry!(parse::parse_tts_from_source_str(
@@ -553,7 +598,7 @@ fn parse_string_via_tts<T, F>(cx: &ExtCtxt, name: &str, string: String, action:
Ok(path) => path,
Err(mut e) => {
e.emit();
return Err(Error);
return Err(());
}
};
@@ -562,14 +607,14 @@ fn parse_string_via_tts<T, F>(cx: &ExtCtxt, name: &str, string: String, action:
Ok(()) => { }
Err(mut e) => {
e.emit();
return Err(Error);
return Err(());
}
}
Ok(path)
}
fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, Error> {
fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, ()> {
let string = try!(get_str_from_lit(cx, name, lit)).to_string();
parse_string_via_tts(cx, name, string, |parser| {
@@ -577,7 +622,7 @@ fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::
})
}
fn parse_lit_into_where(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<Vec<ast::WherePredicate>, Error> {
fn parse_lit_into_where(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<Vec<ast::WherePredicate>, ()> {
let string = try!(get_str_from_lit(cx, name, lit));
if string.is_empty() {
return Ok(Vec::new());
+19
View File
@@ -0,0 +1,19 @@
use std::error;
use std::fmt;
#[derive(Debug)]
pub enum Error {
UnexpectedItemKind,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "expected a struct or enum")
}
}
impl error::Error for Error {
fn description(&self) -> &str {
"expected a struct or enum"
}
}
+156
View File
@@ -0,0 +1,156 @@
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#[cfg(feature = "with-syntex")]
#[macro_use]
extern crate syntex_syntax as syntax;
#[cfg(not(feature = "with-syntex"))]
#[macro_use]
extern crate syntax;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base::ExtCtxt;
use syntax::ptr::P;
pub mod attr;
mod error;
pub use error::Error;
pub struct Item<'a> {
pub ident: ast::Ident,
pub span: codemap::Span,
pub attrs: attr::Item,
pub body: Body<'a>,
pub generics: &'a ast::Generics,
}
pub enum Body<'a> {
Enum(Vec<Variant<'a>>),
Struct(Style, Vec<Field<'a>>),
}
pub struct Variant<'a> {
pub ident: ast::Ident,
pub span: codemap::Span,
pub attrs: attr::Variant,
pub style: Style,
pub fields: Vec<Field<'a>>,
}
pub struct Field<'a> {
pub ident: Option<ast::Ident>,
pub span: codemap::Span,
pub attrs: attr::Field,
pub ty: &'a P<ast::Ty>,
}
pub enum Style {
Struct,
Tuple,
Newtype,
Unit,
}
impl<'a> Item<'a> {
pub fn from_ast(
cx: &ExtCtxt,
item: &'a ast::Item,
) -> Result<Item<'a>, Error> {
let attrs = attr::Item::from_ast(cx, item);
let (body, generics) = match item.node {
ast::ItemKind::Enum(ref enum_def, ref generics) => {
let variants = enum_from_ast(cx, enum_def);
(Body::Enum(variants), generics)
}
ast::ItemKind::Struct(ref variant_data, ref generics) => {
let (style, fields) = struct_from_ast(cx, variant_data);
(Body::Struct(style, fields), generics)
}
_ => {
return Err(Error::UnexpectedItemKind);
}
};
Ok(Item {
ident: item.ident,
span: item.span,
attrs: attrs,
body: body,
generics: generics,
})
}
}
impl<'a> Body<'a> {
pub fn all_fields(&'a self) -> Box<Iterator<Item=&'a Field<'a>> + 'a> {
match *self {
Body::Enum(ref variants) => {
Box::new(variants.iter()
.flat_map(|variant| variant.fields.iter()))
}
Body::Struct(_, ref fields) => {
Box::new(fields.iter())
}
}
}
}
fn enum_from_ast<'a>(
cx: &ExtCtxt,
enum_def: &'a ast::EnumDef,
) -> Vec<Variant<'a>> {
enum_def.variants.iter()
.map(|variant| {
let (style, fields) = struct_from_ast(cx, &variant.node.data);
Variant {
ident: variant.node.name,
span: variant.span,
attrs: attr::Variant::from_ast(cx, variant),
style: style,
fields: fields,
}
})
.collect()
}
fn struct_from_ast<'a>(
cx: &ExtCtxt,
variant_data: &'a ast::VariantData,
) -> (Style, Vec<Field<'a>>) {
match *variant_data {
ast::VariantData::Struct(ref fields, _) => {
(Style::Struct, fields_from_ast(cx, fields))
}
ast::VariantData::Tuple(ref fields, _) if fields.len() == 1 => {
(Style::Newtype, fields_from_ast(cx, fields))
}
ast::VariantData::Tuple(ref fields, _) => {
(Style::Tuple, fields_from_ast(cx, fields))
}
ast::VariantData::Unit(_) => {
(Style::Unit, Vec::new())
}
}
}
fn fields_from_ast<'a>(
cx: &ExtCtxt,
fields: &'a [ast::StructField],
) -> Vec<Field<'a>> {
fields.iter()
.enumerate()
.map(|(i, field)| {
Field {
ident: field.ident,
span: field.span,
attrs: attr::Field::from_ast(cx, i, field),
ty: &field.ty,
}
})
.collect()
}
+4 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_macros"
version = "0.7.10"
version = "0.7.11"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
@@ -18,13 +18,13 @@ nightly-testing = ["clippy", "serde/nightly-testing", "serde_codegen/nightly-tes
[dependencies]
clippy = { version = "^0.*", optional = true }
serde_codegen = { version = "^0.7.10", path = "../serde_codegen", default-features = false, features = ["nightly"] }
serde_codegen = { version = "^0.7.11", path = "../serde_codegen", default-features = false, features = ["nightly"] }
[dev-dependencies]
compiletest_rs = "^0.1.1"
compiletest_rs = "^0.2.0"
fnv = "1.0"
rustc-serialize = "^0.3.16"
serde = { version = "^0.7.10", path = "../serde" }
serde = { version = "^0.7.11", path = "../serde" }
[[test]]
name = "test"
@@ -0,0 +1,32 @@
#![feature(custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]
#[derive(Serialize)]
struct S {
#[serde(rename(serialize="x"))]
#[serde(rename(serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
a: (),
#[serde(rename(serialize="x"))]
#[serde(rename="y")] //~ ERROR: duplicate serde attribute `rename`
b: (),
#[serde(rename(serialize="x"))]
#[serde(rename(deserialize="y"))] // ok
c: (),
#[serde(rename="x")]
#[serde(rename(deserialize="y"))] //~ ERROR: duplicate serde attribute `rename`
d: (),
#[serde(rename(serialize="x", serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
e: (),
#[serde(rename="x", serialize="y")] //~ ERROR: unknown serde field attribute `serialize = "y"`
f: (),
#[serde(rename(serialize="x"), rename(serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
g: (),
}
fn main() {}
@@ -0,0 +1,9 @@
#![feature(custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]
#[derive(Serialize, Deserialize)]
struct Test<'a> {
s: &'a str, //~ ERROR: Serde does not support deserializing fields of type &str
}
fn main() {}
+1 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_tests"
version = "0.7.10"
version = "0.7.11"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
@@ -14,15 +14,12 @@ build = "build.rs"
nightly-testing = ["clippy", "serde/nightly-testing", "serde_codegen/nightly-testing"]
[build-dependencies]
syntex = { version = "^0.35.0" }
syntex_syntax = { version = "^0.35.0" }
serde_codegen = { version = "*", path = "../serde_codegen", features = ["with-syntex"] }
[dev-dependencies]
fnv = "1.0"
rustc-serialize = "^0.3.16"
serde = { version = "*", path = "../serde" }
syntex = "^0.35.0"
[dependencies]
clippy = { version = "^0.*", optional = true }
-1
View File
@@ -1,4 +1,3 @@
extern crate syntex;
extern crate serde_codegen;
use std::env;