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
use quote::quote;
use syn::{AttributeArgs, ItemStruct, NestedMeta};
#[proc_macro_attribute]
pub fn make_optional(
args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let args = syn::parse_macro_input!(args as AttributeArgs);
let mut input = syn::parse_macro_input!(input as ItemStruct);
impl_make_optional(&args, &mut input).into()
}
fn impl_make_optional(_args: &[NestedMeta], obj: &mut ItemStruct) -> proc_macro2::TokenStream {
match obj.fields {
syn::Fields::Named(ref mut fields) => fields.named.iter_mut().for_each(update_field),
syn::Fields::Unnamed(ref mut fields) => fields.unnamed.iter_mut().for_each(update_field),
syn::Fields::Unit => {}
}
quote! {
#obj
}
}
fn update_field(field: &mut syn::Field) {
let attr = syn::parse_quote!(
#[serde(skip_serializing_if = "Option::is_none")]
);
field.attrs.push(attr);
let orig_ty = &field.ty;
field.ty = syn::Type::Verbatim(quote!(Option<#orig_ty>));
}