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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#![deny(
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences
)]
#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))]
#![doc(html_root_url = "https://docs.rs/serde_with_macros/1.1.0")]
extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{
parse::Parser, Attribute, Error, Field, Fields, ItemEnum, ItemStruct, Meta, NestedMeta, Path,
Type,
};
#[proc_macro_attribute]
pub fn skip_serializing_none(_args: TokenStream, input: TokenStream) -> TokenStream {
let res = match skip_serializing_none_do(input) {
Ok(res) => res,
Err(msg) => {
let span = Span::call_site();
Error::new(span, msg).to_compile_error()
}
};
TokenStream::from(res)
}
fn skip_serializing_none_do(input: TokenStream) -> Result<proc_macro2::TokenStream, String> {
if let Ok(mut input) = syn::parse::<ItemStruct>(input.clone()) {
skip_serializing_none_handle_fields(&mut input.fields)?;
Ok(quote!(#input))
} else if let Ok(mut input) = syn::parse::<ItemEnum>(input) {
input
.variants
.iter_mut()
.map(|variant| skip_serializing_none_handle_fields(&mut variant.fields))
.collect::<Result<(), _>>()?;
Ok(quote!(#input))
} else {
Err("The attribute can only be applied to struct or enum definitions.".into())
}
}
fn is_std_option(path: &Path) -> bool {
(path.leading_colon.is_none() && path.segments.len() == 1 && path.segments[0].ident == "Option")
|| (path.segments.len() == 3
&& (path.segments[0].ident == "std" || path.segments[0].ident == "core")
&& path.segments[1].ident == "option"
&& path.segments[2].ident == "Option")
}
#[cfg_attr(feature = "cargo-clippy", allow(cmp_owned))]
fn field_has_attribute(field: &Field, namespace: &str, name: &str) -> bool {
for attr in &field.attrs {
if attr.path.is_ident(namespace) {
if let Ok(expr) = attr.parse_meta() {
if let Meta::List(expr) = expr {
for expr in expr.nested {
if let NestedMeta::Meta(Meta::NameValue(expr)) = expr {
if let Some(ident) = expr.path.get_ident() {
if ident.to_string() == name {
return true;
}
}
}
}
}
}
}
}
false
}
fn skip_serializing_none_add_attr_to_field<'a>(
fields: impl IntoIterator<Item = &'a mut Field>,
) -> Result<(), String> {
fields.into_iter().map(|field| ->Result<(), String> {
if let Type::Path(path) = &field.ty.clone() {
if is_std_option(&path.path) {
let has_skip_serializing_if =
field_has_attribute(&field, "serde", "skip_serializing_if");
let mut has_always_attr = false;
field.attrs.retain(|attr| {
let has_attr = attr.path.is_ident("serialize_always");
has_always_attr |= has_attr;
!has_attr
});
if has_always_attr && has_skip_serializing_if {
let mut msg = r#"The attributes `serialize_always` and `serde(skip_serializing_if = "...")` cannot be used on the same field"#.to_string();
if let Some(ident) = &field.ident {
msg += ": `";
msg += &ident.to_string();
msg += "`";
}
msg +=".";
return Err(msg);
}
if has_skip_serializing_if || has_always_attr {
return Ok(());
}
let attr_tokens = quote!(
#[serde(skip_serializing_if = "Option::is_none")]
);
let parser = Attribute::parse_outer;
let attrs = parser
.parse2(attr_tokens)
.expect("Static attr tokens should not panic");
field.attrs.extend(attrs);
} else {
let has_attr= field.attrs.iter().any(|attr| {
attr.path.is_ident("serialize_always")
});
if has_attr {
return Err("`serialize_always` may only be used on fields of type `Option`.".into());
}
}
}
Ok(())
}).collect()
}
fn skip_serializing_none_handle_fields(fields: &mut Fields) -> Result<(), String> {
match fields {
Fields::Unit => Ok(()),
Fields::Named(ref mut fields) => {
skip_serializing_none_add_attr_to_field(fields.named.iter_mut())
}
Fields::Unnamed(ref mut fields) => {
skip_serializing_none_add_attr_to_field(fields.unnamed.iter_mut())
}
}
}