1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use proc_macro2::{TokenStream, TokenTree};
use serde::{de::Error, de::Visitor, Deserialize};
#[derive(Debug)]
pub struct TokenStreamWrapper(TokenStream);
impl TokenStreamWrapper {
pub fn into_inner(self) -> TokenStream {
self.0
}
}
impl<'de> Deserialize<'de> for TokenStreamWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Self(deserializer.deserialize_bytes(WrapperVisitor)?))
}
}
impl std::ops::Deref for TokenStreamWrapper {
type Target = TokenStream;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug)]
pub struct ParseWrapper<P: syn::parse::Parse>(P);
impl<P: syn::parse::Parse> ParseWrapper<P> {
pub fn into_inner(self) -> P {
self.0
}
}
impl<'de, P: syn::parse::Parse> Deserialize<'de> for ParseWrapper<P> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let token_stream = deserializer.deserialize_bytes(WrapperVisitor)?;
Ok(Self(
syn::parse2::<P>(token_stream)
.map_err(|e| D::Error::custom(&e.to_string()))?,
))
}
}
impl<P: syn::parse::Parse> std::ops::Deref for ParseWrapper<P> {
type Target = P;
fn deref(&self) -> &Self::Target {
&self.0
}
}
struct WrapperVisitor;
impl<'de> Visitor<'de> for WrapperVisitor {
type Value = TokenStream;
fn expecting(
&self,
formatter: &mut std::fmt::Formatter,
) -> std::fmt::Result {
formatter.write_str("TokenStream")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
deserialize_token_stream(v)
}
}
pub(crate) fn serialize_token_stream(tokens: Vec<TokenTree>) -> Vec<u8> {
tokens.into_iter().collect::<TokenStream>().to_string().bytes().collect()
}
fn deserialize_token_stream<E: serde::de::Error>(
v: &[u8],
) -> Result<TokenStream, E> {
String::from_utf8(v.to_vec())
.unwrap()
.parse()
.map_err(|_| E::custom("parse error"))
}