mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-23 11:48:00 +00:00
Compare commits
70 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6ab508a93c | |||
| 9f38c2ab59 | |||
| 021ce5be88 | |||
| f1f8b4622b | |||
| 1fb2172a25 | |||
| 5941f1d071 | |||
| 8d6cc4dfa5 | |||
| c9e2e518ba | |||
| 51042bde50 | |||
| 5c6a0e12e9 | |||
| d4e1ef659a | |||
| f5f35677f0 | |||
| 90d9c77186 | |||
| 882d130e19 | |||
| 5f84e601b6 | |||
| 0bf6a17428 | |||
| db8881d845 | |||
| 3403352749 | |||
| ac69524258 | |||
| 28589620f6 | |||
| 8e4da7f36b | |||
| 4c4a27f53c | |||
| b838651ac9 | |||
| 5cd8212a61 | |||
| c5f606f10f | |||
| c21bea8b30 | |||
| 22a26a33f4 | |||
| 8a09f05644 | |||
| 5923a0cd2f | |||
| 1576b5a8a0 | |||
| 2c4dbf5a84 | |||
| 021f4f2d70 | |||
| decc571988 | |||
| 322d7a90db | |||
| dd3f653103 | |||
| 46a1860601 | |||
| 84a573c926 | |||
| 7dfa8f43f4 | |||
| 7375b4e847 | |||
| 48da62ed07 | |||
| 9834af7ed9 | |||
| 6b404d8529 | |||
| 3119cc8857 | |||
| bb059b97c0 | |||
| b7188f7022 | |||
| a64fe99d1b | |||
| c716c4e261 | |||
| 3d2e3beafe | |||
| 1917e54a6e | |||
| 898b346d48 | |||
| e90adb20ef | |||
| a52e7f5554 | |||
| 7afb8b52ae | |||
| cb4694387e | |||
| 58fa302007 | |||
| bf33daf124 | |||
| 4b472be56e | |||
| bdffaf3ea1 | |||
| f197c3ce96 | |||
| 01dfad6705 | |||
| 2e06786262 | |||
| 578f34ecaf | |||
| 2c8767cb46 | |||
| 45c51d3198 | |||
| bd40830905 | |||
| 4e6cd2d63f | |||
| 2256a04926 | |||
| 660ea7bd7b | |||
| 7052833512 | |||
| 5c2cf5778f |
+9
-12
@@ -1,39 +1,36 @@
|
||||
sudo: false
|
||||
language: rust
|
||||
rust:
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
- 1.5.0
|
||||
- 1.7.0
|
||||
- 1.8.0
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- 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 --skip 1.5.0 build -- --no-default-features)
|
||||
- (cd serde && travis-cargo --only nightly build -- --no-default-features)
|
||||
- (cd serde && travis-cargo 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 --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=""
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
## 0.7.6
|
||||
|
||||
NOTES:
|
||||
|
||||
* Syncs `serde_codegen` and `serde_macros` with rustc 1.10.0-nightly (7bddce693 2016-05-27).
|
||||
|
||||
FEATURES:
|
||||
|
||||
* `#[serde(serialize_with=..., deserialize_with=...)]` now supports tuples. #335
|
||||
* Serde now can be used in `#[no_std]` environments. #316
|
||||
@@ -4,7 +4,7 @@ Serde Rust Serialization Framework
|
||||
[](https://travis-ci.org/serde-rs/serde)
|
||||
[](https://coveralls.io/github/serde-rs/serde?branch=master)
|
||||
[](https://crates.io/crates/serde)
|
||||
[](http://clippy.bashy.io/github/serde-rs/serde/master/log)
|
||||
[](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;
|
||||
@@ -142,10 +140,7 @@ pub fn main() {
|
||||
let src = Path::new("src/main.rs.in");
|
||||
let dst = Path::new(&out_dir).join("main.rs");
|
||||
|
||||
let mut registry = syntex::Registry::new();
|
||||
|
||||
serde_codegen::register(&mut registry);
|
||||
registry.expand("", &src, &dst).unwrap();
|
||||
serde_codegen::expand(&src, &dst).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -178,7 +173,6 @@ nightly = ["serde_macros"]
|
||||
|
||||
[build-dependencies]
|
||||
serde_codegen = { version = "*", optional = true }
|
||||
syntex = "*"
|
||||
|
||||
[dependencies]
|
||||
serde = "*"
|
||||
@@ -191,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;
|
||||
@@ -203,10 +196,7 @@ mod inner {
|
||||
let src = Path::new("src/main.rs.in");
|
||||
let dst = Path::new(&out_dir).join("main.rs");
|
||||
|
||||
let mut registry = syntex::Registry::new();
|
||||
|
||||
serde_codegen::register(&mut registry);
|
||||
registry.expand("", &src, &dst).unwrap();
|
||||
serde_codegen::expand(&src, &dst).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -688,12 +678,15 @@ how types are serialized. Here are the supported annotations:
|
||||
|
||||
Container Annotations:
|
||||
|
||||
| Annotation | Function |
|
||||
| ---------- | -------- |
|
||||
| `#[serde(rename="name")]` | Serialize and deserialize this container with the given name |
|
||||
| `#[serde(rename(serialize="name1"))]` | Serialize this container with the given name |
|
||||
| `#[serde(rename(deserialize="name1"))]` | Deserialize this container with the given name |
|
||||
| `#[serde(deny_unknown_fields)]` | Always error during serialization when encountering unknown fields. When absent, unknown fields are ignored for self-describing formats like JSON. |
|
||||
| Annotation | Function |
|
||||
| ---------- | -------- |
|
||||
| `#[serde(rename="name")]` | Serialize and deserialize this container with the given name |
|
||||
| `#[serde(rename(serialize="name1"))]` | Serialize this container with the given name |
|
||||
| `#[serde(rename(deserialize="name1"))]` | Deserialize this container with the given name |
|
||||
| `#[serde(deny_unknown_fields)]` | Always error during serialization when encountering unknown fields. When absent, unknown fields are ignored for self-describing formats like JSON. |
|
||||
| `#[serde(bound="T: MyTrait")]` | Where-clause for the Serialize and Deserialize impls. This replaces any bounds inferred by Serde. |
|
||||
| `#[serde(bound(serialize="T: MyTrait"))]` | Where-clause for the Serialize impl. |
|
||||
| `#[serde(bound(deserialize="T: MyTrait"))]` | Where-clause for the Deserialize impl. |
|
||||
|
||||
Variant Annotations:
|
||||
|
||||
@@ -705,18 +698,21 @@ Variant Annotations:
|
||||
|
||||
Field Annotations:
|
||||
|
||||
| Annotation | Function |
|
||||
| ---------- | -------- |
|
||||
| `#[serde(rename="name")]` | Serialize and deserialize this field with the given name |
|
||||
| `#[serde(rename(serialize="name1"))]` | Serialize this field with the given name |
|
||||
| `#[serde(rename(deserialize="name1"))]` | Deserialize this field with the given name |
|
||||
| `#[serde(default)]` | If the value is not specified, use the `Default::default()` |
|
||||
| `#[serde(default="$path")]` | Call the path to a function `fn() -> T` to build the value |
|
||||
| `#[serde(skip_serializing)]` | Do not serialize this value |
|
||||
| `#[serde(skip_deserializing)]` | Always use `Default::default()` or `#[serde(default="$path")]` instead of deserializing this value |
|
||||
| `#[serde(skip_serializing_if="$path")]` | Do not serialize this value if this function `fn(&T) -> bool` returns `true` |
|
||||
| `#[serde(serialize_with="$path")]` | Call a function `fn<S>(&T, &mut S) -> Result<(), S::Error> where S: Serializer` to serialize this value of type `T` |
|
||||
| `#[serde(deserialize_with="$path")]` | Call a function `fn<D>(&mut D) -> Result<T, D::Error> where D: Deserializer` to deserialize this value of type `T` |
|
||||
| Annotation | Function |
|
||||
| ---------- | -------- |
|
||||
| `#[serde(rename="name")]` | Serialize and deserialize this field with the given name |
|
||||
| `#[serde(rename(serialize="name1"))]` | Serialize this field with the given name |
|
||||
| `#[serde(rename(deserialize="name1"))]` | Deserialize this field with the given name |
|
||||
| `#[serde(default)]` | If the value is not specified, use the `Default::default()` |
|
||||
| `#[serde(default="$path")]` | Call the path to a function `fn() -> T` to build the value |
|
||||
| `#[serde(skip_serializing)]` | Do not serialize this value |
|
||||
| `#[serde(skip_deserializing)]` | Always use `Default::default()` or `#[serde(default="$path")]` instead of deserializing this value |
|
||||
| `#[serde(skip_serializing_if="$path")]` | Do not serialize this value if this function `fn(&T) -> bool` returns `true` |
|
||||
| `#[serde(serialize_with="$path")]` | Call a function `fn<S>(&T, &mut S) -> Result<(), S::Error> where S: Serializer` to serialize this value of type `T` |
|
||||
| `#[serde(deserialize_with="$path")]` | Call a function `fn<D>(&mut D) -> Result<T, D::Error> where D: Deserializer` to deserialize this value of type `T` |
|
||||
| `#[serde(bound="T: MyTrait")]` | Where-clause for the Serialize and Deserialize impls. This replaces any bounds inferred by Serde for the current field. |
|
||||
| `#[serde(bound(serialize="T: MyTrait"))]` | Where-clause for the Serialize impl. |
|
||||
| `#[serde(bound(deserialize="T: MyTrait"))]` | Where-clause for the Deserialize impl. |
|
||||
|
||||
Using in `no_std` crates
|
||||
========================
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
paths = [
|
||||
"../serde",
|
||||
"../serde_codegen",
|
||||
"../serde_macros",
|
||||
]
|
||||
@@ -9,10 +9,9 @@ default = ["serde_codegen"]
|
||||
nightly = ["serde_macros"]
|
||||
|
||||
[build-dependencies]
|
||||
serde_codegen = { version = "^0.7.5", optional = true }
|
||||
syntex = "^0.32.0"
|
||||
serde_codegen = { version = "^0.7.11", optional = true }
|
||||
|
||||
[dependencies]
|
||||
serde = "^0.7.5"
|
||||
serde = "^0.7.11"
|
||||
serde_json = "^0.7.0"
|
||||
serde_macros = { version = "^0.7.5", optional = true }
|
||||
serde_macros = { version = "^0.7.11", optional = true }
|
||||
|
||||
@@ -2,12 +2,12 @@ This example demonstrates how to use Serde with Syntex. On stable or nightly
|
||||
with Syntex, it can be built with:
|
||||
|
||||
```
|
||||
% multirust run stable cargo run
|
||||
% rustup run stable cargo run
|
||||
Running `target/debug/serde-syntex-example`
|
||||
{"x":1,"y":2}
|
||||
Point { x: 1, y: 2 }
|
||||
|
||||
% multirust run nightly cargo run
|
||||
% rustup run nightly cargo run
|
||||
Running `target/debug/serde-syntex-example`
|
||||
{"x":1,"y":2}
|
||||
Point { x: 1, y: 2 }
|
||||
@@ -16,5 +16,5 @@ Point { x: 1, y: 2 }
|
||||
On nightly, it can use a plugin with:
|
||||
|
||||
```
|
||||
% multirust run nightly cargo run --features nightly --no-default-features
|
||||
% rustup run nightly cargo run --features nightly --no-default-features
|
||||
```
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#[cfg(not(feature = "serde_macros"))]
|
||||
mod inner {
|
||||
extern crate syntex;
|
||||
extern crate serde_codegen;
|
||||
|
||||
use std::env;
|
||||
@@ -12,10 +11,7 @@ mod inner {
|
||||
let src = Path::new("src/main.rs.in");
|
||||
let dst = Path::new(&out_dir).join("main.rs");
|
||||
|
||||
let mut registry = syntex::Registry::new();
|
||||
|
||||
serde_codegen::register(&mut registry);
|
||||
registry.expand("", &src, &dst).unwrap();
|
||||
serde_codegen::expand(&src, &dst).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#![cfg_attr(nightly, feature(custom_derive, plugin))]
|
||||
#![cfg_attr(nightly, plugin(serde_macros))]
|
||||
#![cfg_attr(feature = "serde_macros", feature(custom_derive, plugin))]
|
||||
#![cfg_attr(feature = "serde_macros", plugin(serde_macros))]
|
||||
|
||||
extern crate serde;
|
||||
extern crate serde_json;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "0.7.7"
|
||||
version = "0.7.11"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
|
||||
+50
-55
@@ -32,7 +32,7 @@ use collections::enum_set::{CLike, EnumSet};
|
||||
#[cfg(all(feature = "nightly", feature = "collections"))]
|
||||
use collections::borrow::ToOwned;
|
||||
|
||||
use core::hash::Hash;
|
||||
use core::hash::{Hash, BuildHasher};
|
||||
use core::marker::PhantomData;
|
||||
#[cfg(feature = "std")]
|
||||
use std::net;
|
||||
@@ -381,29 +381,30 @@ impl<T> Deserialize for PhantomData<T> where T: Deserialize {
|
||||
macro_rules! seq_impl {
|
||||
(
|
||||
$ty:ty,
|
||||
< $($constraints:ident),* >,
|
||||
$visitor_name:ident,
|
||||
$visitor_ty:ident < $($typaram:ident : $bound1:ident $(+ $bound2:ident)*),* >,
|
||||
$visitor:ident,
|
||||
$ctor:expr,
|
||||
$with_capacity:expr,
|
||||
$insert:expr
|
||||
) => {
|
||||
/// A visitor that produces a sequence.
|
||||
pub struct $visitor_name<T> {
|
||||
marker: PhantomData<T>,
|
||||
pub struct $visitor_ty<$($typaram),*> {
|
||||
marker: PhantomData<$ty>,
|
||||
}
|
||||
|
||||
impl<T> $visitor_name<T> {
|
||||
impl<$($typaram),*> $visitor_ty<$($typaram),*>
|
||||
where $($typaram: $bound1 $(+ $bound2)*),*
|
||||
{
|
||||
/// Construct a new sequence visitor.
|
||||
pub fn new() -> Self {
|
||||
$visitor_name {
|
||||
$visitor_ty {
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Visitor for $visitor_name<T>
|
||||
where T: $($constraints +)*,
|
||||
impl<$($typaram),*> Visitor for $visitor_ty<$($typaram),*>
|
||||
where $($typaram: $bound1 $(+ $bound2)*),*
|
||||
{
|
||||
type Value = $ty;
|
||||
|
||||
@@ -430,13 +431,13 @@ macro_rules! seq_impl {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deserialize for $ty
|
||||
where T: $($constraints +)*,
|
||||
impl<$($typaram),*> Deserialize for $ty
|
||||
where $($typaram: $bound1 $(+ $bound2)*),*
|
||||
{
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.deserialize_seq($visitor_name::new())
|
||||
deserializer.deserialize_seq($visitor_ty::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -445,8 +446,7 @@ macro_rules! seq_impl {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
seq_impl!(
|
||||
BinaryHeap<T>,
|
||||
<Deserialize, Ord>,
|
||||
BinaryHeapVisitor,
|
||||
BinaryHeapVisitor<T: Deserialize + Ord>,
|
||||
visitor,
|
||||
BinaryHeap::new(),
|
||||
BinaryHeap::with_capacity(visitor.size_hint().0),
|
||||
@@ -455,8 +455,7 @@ seq_impl!(
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
seq_impl!(
|
||||
BTreeSet<T>,
|
||||
<Deserialize, Eq, Ord>,
|
||||
BTreeSetVisitor,
|
||||
BTreeSetVisitor<T: Deserialize + Eq + Ord>,
|
||||
visitor,
|
||||
BTreeSet::new(),
|
||||
BTreeSet::new(),
|
||||
@@ -465,8 +464,7 @@ seq_impl!(
|
||||
#[cfg(all(feature = "nightly", feature = "collections"))]
|
||||
seq_impl!(
|
||||
EnumSet<T>,
|
||||
<Deserialize, CLike>,
|
||||
EnumSetVisitor,
|
||||
EnumSetVisitor<T: Deserialize + CLike>,
|
||||
visitor,
|
||||
EnumSet::new(),
|
||||
EnumSet::new(),
|
||||
@@ -475,8 +473,7 @@ seq_impl!(
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
seq_impl!(
|
||||
LinkedList<T>,
|
||||
<Deserialize>,
|
||||
LinkedListVisitor,
|
||||
LinkedListVisitor<T: Deserialize>,
|
||||
visitor,
|
||||
LinkedList::new(),
|
||||
LinkedList::new(),
|
||||
@@ -484,19 +481,18 @@ seq_impl!(
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
seq_impl!(
|
||||
HashSet<T>,
|
||||
<Deserialize, Eq, Hash>,
|
||||
HashSetVisitor,
|
||||
HashSet<T, S>,
|
||||
HashSetVisitor<T: Deserialize + Eq + Hash,
|
||||
S: BuildHasher + Default>,
|
||||
visitor,
|
||||
HashSet::new(),
|
||||
HashSet::with_capacity(visitor.size_hint().0),
|
||||
HashSet::with_hasher(S::default()),
|
||||
HashSet::with_capacity_and_hasher(visitor.size_hint().0, S::default()),
|
||||
HashSet::insert);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
seq_impl!(
|
||||
Vec<T>,
|
||||
<Deserialize>,
|
||||
VecVisitor,
|
||||
VecVisitor<T: Deserialize>,
|
||||
visitor,
|
||||
Vec::new(),
|
||||
Vec::with_capacity(visitor.size_hint().0),
|
||||
@@ -505,8 +501,7 @@ seq_impl!(
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
seq_impl!(
|
||||
VecDeque<T>,
|
||||
<Deserialize>,
|
||||
VecDequeVisitor,
|
||||
VecDequeVisitor<T: Deserialize>,
|
||||
visitor,
|
||||
VecDeque::new(),
|
||||
VecDeque::with_capacity(visitor.size_hint().0),
|
||||
@@ -651,7 +646,6 @@ array_impls! {
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
() => {};
|
||||
($($len:expr => $visitor:ident => ($($name:ident),+),)+) => {
|
||||
$(
|
||||
/// Construct a tuple visitor.
|
||||
@@ -719,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),
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@@ -726,30 +724,29 @@ tuple_impls! {
|
||||
macro_rules! map_impl {
|
||||
(
|
||||
$ty:ty,
|
||||
< $($constraints:ident),* >,
|
||||
$visitor_name:ident,
|
||||
$visitor_ty:ident < $($typaram:ident : $bound1:ident $(+ $bound2:ident)*),* >,
|
||||
$visitor:ident,
|
||||
$ctor:expr,
|
||||
$with_capacity:expr,
|
||||
$insert:expr
|
||||
$with_capacity:expr
|
||||
) => {
|
||||
/// A visitor that produces a map.
|
||||
pub struct $visitor_name<K, V> {
|
||||
pub struct $visitor_ty<$($typaram),*> {
|
||||
marker: PhantomData<$ty>,
|
||||
}
|
||||
|
||||
impl<K, V> $visitor_name<K, V> {
|
||||
impl<$($typaram),*> $visitor_ty<$($typaram),*>
|
||||
where $($typaram: $bound1 $(+ $bound2)*),*
|
||||
{
|
||||
/// Construct a `MapVisitor*<T>`.
|
||||
pub fn new() -> Self {
|
||||
$visitor_name {
|
||||
$visitor_ty {
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> Visitor for $visitor_name<K, V>
|
||||
where K: $($constraints +)*,
|
||||
V: Deserialize,
|
||||
impl<$($typaram),*> Visitor for $visitor_ty<$($typaram),*>
|
||||
where $($typaram: $bound1 $(+ $bound2)*),*
|
||||
{
|
||||
type Value = $ty;
|
||||
|
||||
@@ -767,7 +764,7 @@ macro_rules! map_impl {
|
||||
let mut values = $with_capacity;
|
||||
|
||||
while let Some((key, value)) = try!($visitor.visit()) {
|
||||
$insert(&mut values, key, value);
|
||||
values.insert(key, value);
|
||||
}
|
||||
|
||||
try!($visitor.end());
|
||||
@@ -776,14 +773,13 @@ macro_rules! map_impl {
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> Deserialize for $ty
|
||||
where K: $($constraints +)*,
|
||||
V: Deserialize,
|
||||
impl<$($typaram),*> Deserialize for $ty
|
||||
where $($typaram: $bound1 $(+ $bound2)*),*
|
||||
{
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.deserialize_map($visitor_name::new())
|
||||
deserializer.deserialize_map($visitor_ty::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -792,22 +788,21 @@ macro_rules! map_impl {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
map_impl!(
|
||||
BTreeMap<K, V>,
|
||||
<Deserialize, Eq, Ord>,
|
||||
BTreeMapVisitor,
|
||||
BTreeMapVisitor<K: Deserialize + Eq + Ord,
|
||||
V: Deserialize>,
|
||||
visitor,
|
||||
BTreeMap::new(),
|
||||
BTreeMap::new(),
|
||||
BTreeMap::insert);
|
||||
BTreeMap::new());
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
map_impl!(
|
||||
HashMap<K, V>,
|
||||
<Deserialize, Eq, Hash>,
|
||||
HashMapVisitor,
|
||||
HashMap<K, V, S>,
|
||||
HashMapVisitor<K: Deserialize + Eq + Hash,
|
||||
V: Deserialize,
|
||||
S: BuildHasher + Default>,
|
||||
visitor,
|
||||
HashMap::new(),
|
||||
HashMap::with_capacity(visitor.size_hint().0),
|
||||
HashMap::insert);
|
||||
HashMap::with_hasher(S::default()),
|
||||
HashMap::with_capacity_and_hasher(visitor.size_hint().0, S::default()));
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
+1
-1
@@ -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,
|
||||
{
|
||||
|
||||
+71
-3
@@ -31,7 +31,7 @@ use collections::enum_set::{CLike, EnumSet};
|
||||
#[cfg(all(feature = "nightly", feature = "collections"))]
|
||||
use collections::borrow::ToOwned;
|
||||
|
||||
use core::hash::Hash;
|
||||
use core::hash::{Hash, BuildHasher};
|
||||
#[cfg(feature = "nightly")]
|
||||
use core::iter;
|
||||
#[cfg(feature = "std")]
|
||||
@@ -330,8 +330,9 @@ impl<T> Serialize for EnumSet<T>
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T> Serialize for HashSet<T>
|
||||
impl<T, H> Serialize for HashSet<T, H>
|
||||
where T: Serialize + Eq + Hash,
|
||||
H: BuildHasher,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
|
||||
@@ -567,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,
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@@ -651,9 +718,10 @@ impl<K, V> Serialize for BTreeMap<K, V>
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<K, V> Serialize for HashMap<K, V>
|
||||
impl<K, V, H> Serialize for HashMap<K, V, H>
|
||||
where K: Serialize + Eq + Hash,
|
||||
V: Serialize,
|
||||
H: BuildHasher,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
|
||||
|
||||
+18
-10
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_codegen"
|
||||
version = "0.7.7"
|
||||
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"
|
||||
@@ -8,22 +8,30 @@ repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://github.com/serde-rs/serde"
|
||||
keywords = ["serde", "serialization"]
|
||||
build = "build.rs"
|
||||
include = ["Cargo.toml", "build.rs", "src/**/*.rs"]
|
||||
include = ["Cargo.toml", "build.rs", "src/**/*.rs", "src/lib.rs.in"]
|
||||
|
||||
[features]
|
||||
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.11.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.17.0", default-features = false }
|
||||
aster = { version = "^0.19.0", default-features = false }
|
||||
clippy = { version = "^0.*", optional = true }
|
||||
quasi = { version = "^0.11.0", default-features = false }
|
||||
quasi_macros = { version = "^0.11.0", optional = true }
|
||||
syntex = { version = "^0.33.0", optional = true }
|
||||
syntex_syntax = { version = "^0.33.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,6 +1,5 @@
|
||||
#[cfg(feature = "with-syntex")]
|
||||
mod inner {
|
||||
extern crate syntex;
|
||||
extern crate quasi_codegen;
|
||||
|
||||
use std::env;
|
||||
@@ -8,13 +7,11 @@ mod inner {
|
||||
|
||||
pub fn main() {
|
||||
let out_dir = env::var_os("OUT_DIR").unwrap();
|
||||
let mut registry = syntex::Registry::new();
|
||||
quasi_codegen::register(&mut registry);
|
||||
|
||||
let src = Path::new("src/lib.rs.in");
|
||||
let dst = Path::new(&out_dir).join("lib.rs");
|
||||
|
||||
registry.expand("", &src, &dst).unwrap();
|
||||
quasi_codegen::expand(&src, &dst).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,485 +0,0 @@
|
||||
use std::rc::Rc;
|
||||
use syntax::ast::{self, TokenTree};
|
||||
use syntax::attr;
|
||||
use syntax::codemap::Span;
|
||||
use syntax::ext::base::ExtCtxt;
|
||||
use syntax::fold::Folder;
|
||||
use syntax::parse::parser::PathStyle;
|
||||
use syntax::parse::token::{self, InternedString};
|
||||
use syntax::parse;
|
||||
use syntax::print::pprust::{lit_to_string, meta_item_to_string};
|
||||
use syntax::ptr::P;
|
||||
|
||||
use aster::AstBuilder;
|
||||
|
||||
use error::Error;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Name {
|
||||
ident: ast::Ident,
|
||||
serialize_name: Option<InternedString>,
|
||||
deserialize_name: Option<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())
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents container (e.g. struct) attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct ContainerAttrs {
|
||||
name: Name,
|
||||
deny_unknown_fields: bool,
|
||||
}
|
||||
|
||||
impl ContainerAttrs {
|
||||
/// 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,
|
||||
};
|
||||
|
||||
for meta_items in item.attrs().iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
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);
|
||||
}
|
||||
|
||||
// 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));
|
||||
|
||||
container_attrs.name.serialize_name = ser_name;
|
||||
container_attrs.name.deserialize_name = de_name;
|
||||
}
|
||||
|
||||
// Parse `#[serde(deny_unknown_fields)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"deny_unknown_fields" => {
|
||||
container_attrs.deny_unknown_fields = true;
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde container attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
|
||||
return Err(Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(container_attrs)
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn deny_unknown_fields(&self) -> bool {
|
||||
self.deny_unknown_fields
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents variant attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct VariantAttrs {
|
||||
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),
|
||||
};
|
||||
|
||||
for meta_items in variant.node.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
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);
|
||||
}
|
||||
|
||||
// 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));
|
||||
|
||||
variant_attrs.name.serialize_name = ser_name;
|
||||
variant_attrs.name.deserialize_name = de_name;
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde variant attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
|
||||
return Err(Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(variant_attrs)
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents field attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct FieldAttrs {
|
||||
name: Name,
|
||||
skip_serializing_field: bool,
|
||||
skip_deserializing_field: bool,
|
||||
skip_serializing_if: Option<ast::Path>,
|
||||
default_expr_if_missing: Option<P<ast::Expr>>,
|
||||
serialize_with: Option<ast::Path>,
|
||||
deserialize_with: Option<ast::Path>,
|
||||
}
|
||||
|
||||
impl FieldAttrs {
|
||||
/// 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();
|
||||
|
||||
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_expr_if_missing: None,
|
||||
serialize_with: None,
|
||||
deserialize_with: None,
|
||||
};
|
||||
|
||||
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
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);
|
||||
}
|
||||
|
||||
// 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));
|
||||
|
||||
field_attrs.name.serialize_name = ser_name;
|
||||
field_attrs.name.deserialize_name = de_name;
|
||||
}
|
||||
|
||||
// Parse `#[serde(default)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"default" => {
|
||||
let default_expr = builder.expr().default();
|
||||
field_attrs.default_expr_if_missing = Some(default_expr);
|
||||
}
|
||||
|
||||
// Parse `#[serde(default="...")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"default" => {
|
||||
let wrapped_expr = wrap_default(
|
||||
try!(parse_lit_into_path(cx, name, lit)),
|
||||
);
|
||||
|
||||
field_attrs.default_expr_if_missing = Some(wrapped_expr);
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_serializing)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"skip_serializing" => {
|
||||
field_attrs.skip_serializing_field = true;
|
||||
}
|
||||
|
||||
// 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_expr_if_missing.is_none() {
|
||||
let default_expr = builder.expr().default();
|
||||
field_attrs.default_expr_if_missing = Some(default_expr);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde field attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
|
||||
return Err(Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(field_attrs)
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn skip_serializing_field(&self) -> bool {
|
||||
self.skip_serializing_field
|
||||
}
|
||||
|
||||
pub fn skip_deserializing_field(&self) -> bool {
|
||||
self.skip_deserializing_field
|
||||
}
|
||||
|
||||
pub fn skip_serializing_if(&self) -> Option<&ast::Path> {
|
||||
self.skip_serializing_if.as_ref()
|
||||
}
|
||||
|
||||
pub fn default_expr_if_missing(&self) -> Option<&P<ast::Expr>> {
|
||||
self.default_expr_if_missing.as_ref()
|
||||
}
|
||||
|
||||
pub fn serialize_with(&self) -> Option<&ast::Path> {
|
||||
self.serialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn deserialize_with(&self) -> Option<&ast::Path> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Zip together fields and `#[serde(...)]` attributes on those fields.
|
||||
pub fn fields_with_attrs<'a>(
|
||||
cx: &ExtCtxt,
|
||||
fields: &'a [ast::StructField],
|
||||
) -> Result<Vec<(&'a ast::StructField, FieldAttrs)>, Error> {
|
||||
fields.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
let attrs = try!(FieldAttrs::from_field(cx, i, field));
|
||||
Ok((field, attrs))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn get_renames(cx: &ExtCtxt,
|
||||
items: &[P<ast::MetaItem>],
|
||||
)-> Result<(Option<InternedString>, Option<InternedString>), Error> {
|
||||
let mut ser_name = None;
|
||||
let mut de_name = None;
|
||||
|
||||
for item in items {
|
||||
match item.node {
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize" => {
|
||||
let s = try!(get_str_from_lit(cx, name, lit));
|
||||
ser_name = Some(s);
|
||||
}
|
||||
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => {
|
||||
let s = try!(get_str_from_lit(cx, name, lit));
|
||||
de_name = Some(s);
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
item.span,
|
||||
&format!("unknown rename attribute `{}`",
|
||||
meta_item_to_string(item)));
|
||||
|
||||
return Err(Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((ser_name, de_name))
|
||||
}
|
||||
|
||||
pub fn get_serde_meta_items(attr: &ast::Attribute) -> Option<&[P<ast::MetaItem>]> {
|
||||
match attr.node.value.node {
|
||||
ast::MetaItemKind::List(ref name, ref items) if name == &"serde" => {
|
||||
attr::mark_used(&attr);
|
||||
Some(items)
|
||||
}
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
/// This syntax folder rewrites tokens to say their spans are coming from a macro context.
|
||||
struct Respanner<'a, 'b: 'a> {
|
||||
cx: &'a ExtCtxt<'b>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> Folder for Respanner<'a, 'b> {
|
||||
fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree {
|
||||
match *tt {
|
||||
TokenTree::Token(span, ref tok) => {
|
||||
TokenTree::Token(
|
||||
self.new_span(span),
|
||||
self.fold_token(tok.clone())
|
||||
)
|
||||
}
|
||||
TokenTree::Delimited(span, ref delimed) => {
|
||||
TokenTree::Delimited(
|
||||
self.new_span(span),
|
||||
Rc::new(ast::Delimited {
|
||||
delim: delimed.delim,
|
||||
open_span: delimed.open_span,
|
||||
tts: self.fold_tts(&delimed.tts),
|
||||
close_span: delimed.close_span,
|
||||
})
|
||||
)
|
||||
}
|
||||
TokenTree::Sequence(span, ref seq) => {
|
||||
TokenTree::Sequence(
|
||||
self.new_span(span),
|
||||
Rc::new(ast::SequenceRepetition {
|
||||
tts: self.fold_tts(&seq.tts),
|
||||
separator: seq.separator.clone().map(|tok| self.fold_token(tok)),
|
||||
..**seq
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn new_span(&mut self, span: Span) -> Span {
|
||||
Span {
|
||||
lo: span.lo,
|
||||
hi: span.hi,
|
||||
expn_id: self.cx.backtrace(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<InternedString, Error> {
|
||||
match lit.node {
|
||||
ast::LitKind::Str(ref s, _) => Ok(s.clone()),
|
||||
_ => {
|
||||
cx.span_err(
|
||||
lit.span,
|
||||
&format!("serde annotation `{}` must be a string, not `{}`",
|
||||
name,
|
||||
lit_to_string(lit)));
|
||||
|
||||
return Err(Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, Error> {
|
||||
let source = try!(get_str_from_lit(cx, name, lit));
|
||||
|
||||
// If we just parse the string into an expression, any syntax errors in the source will only
|
||||
// have spans that point inside the string, and not back to the attribute. So to have better
|
||||
// error reporting, we'll first parse the string into a token tree. Then we'll update those
|
||||
// spans to say they're coming from a macro context that originally came from the attribute,
|
||||
// and then finally parse them into an expression.
|
||||
let tts = panictry!(parse::parse_tts_from_source_str(
|
||||
format!("<serde {} expansion>", name),
|
||||
(*source).to_owned(),
|
||||
cx.cfg(),
|
||||
cx.parse_sess()));
|
||||
|
||||
// Respan the spans to say they are all coming from this macro.
|
||||
let tts = Respanner { cx: cx }.fold_tts(&tts);
|
||||
|
||||
let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts);
|
||||
|
||||
let path = match parser.parse_path(PathStyle::Type) {
|
||||
Ok(path) => path,
|
||||
Err(mut e) => {
|
||||
e.emit();
|
||||
return Err(Error);
|
||||
}
|
||||
};
|
||||
|
||||
// Make sure to error out if there are trailing characters in the stream.
|
||||
match parser.expect(&token::Eof) {
|
||||
Ok(()) => { }
|
||||
Err(mut e) => {
|
||||
e.emit();
|
||||
return Err(Error);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// This function wraps the expression in `#[serde(default="...")]` in a function to prevent it
|
||||
/// from accessing the internal `Deserialize` state.
|
||||
fn wrap_default(path: ast::Path) -> P<ast::Expr> {
|
||||
AstBuilder::new().expr().call()
|
||||
.build_path(path)
|
||||
.build()
|
||||
}
|
||||
+81
-37
@@ -3,10 +3,11 @@ use std::collections::HashSet;
|
||||
use aster::AstBuilder;
|
||||
|
||||
use syntax::ast;
|
||||
use syntax::ext::base::ExtCtxt;
|
||||
use syntax::ptr::P;
|
||||
use syntax::visit;
|
||||
|
||||
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
|
||||
// allowed here".
|
||||
@@ -21,22 +22,49 @@ pub fn without_defaults(generics: &ast::Generics) -> ast::Generics {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_bound(
|
||||
cx: &ExtCtxt,
|
||||
pub fn with_where_predicates(
|
||||
builder: &AstBuilder,
|
||||
item: &ast::Item,
|
||||
generics: &ast::Generics,
|
||||
filter: &Fn(&ast::StructField) -> bool,
|
||||
bound: &ast::Path,
|
||||
predicates: &[ast::WherePredicate],
|
||||
) -> ast::Generics {
|
||||
builder.from_generics(generics.clone())
|
||||
.with_predicates(predicates.to_vec())
|
||||
.build()
|
||||
}
|
||||
|
||||
pub fn with_where_predicates_from_fields<F>(
|
||||
builder: &AstBuilder,
|
||||
item: &Item,
|
||||
generics: &ast::Generics,
|
||||
from_field: F,
|
||||
) -> ast::Generics
|
||||
where F: Fn(&attr::Field) -> Option<&[ast::WherePredicate]>,
|
||||
{
|
||||
builder.from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
all_variants(cx, item).iter()
|
||||
.flat_map(|variant_data| all_struct_fields(variant_data))
|
||||
.filter(|field| filter(field))
|
||||
item.body.all_fields()
|
||||
.flat_map(|field| from_field(&field.attrs))
|
||||
.flat_map(|predicates| predicates.to_vec()))
|
||||
.build()
|
||||
}
|
||||
|
||||
pub fn with_bound<F>(
|
||||
builder: &AstBuilder,
|
||||
item: &Item,
|
||||
generics: &ast::Generics,
|
||||
filter: F,
|
||||
bound: &ast::Path,
|
||||
) -> ast::Generics
|
||||
where F: Fn(&attr::Field) -> bool,
|
||||
{
|
||||
builder.from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
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))
|
||||
.map(|ty| strip_reference(ty))
|
||||
.map(|ty| builder.where_predicate()
|
||||
// the type that is being bounded e.g. T
|
||||
@@ -47,34 +75,6 @@ pub fn with_bound(
|
||||
.build()
|
||||
}
|
||||
|
||||
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(_) => {
|
||||
&[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rust <1.7 enforces that `where` clauses involve generic type parameters. The
|
||||
// corresponding compiler error is E0193. It is no longer enforced in Rust >=1.7
|
||||
// so this filtering can be removed in the future when we stop supporting <1.7.
|
||||
@@ -113,6 +113,50 @@ fn contains_generic(ty: &ast::Ty, generics: &ast::Generics) -> bool {
|
||||
visitor.found_generic
|
||||
}
|
||||
|
||||
// We do not attempt to generate any bounds based on field types that are
|
||||
// directly recursive, as in:
|
||||
//
|
||||
// struct Test<D> {
|
||||
// next: Box<Test<D>>,
|
||||
// }
|
||||
//
|
||||
// This does not catch field types that are mutually recursive with some other
|
||||
// type. For those, we require bounds to be specified by a `bound` attribute if
|
||||
// the inferred ones are not correct.
|
||||
//
|
||||
// struct Test<D> {
|
||||
// #[serde(bound="D: Serialize + Deserialize")]
|
||||
// next: Box<Other<D>>,
|
||||
// }
|
||||
// struct Other<D> {
|
||||
// #[serde(bound="D: Serialize + Deserialize")]
|
||||
// next: Box<Test<D>>,
|
||||
// }
|
||||
fn contains_recursion(ty: &ast::Ty, ident: ast::Ident) -> bool {
|
||||
struct FindRecursion {
|
||||
ident: ast::Ident,
|
||||
found_recursion: bool,
|
||||
}
|
||||
impl<'v> visit::Visitor<'v> for FindRecursion {
|
||||
fn visit_path(&mut self, path: &'v ast::Path, _id: ast::NodeId) {
|
||||
if !path.global
|
||||
&& path.segments.len() == 1
|
||||
&& path.segments[0].identifier == self.ident {
|
||||
self.found_recursion = true;
|
||||
} else {
|
||||
visit::walk_path(self, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut visitor = FindRecursion {
|
||||
ident: ident,
|
||||
found_recursion: false,
|
||||
};
|
||||
visit::walk_ty(&mut visitor, ty);
|
||||
visitor.found_recursion
|
||||
}
|
||||
|
||||
// This is required to handle types that use both a reference and a value of
|
||||
// the same type, as in:
|
||||
//
|
||||
|
||||
+279
-300
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,7 @@
|
||||
|
||||
extern crate aster;
|
||||
extern crate quasi;
|
||||
extern crate serde_item as item;
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
extern crate syntex;
|
||||
@@ -22,6 +23,9 @@ extern crate syntax;
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
extern crate rustc_plugin;
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
use syntax::feature_gate::AttributeType;
|
||||
|
||||
@@ -31,6 +35,16 @@ include!(concat!(env!("OUT_DIR"), "/lib.rs"));
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
include!("lib.rs.in");
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
pub fn expand<S, D>(src: S, dst: D) -> Result<(), syntex::Error>
|
||||
where S: AsRef<Path>,
|
||||
D: AsRef<Path>,
|
||||
{
|
||||
let mut registry = syntex::Registry::new();
|
||||
register(&mut registry);
|
||||
registry.expand("", src.as_ref(), dst.as_ref())
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
pub fn register(reg: &mut syntex::Registry) {
|
||||
use syntax::{ast, fold};
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
mod attr;
|
||||
mod bound;
|
||||
mod de;
|
||||
mod error;
|
||||
|
||||
+207
-260
@@ -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,52 +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 impl_generics = build_impl_generics(cx, builder, item, generics);
|
||||
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()));
|
||||
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;
|
||||
@@ -89,172 +74,136 @@ 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,
|
||||
item: &item::Item,
|
||||
) -> ast::Generics {
|
||||
let generics = bound::without_defaults(generics);
|
||||
let generics = bound::with_bound(cx, builder, item, &generics,
|
||||
&serialized_by_us,
|
||||
&builder.path().ids(&["_serde", "ser", "Serialize"]).build());
|
||||
generics
|
||||
let generics = bound::without_defaults(item.generics);
|
||||
|
||||
let generics = bound::with_where_predicates_from_fields(
|
||||
builder, item, &generics,
|
||||
|attrs| attrs.ser_bound());
|
||||
|
||||
match item.attrs.ser_bound() {
|
||||
Some(predicates) => {
|
||||
bound::with_where_predicates(builder, &generics, predicates)
|
||||
}
|
||||
None => {
|
||||
bound::with_bound(builder, item, &generics,
|
||||
needs_serialize_bound,
|
||||
&builder.path().ids(&["_serde", "ser", "Serialize"]).build())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fields with a `skip_serializing` or `serialize_with` attribute are not
|
||||
// serialized by us. All other fields may need a `T: Serialize` bound where T is
|
||||
// the type of the field.
|
||||
fn serialized_by_us(field: &ast::StructField) -> bool {
|
||||
for meta_items in field.attrs.iter().filter_map(attr::get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item.node {
|
||||
ast::MetaItemKind::Word(ref name) if name == &"skip_serializing" => {
|
||||
return false
|
||||
}
|
||||
ast::MetaItemKind::NameValue(ref name, _) if name == &"serialize_with" => {
|
||||
return false
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
// 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::Field) -> bool {
|
||||
!attrs.skip_serializing()
|
||||
&& attrs.serialize_with().is_none()
|
||||
&& attrs.ser_bound().is_none()
|
||||
}
|
||||
|
||||
fn serialize_body(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
item: &Item,
|
||||
item: &item::Item,
|
||||
impl_generics: &ast::Generics,
|
||||
ty: P<ast::Ty>,
|
||||
) -> Result<P<ast::Expr>, 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, _) => {
|
||||
) -> 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(
|
||||
@@ -262,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(),
|
||||
@@ -277,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 {
|
||||
@@ -289,7 +238,7 @@ fn serialize_tuple_struct(
|
||||
state: 0,
|
||||
_structure_ty: ::std::marker::PhantomData::<&$ty>,
|
||||
})
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_struct(
|
||||
@@ -297,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(),
|
||||
@@ -312,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 {
|
||||
@@ -324,7 +273,7 @@ fn serialize_struct(
|
||||
state: 0,
|
||||
_structure_ty: ::std::marker::PhantomData::<&$ty>,
|
||||
})
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_item_enum(
|
||||
@@ -333,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(
|
||||
@@ -348,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(
|
||||
@@ -367,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,
|
||||
@@ -388,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,
|
||||
@@ -399,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();
|
||||
|
||||
@@ -419,7 +366,7 @@ fn serialize_variant(
|
||||
)
|
||||
.build();
|
||||
|
||||
let expr = try!(serialize_tuple_variant(
|
||||
let expr = serialize_tuple_variant(
|
||||
cx,
|
||||
builder,
|
||||
type_name,
|
||||
@@ -427,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();
|
||||
|
||||
@@ -444,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,
|
||||
@@ -458,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 }
|
||||
))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -483,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,
|
||||
@@ -503,7 +448,7 @@ fn serialize_newtype_variant(
|
||||
$variant_name,
|
||||
$field_expr,
|
||||
)
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(
|
||||
@@ -514,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| {
|
||||
@@ -528,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(),
|
||||
@@ -537,7 +482,7 @@ fn serialize_tuple_variant(
|
||||
fields,
|
||||
generics,
|
||||
true,
|
||||
));
|
||||
);
|
||||
|
||||
let value_expr = builder.expr().tuple()
|
||||
.with_exprs(
|
||||
@@ -547,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 {
|
||||
@@ -555,7 +500,7 @@ fn serialize_tuple_variant(
|
||||
state: 0,
|
||||
_structure_ty: ::std::marker::PhantomData::<&$structure_ty>,
|
||||
})
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(
|
||||
@@ -565,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")
|
||||
@@ -580,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")
|
||||
@@ -617,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(),
|
||||
@@ -626,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 {
|
||||
@@ -644,7 +588,7 @@ fn serialize_struct_variant(
|
||||
_structure_ty: ::std::marker::PhantomData,
|
||||
},
|
||||
)
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct_visitor(
|
||||
@@ -653,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, &(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);
|
||||
}
|
||||
@@ -698,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,
|
||||
@@ -727,7 +669,7 @@ fn serialize_tuple_struct_visitor(
|
||||
}
|
||||
}
|
||||
).unwrap(),
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
fn serialize_struct_visitor(
|
||||
@@ -736,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, &(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)
|
||||
}
|
||||
@@ -787,23 +727,23 @@ fn serialize_struct_visitor(
|
||||
.strip_bounds()
|
||||
.build();
|
||||
|
||||
let len = fields_with_attrs.iter()
|
||||
.filter(|&&(_, ref attrs)| !attrs.skip_serializing_field())
|
||||
.map(|&(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,
|
||||
@@ -835,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,
|
||||
@@ -863,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 {
|
||||
@@ -876,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())
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
@@ -0,0 +1,637 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use syntax::ast::{self, TokenTree};
|
||||
use syntax::attr;
|
||||
use syntax::codemap::{Span, Spanned, respan};
|
||||
use syntax::ext::base::ExtCtxt;
|
||||
use syntax::fold::Folder;
|
||||
use syntax::parse::parser::{Parser, PathStyle};
|
||||
use syntax::parse::token::{self, InternedString};
|
||||
use syntax::parse;
|
||||
use syntax::print::pprust::{lit_to_string, meta_item_to_string};
|
||||
use syntax::ptr::P;
|
||||
|
||||
// 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.
|
||||
|
||||
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 {
|
||||
serialize: InternedString,
|
||||
deserialize: InternedString,
|
||||
}
|
||||
|
||||
impl Name {
|
||||
/// Return the container name for the container when serializing.
|
||||
pub fn serialize_name(&self) -> InternedString {
|
||||
self.serialize.clone()
|
||||
}
|
||||
|
||||
/// Return the container name for the container when deserializing.
|
||||
pub fn deserialize_name(&self) -> InternedString {
|
||||
self.deserialize.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents container (e.g. struct) attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct Item {
|
||||
name: Name,
|
||||
deny_unknown_fields: bool,
|
||||
ser_bound: Option<Vec<ast::WherePredicate>>,
|
||||
de_bound: Option<Vec<ast::WherePredicate>>,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
/// Extract out the `#[serde(...)]` attributes from an item.
|
||||
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" => {
|
||||
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" => {
|
||||
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" => {
|
||||
deny_unknown_fields.set_true(span);
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound="D: Serialize")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"bound" => {
|
||||
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" => {
|
||||
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
|
||||
ser_bound.set_opt(ser);
|
||||
de_bound.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde container attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn deny_unknown_fields(&self) -> bool {
|
||||
self.deny_unknown_fields
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
self.ser_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn de_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents variant attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct Variant {
|
||||
name: 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" => {
|
||||
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" => {
|
||||
if let Ok((ser, de)) = get_renames(cx, meta_items) {
|
||||
ser_name.set_opt(ser);
|
||||
de_name.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde variant attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Variant {
|
||||
name: Name {
|
||||
serialize: ser_name.get().unwrap_or(ident.clone()),
|
||||
deserialize: de_name.get().unwrap_or(ident),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents field attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct Field {
|
||||
name: Name,
|
||||
skip_serializing: bool,
|
||||
skip_deserializing: bool,
|
||||
skip_serializing_if: Option<ast::Path>,
|
||||
default: FieldDefault,
|
||||
serialize_with: Option<ast::Path>,
|
||||
deserialize_with: Option<ast::Path>,
|
||||
ser_bound: Option<Vec<ast::WherePredicate>>,
|
||||
de_bound: Option<Vec<ast::WherePredicate>>,
|
||||
}
|
||||
|
||||
/// Represents the default to use for a field when deserializing.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum FieldDefault {
|
||||
/// Field must always be specified because it does not have a default.
|
||||
None,
|
||||
/// The default is given by `std::default::Default::default()`.
|
||||
Default,
|
||||
/// The default is given by this function.
|
||||
Path(ast::Path),
|
||||
}
|
||||
|
||||
impl Field {
|
||||
/// Extract out the `#[serde(...)]` attributes from a struct field.
|
||||
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 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" => {
|
||||
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" => {
|
||||
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" => {
|
||||
default.set(span, FieldDefault::Default);
|
||||
}
|
||||
|
||||
// Parse `#[serde(default="...")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"default" => {
|
||||
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" => {
|
||||
skip_serializing.set_true(span);
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_deserializing)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"skip_deserializing" => {
|
||||
skip_deserializing.set_true(span);
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_serializing_if="...")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"skip_serializing_if" => {
|
||||
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" => {
|
||||
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" => {
|
||||
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" => {
|
||||
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" => {
|
||||
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
|
||||
ser_bound.set_opt(ser);
|
||||
de_bound.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde field attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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(&self) -> bool {
|
||||
self.skip_serializing
|
||||
}
|
||||
|
||||
pub fn skip_deserializing(&self) -> bool {
|
||||
self.skip_deserializing
|
||||
}
|
||||
|
||||
pub fn skip_serializing_if(&self) -> Option<&ast::Path> {
|
||||
self.skip_serializing_if.as_ref()
|
||||
}
|
||||
|
||||
pub fn default(&self) -> &FieldDefault {
|
||||
&self.default
|
||||
}
|
||||
|
||||
pub fn serialize_with(&self) -> Option<&ast::Path> {
|
||||
self.serialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn deserialize_with(&self) -> Option<&ast::Path> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
self.ser_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn de_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
}
|
||||
|
||||
fn get_ser_and_de<T, F>(
|
||||
cx: &ExtCtxt,
|
||||
attribute: &'static str,
|
||||
items: &[P<ast::MetaItem>],
|
||||
f: F
|
||||
) -> Result<(Option<Spanned<T>>, Option<Spanned<T>>), ()>
|
||||
where F: Fn(&ExtCtxt, &str, &ast::Lit) -> Result<T, ()>,
|
||||
{
|
||||
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" => {
|
||||
if let Ok(v) = f(cx, name, lit) {
|
||||
ser_item.set(item.span, v);
|
||||
}
|
||||
}
|
||||
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => {
|
||||
if let Ok(v) = f(cx, name, lit) {
|
||||
de_item.set(item.span, v);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
item.span,
|
||||
&format!("unknown {} attribute `{}`",
|
||||
attribute,
|
||||
meta_item_to_string(item)));
|
||||
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((ser_item.get_spanned(), de_item.get_spanned()))
|
||||
}
|
||||
|
||||
fn get_renames(
|
||||
cx: &ExtCtxt,
|
||||
items: &[P<ast::MetaItem>],
|
||||
) -> 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<Spanned<Vec<ast::WherePredicate>>>, Option<Spanned<Vec<ast::WherePredicate>>>), ()> {
|
||||
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
|
||||
}
|
||||
|
||||
pub fn get_serde_meta_items(attr: &ast::Attribute) -> Option<&[P<ast::MetaItem>]> {
|
||||
match attr.node.value.node {
|
||||
ast::MetaItemKind::List(ref name, ref items) if name == &"serde" => {
|
||||
attr::mark_used(&attr);
|
||||
Some(items)
|
||||
}
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
/// This syntax folder rewrites tokens to say their spans are coming from a macro context.
|
||||
struct Respanner<'a, 'b: 'a> {
|
||||
cx: &'a ExtCtxt<'b>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> Folder for Respanner<'a, 'b> {
|
||||
fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree {
|
||||
match *tt {
|
||||
TokenTree::Token(span, ref tok) => {
|
||||
TokenTree::Token(
|
||||
self.new_span(span),
|
||||
self.fold_token(tok.clone())
|
||||
)
|
||||
}
|
||||
TokenTree::Delimited(span, ref delimed) => {
|
||||
TokenTree::Delimited(
|
||||
self.new_span(span),
|
||||
Rc::new(ast::Delimited {
|
||||
delim: delimed.delim,
|
||||
open_span: delimed.open_span,
|
||||
tts: self.fold_tts(&delimed.tts),
|
||||
close_span: delimed.close_span,
|
||||
})
|
||||
)
|
||||
}
|
||||
TokenTree::Sequence(span, ref seq) => {
|
||||
TokenTree::Sequence(
|
||||
self.new_span(span),
|
||||
Rc::new(ast::SequenceRepetition {
|
||||
tts: self.fold_tts(&seq.tts),
|
||||
separator: seq.separator.clone().map(|tok| self.fold_token(tok)),
|
||||
..**seq
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn new_span(&mut self, span: Span) -> Span {
|
||||
Span {
|
||||
lo: span.lo,
|
||||
hi: span.hi,
|
||||
expn_id: self.cx.backtrace(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
_ => {
|
||||
cx.span_err(
|
||||
lit.span,
|
||||
&format!("serde annotation `{}` must be a string, not `{}`",
|
||||
name,
|
||||
lit_to_string(lit)));
|
||||
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we just parse a string literal from an attibute, any syntax errors in the
|
||||
// source will only have spans that point inside the string and not back to the
|
||||
// attribute. So to have better error reporting, we'll first parse the string
|
||||
// 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, ()>
|
||||
where F: for<'a> Fn(&'a mut Parser) -> parse::PResult<'a, T>,
|
||||
{
|
||||
let tts = panictry!(parse::parse_tts_from_source_str(
|
||||
format!("<serde {} expansion>", name),
|
||||
string,
|
||||
cx.cfg(),
|
||||
cx.parse_sess()));
|
||||
|
||||
// Respan the spans to say they are all coming from this macro.
|
||||
let tts = Respanner { cx: cx }.fold_tts(&tts);
|
||||
|
||||
let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts);
|
||||
|
||||
let path = match action(&mut parser) {
|
||||
Ok(path) => path,
|
||||
Err(mut e) => {
|
||||
e.emit();
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
// Make sure to error out if there are trailing characters in the stream.
|
||||
match parser.expect(&token::Eof) {
|
||||
Ok(()) => { }
|
||||
Err(mut e) => {
|
||||
e.emit();
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
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| {
|
||||
parser.parse_path(PathStyle::Type)
|
||||
})
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
let where_string = format!("where {}", string);
|
||||
|
||||
parse_string_via_tts(cx, name, where_string, |parser| {
|
||||
let where_clause = try!(parser.parse_where_clause());
|
||||
Ok(where_clause.predicates)
|
||||
})
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_macros"
|
||||
version = "0.7.7"
|
||||
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,12 +18,13 @@ nightly-testing = ["clippy", "serde/nightly-testing", "serde_codegen/nightly-tes
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "^0.*", optional = true }
|
||||
serde_codegen = { version = "^0.7.7", 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.7", 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,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_tests"
|
||||
version = "0.7.6"
|
||||
version = "0.7.11"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
@@ -14,14 +14,12 @@ build = "build.rs"
|
||||
nightly-testing = ["clippy", "serde/nightly-testing", "serde_codegen/nightly-testing"]
|
||||
|
||||
[build-dependencies]
|
||||
syntex = { version = "^0.33.0" }
|
||||
syntex_syntax = { version = "^0.33.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.33.0"
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "^0.*", optional = true }
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
extern crate syntex;
|
||||
extern crate serde_codegen;
|
||||
|
||||
use std::env;
|
||||
@@ -13,10 +12,6 @@ fn main() {
|
||||
] {
|
||||
let src = Path::new(src);
|
||||
let dst = Path::new(&out_dir).join(dst);
|
||||
|
||||
let mut registry = syntex::Registry::new();
|
||||
|
||||
serde_codegen::register(&mut registry);
|
||||
registry.expand("", &src, &dst).unwrap();
|
||||
serde_codegen::expand(&src, &dst).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,14 @@ macro_rules! hashset {
|
||||
$(set.insert($value);)+
|
||||
set
|
||||
}
|
||||
};
|
||||
($hasher:ident @ $($value:expr),+) => {
|
||||
{
|
||||
use std::hash::BuildHasherDefault;
|
||||
let mut set = HashSet::with_hasher(BuildHasherDefault::<$hasher>::default());
|
||||
$(set.insert($value);)+
|
||||
set
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,5 +83,13 @@ macro_rules! hashmap {
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
};
|
||||
($hasher:ident @ $($key:expr => $value:expr),+) => {
|
||||
{
|
||||
use std::hash::BuildHasherDefault;
|
||||
let mut map = HashMap::with_hasher(BuildHasherDefault::<$hasher>::default());
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,7 +441,8 @@ enum RenameEnumSerializeDeserialize<A> {
|
||||
#[serde(rename(serialize="dick_grayson", deserialize="jason_todd"))]
|
||||
Robin {
|
||||
a: i8,
|
||||
#[serde(rename(serialize="c", deserialize="d"))]
|
||||
#[serde(rename(serialize="c"))]
|
||||
#[serde(rename(deserialize="d"))]
|
||||
b: A,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::net;
|
||||
use std::path::PathBuf;
|
||||
|
||||
extern crate fnv;
|
||||
use self::fnv::FnvHasher;
|
||||
|
||||
use token::{
|
||||
Error,
|
||||
Token,
|
||||
@@ -284,6 +287,18 @@ declare_tests! {
|
||||
Token::TupleStructStart("Anything", Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
hashset![FnvHasher @ 1, 2, 3] => vec![
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_vec {
|
||||
Vec::<isize>::new() => vec![
|
||||
@@ -532,6 +547,17 @@ declare_tests! {
|
||||
Token::StructStart("Anything", Some(0)),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![FnvHasher @ 1 => 2, 3 => 4] => vec![
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_struct {
|
||||
Struct { a: 1, b: 2, c: 0 } => vec![
|
||||
|
||||
@@ -74,8 +74,59 @@ struct Tuple<T>(
|
||||
X,
|
||||
);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum TreeNode<D> {
|
||||
Split {
|
||||
left: Box<TreeNode<D>>,
|
||||
right: Box<TreeNode<D>>,
|
||||
},
|
||||
Leaf {
|
||||
data: D,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ListNode<D> {
|
||||
data: D,
|
||||
next: Box<ListNode<D>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(bound="D: SerializeWith + DeserializeWith")]
|
||||
struct WithTraits1<D, E> {
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
deserialize_with="DeserializeWith::deserialize_with")]
|
||||
d: D,
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
deserialize_with="DeserializeWith::deserialize_with",
|
||||
bound="E: SerializeWith + DeserializeWith")]
|
||||
e: E,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(bound(serialize="D: SerializeWith",
|
||||
deserialize="D: DeserializeWith"))]
|
||||
struct WithTraits2<D, E> {
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
deserialize_with="DeserializeWith::deserialize_with")]
|
||||
d: D,
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
bound(serialize="E: SerializeWith"))]
|
||||
#[serde(deserialize_with="DeserializeWith::deserialize_with",
|
||||
bound(deserialize="E: DeserializeWith"))]
|
||||
e: E,
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
trait SerializeWith {
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: &mut S) -> Result<(), S::Error>;
|
||||
}
|
||||
|
||||
trait DeserializeWith: Sized {
|
||||
fn deserialize_with<D: Deserializer>(_: &mut D) -> Result<Self, D::Error>;
|
||||
}
|
||||
|
||||
// Implements neither Serialize nor Deserialize
|
||||
struct X;
|
||||
fn ser_x<S: Serializer>(_: &X, _: &mut S) -> Result<(), S::Error> { panic!() }
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::net;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str;
|
||||
|
||||
use token::{self, Token};
|
||||
|
||||
extern crate fnv;
|
||||
use self::fnv::FnvHasher;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -144,6 +147,24 @@ declare_ser_tests! {
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_hashset {
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
hashset![1] => &[
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
hashset![FnvHasher @ 1] => &[
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_tuple {
|
||||
(1,) => &[
|
||||
Token::TupleStart(1),
|
||||
@@ -204,6 +225,26 @@ declare_ser_tests! {
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_hashmap {
|
||||
HashMap::<isize, isize>::new() => &[
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![1 => 2] => &[
|
||||
Token::MapStart(Some(1)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![FnvHasher @ 1 => 2] => &[
|
||||
Token::MapStart(Some(1)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_unit_struct {
|
||||
UnitStruct => &[Token::UnitStruct("UnitStruct")],
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user