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
use proc_macro::TokenStream;
use quote::ToTokens;
use syn::{
parse::{Error, Parse, ParseStream},
spanned::Spanned,
Fields, FnArg, ItemEnum, ItemFn, Pat,
};
#[proc_macro_attribute]
pub fn with_methods(arg: TokenStream, input: TokenStream) -> TokenStream {
let mut input_methods = syn::parse_macro_input!(arg as Methods).0;
let input_enum = syn::parse_macro_input!(input as ItemEnum);
let mut errors = vec![];
for method in input_methods.iter_mut() {
if let Err(error) = add_block_to_fn(method, &input_enum) {
let span = error.span;
let message = error.message;
errors.push(quote::quote_spanned! {
span.span() => compile_error!(#message);
})
}
}
let enum_ident = &input_enum.ident;
let enum_impl = quote::quote! {
impl #enum_ident {
#(#input_methods)*
}
};
TokenStream::from(quote::quote! {
#input_enum
#enum_impl
#(#errors)*
})
}
struct Methods(Vec<ItemFn>);
impl Parse for Methods {
fn parse(input: ParseStream) -> Result<Self, Error> {
let mut methods = vec![];
while !input.is_empty() {
methods.push(input.parse()?);
}
Ok(Methods(methods))
}
}
fn add_block_to_fn(input_method: &mut ItemFn, input_enum: &ItemEnum) -> Result<(), MacroError> {
let method_ident = &input_method.sig.ident;
let mut has_self_arg = false;
let method_arg_idents: Vec<_> = input_method
.sig
.inputs
.iter()
.filter_map(|i| match i {
FnArg::Typed(t) => match &*t.pat {
Pat::Ident(i) => {
if i.ident == "self" {
has_self_arg = true;
None
} else {
Some(i.ident.to_token_stream())
}
}
_ => None,
},
FnArg::Receiver(_) => {
has_self_arg = true;
None
}
})
.collect();
let and = syn::Token![&](method_ident.span());
let self_token = syn::Token![self](method_ident.span());
if !has_self_arg {
input_method.sig.inputs.insert(
0,
FnArg::Receiver(syn::Receiver {
attrs: vec![],
reference: Some((and, None)),
mutability: None,
self_token,
}),
);
}
let mut match_arms = vec![];
for variant in &input_enum.variants {
let variant_ident = &variant.ident;
match &variant.fields {
Fields::Named(fields) => {
let mut first_field = fields
.named
.first()
.ok_or_else(|| MacroError {
span: Box::new(fields.clone()),
message: "variants must have at least one field".to_string(),
})?
.clone();
let path = if let syn::Type::Path(path) = &mut first_field.ty {
path
} else {
panic!();
};
for seg in &mut path.path.segments {
if let syn::PathArguments::AngleBracketed(gen) = &mut seg.arguments {
let colon2 = syn::Token![::](gen.span());
gen.colon2_token = Some(colon2);
}
}
let first_field_ident = first_field.ident.as_ref().unwrap();
let first_field_type = &first_field.ty;
let match_arm = if has_self_arg {
quote::quote! {
Self::#variant_ident { #first_field_ident, .. } => #first_field_type :: #method_ident (#first_field_ident, #(#method_arg_idents,)* )
}
} else {
quote::quote! {
Self::#variant_ident { .. } => #first_field_type :: #method_ident (#(#method_arg_idents,)* )
}
};
match_arms.push(match_arm);
}
Fields::Unnamed(fields) => {
let mut first_field = fields
.unnamed
.first()
.ok_or_else(|| MacroError {
span: Box::new(fields.clone()),
message: "variants must have at least one field".to_string(),
})?
.clone();
let path = if let syn::Type::Path(path) = &mut first_field.ty {
path
} else {
panic!();
};
for seg in &mut path.path.segments {
if let syn::PathArguments::AngleBracketed(gen) = &mut seg.arguments {
let colon2 = syn::Token![::](gen.span());
gen.colon2_token = Some(colon2);
}
}
let match_arm = if has_self_arg {
quote::quote! {
Self::#variant_ident ( f_1, .. ) => #first_field :: #method_ident (f_1, #(#method_arg_idents,)* )
}
} else {
quote::quote! {
Self::#variant_ident ( .. ) => #first_field :: #method_ident ( #(#method_arg_idents,)* )
}
};
match_arms.push(match_arm);
}
Fields::Unit => {
return Err(MacroError {
span: Box::new(variant.clone()),
message: "variants must have at least one field".to_string(),
})
}
};
}
input_method.block = syn::parse(
quote::quote!(
{
match self {
#(#match_arms),*
}
}
)
.into(),
)
.map_err(|e| MacroError {
message: e.to_string(),
span: Box::new(e.span()),
})?;
Ok(())
}
struct MacroError {
span: Box<dyn Spanned>,
message: String,
}