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
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
#[macro_use]
extern crate syn;
use proc_macro::TokenStream;
use proc_macro2::Ident;
use proc_macro_roids::{FieldsExt, IdentExt};
use syn::{
parse_macro_input, Fields, GenericParam, Generics, ImplGenerics, ItemEnum, PathSegment,
PredicateType, TraitBound, Type, TypeGenerics, TypeParam, TypeParamBound, TypePath,
WhereClause, WherePredicate,
};
#[proc_macro_attribute]
pub fn enser(_args: TokenStream, input: TokenStream) -> TokenStream {
let mut item = parse_macro_input!(input as ItemEnum);
let gen = impl_enser_derive(&mut item);
gen.into()
}
fn impl_enser_derive(the_enum: &mut ItemEnum) -> proc_macro2::TokenStream {
// The enum must implement `Clone`, as well as `Deserialize` and `Serialize`.
let mut enser = the_enum.clone();
// generate separate enum, attach `(())` to every unit variant
let enser_mod: Ident = parse_quote!(_enser);
let enser_mod = enser_mod.append(&the_enum.ident);
let enser_enum_name = enser.ident.append("Serde");
// MyEnum -> MyEnumSerde
enser.vis = parse_quote!(pub(super));
enser.ident = enser_enum_name;
// Variant -> Variant(())
attach_tuple_to_unit_variants(&mut enser);
let Generics {
params,
where_clause,
..
} = &mut the_enum.generics;
params.iter_mut().for_each(|generic_param| {
if let GenericParam::Type(TypeParam {
ident: type_param_ident,
bounds,
..
}) = generic_param
{
// If neither the bounds in the param / in the where clause contains `Clone`,
// then we add the `Clone` bound
let where_bounds_for_type_contains_clone =
if let Some(where_clause) = where_clause.as_ref() {
where_clause
.predicates
.iter()
.filter_map(|predicate| {
if let WherePredicate::Type(PredicateType {
bounded_ty: Type::Path(TypePath { path, .. }),
bounds,
..
}) = predicate
{
if path.segments.len() == 1 {
if let Some(PathSegment {
ident: predicate_ident,
..
}) = path.segments.last()
{
if type_param_ident == predicate_ident {
// This where predicate is for the type param
return Some(bounds);
}
}
}
}
None
})
.any(|bounds| bounds_contains_clone(bounds.iter()))
} else {
false
};
if !bounds_contains_clone(bounds.iter()) && !where_bounds_for_type_contains_clone {
// Add the `Clone` bound
//
// We can't add this to the type bounds, because something makes Rust error:
//
// ```text
// error[E0658]: associated type bounds are unstable
// --> examples/generics.rs:13:1
// |
// 13 | #[enser::enser]
// | ^^^^^^^^^^^^^^^
// |
// = note: see issue #52662 <https://github.com/rust-lang/rust/issues/52662> for more information
// = help: add `#![feature(associated_type_bounds)]` to the crate attributes to enable
// = note: this error originates in the attribute macro `enser::enser` (in Nightly builds, run with -Z macro-backtrace for more info)
// For more information about this error, try `rustc --explain E0658`.
// ```
//
// Possibly one of the serde generated impls.
if let Some(where_clause) = where_clause.as_mut() {
let where_predicate_exists = where_clause
.predicates
.iter_mut()
.filter_map(|predicate| {
if let WherePredicate::Type(PredicateType {
bounded_ty: Type::Path(TypePath { path, .. }),
bounds,
..
}) = predicate
{
if path.segments.len() == 1 {
if let Some(PathSegment {
ident: predicate_ident,
..
}) = path.segments.last()
{
if type_param_ident == predicate_ident {
// This where predicate is for the type param
return Some(bounds);
}
}
}
}
None
})
// Only apply `Clone` to one predicate
.next()
.map(|bounds| {
bounds.push(parse_quote!(std::clone::Clone));
true
})
.unwrap_or(false);
if !where_predicate_exists {
// Need to add one for this type parameter
where_clause
.predicates
.push(parse_quote!(#type_param_ident: std::clone::Clone))
}
} else {
// We need to attach the where clause
*where_clause = Some(parse_quote!(where #type_param_ident: std::clone::Clone,));
}
}
}
});
let generics_split = the_enum.generics.split_for_impl();
let the_enum_from_enser = impl_the_enum_from_enser(the_enum, &enser, &generics_split);
let enser_from_the_enum = impl_enser_from_the_enum(the_enum, &enser, &generics_split);
// Tell serde to serialize and deserialize with `enser`
let ty_generics = &generics_split.0;
let ty_generics = quote!(#ty_generics);
let enser_enum_name = &enser.ident;
let enser_enum_path_str = format!("{enser_mod}::{enser_enum_name}{ty_generics}");
the_enum
.attrs
.push(parse_quote!(#[serde(from = #enser_enum_path_str, into = #enser_enum_path_str)]));
quote! {
#the_enum
mod #enser_mod {
// Imports `serde` or `{Deserialize, Serialize}`, depending on usage.
use super::*;
#enser
#the_enum_from_enser
#enser_from_the_enum
}
}
}
fn bounds_contains_clone<'bounds>(
mut bounds: impl Iterator<Item = &'bounds TypeParamBound>,
) -> bool {
bounds.any(|bound| {
matches!(
bound,
TypeParamBound::Trait(TraitBound { path, .. }) if matches!(
path.segments.last(),
Some(PathSegment { ident, .. }) if ident == "Clone"))
})
}
fn attach_tuple_to_unit_variants(enser: &mut ItemEnum) {
enser
.variants
.iter_mut()
.filter_map(|variant| {
if let Fields::Unit = &variant.fields {
Some(&mut variant.fields)
} else {
None
}
})
.for_each(|fields| *fields = Fields::Unnamed(parse_quote!((()))));
}
fn impl_the_enum_from_enser(
the_enum: &ItemEnum,
enser: &ItemEnum,
generics_split: &(ImplGenerics<'_>, TypeGenerics<'_>, Option<&WhereClause>),
) -> proc_macro2::TokenStream {
let the_enum_name = &the_enum.ident;
let enser_enum_name = &enser.ident;
let variant_mappings = the_enum.variants.iter().map(|variant| {
let variant_name = &variant.ident;
match &variant.fields {
Fields::Unit => {
quote!(#enser_enum_name::#variant_name(()) => #the_enum_name::#variant_name)
}
fields @ Fields::Unnamed(_) | fields @ Fields::Named(_) => {
let fields = fields.construction_form();
quote! {
#enser_enum_name::#variant_name #fields =>
#the_enum_name::#variant_name #fields
}
}
}
});
let (impl_generics, ty_generics, where_clause) = generics_split;
quote! {
impl #impl_generics From<#enser_enum_name #ty_generics> for #the_enum_name #ty_generics #where_clause {
fn from(enser_enum: #enser_enum_name #ty_generics) -> Self {
match enser_enum {
#(#variant_mappings),*
}
}
}
}
}
fn impl_enser_from_the_enum(
the_enum: &ItemEnum,
enser: &ItemEnum,
generics_split: &(ImplGenerics<'_>, TypeGenerics<'_>, Option<&WhereClause>),
) -> proc_macro2::TokenStream {
let the_enum_name = &the_enum.ident;
let enser_enum_name = &enser.ident;
let variant_mappings = the_enum.variants.iter().map(|variant| {
let variant_name = &variant.ident;
match &variant.fields {
Fields::Unit => {
quote!(#the_enum_name::#variant_name => #enser_enum_name::#variant_name(()))
}
fields @ Fields::Unnamed(_) | fields @ Fields::Named(_) => {
let fields = fields.construction_form();
quote! {
#the_enum_name::#variant_name #fields =>
#enser_enum_name::#variant_name #fields
}
}
}
});
let (impl_generics, ty_generics, where_clause) = generics_split;
quote! {
impl #impl_generics From<#the_enum_name #ty_generics> for #enser_enum_name #ty_generics #where_clause {
fn from(the_enum: #the_enum_name #ty_generics) -> Self {
match the_enum {
#(#variant_mappings),*
}
}
}
}
}