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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
extern crate proc_macro;
use inflector::Inflector;
use pmutil::{smart_quote, Quote, ToTokensExt};
use proc_macro2::Span;
use quote::quote;
use syn::punctuated::{Pair, Punctuated};
use syn::spanned::Spanned;
use syn::{
parse, Data, DataEnum, DeriveInput, Field, Fields, Generics, Ident, ImplItem, ItemImpl, Lit,
Meta, MetaNameValue, NestedMeta, Path, Token, Type, TypePath, TypeReference, TypeTuple,
WhereClause,
};
#[proc_macro_derive(Is, attributes(is))]
pub fn is(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input: DeriveInput = syn::parse(input).expect("failed to parse derive input");
let generics: Generics = input.generics.clone();
let items = match input.data {
Data::Enum(e) => expand(e),
_ => panic!("`Is` can be applied only on enums"),
};
ItemImpl {
attrs: vec![],
defaultness: None,
unsafety: None,
impl_token: Default::default(),
generics: Default::default(),
trait_: None,
self_ty: Box::new(Type::Path(TypePath {
qself: None,
path: Path::from(input.ident),
})),
brace_token: Default::default(),
items,
}
.with_generics(generics)
.dump()
.into()
}
#[derive(Debug)]
struct Input {
name: String,
}
fn expand(input: DataEnum) -> Vec<ImplItem> {
let mut items = vec![];
for v in &input.variants {
let attrs = v
.attrs
.iter()
.filter(|attr| attr.path.is_ident("is"))
.collect::<Vec<_>>();
if attrs.len() >= 2 {
panic!("derive(Is) expects no attribute or one attribute")
}
let i = match attrs.into_iter().next() {
None => Input {
name: {
v.ident.to_string().to_snake_case()
},
},
Some(attr) => {
let meta = attr
.parse_meta()
.unwrap_or_else(|err| panic!("failed to parse is({:?}): {}", attr.tokens, err));
let mut input = Input {
name: Default::default(),
};
let mut apply = |v: MetaNameValue| {
assert!(
v.path.is_ident("name"),
"Currently, is() only supports `is(name = 'foo')`"
);
input.name = match v.lit {
Lit::Str(s) => s.value(),
_ => unimplemented!(
"is(): name must be a string li teral but {:?} is provided",
v.lit
),
};
};
match meta {
Meta::NameValue(v) => {
apply(v)
}
Meta::List(l) => {
for meta in l.nested {
match meta {
NestedMeta::Lit(l) => {
unimplemented!("is($literal) where $literal = {:?}", l)
}
NestedMeta::Meta(Meta::NameValue(v)) => apply(v),
_ => unimplemented!("is({})", meta.dump()),
}
}
}
_ => unimplemented!("is({:?})", meta),
}
input
}
};
let name = &*i.name;
{
let name_of_is = Ident::new(&format!("is_{}", name), v.ident.span());
let docs_of_is = format!(
"Returns `true` if `self` is of variant [`{variant}`].\n\n\
[`{variant}`]: #variant.{variant}",
variant = v.ident,
);
items.extend(
Quote::new_call_site()
.quote_with(smart_quote!(
Vars {
docs_of_is,
name_of_is,
Variant: &v.ident
},
{
impl Type {
#[doc = docs_of_is]
#[inline]
pub const fn name_of_is(&self) -> bool {
match *self {
Self::Variant { .. } => true,
_ => false,
}
}
}
}
))
.parse::<ItemImpl>()
.items,
);
}
{
let name_of_cast = Ident::new(&format!("as_{}", name), v.ident.span());
let name_of_cast_mut = Ident::new(&format!("as_mut_{}", name), v.ident.span());
let name_of_expect = Ident::new(&format!("expect_{}", name), v.ident.span());
let name_of_take = Ident::new(&name, v.ident.span());
let docs_of_cast = format!(
"Returns `Some` if `self` is a reference of variant [`{variant}`], and `None` otherwise.\n\n\
[`{variant}`]: #variant.{variant}",
variant = v.ident,
);
let docs_of_cast_mut = format!(
"Returns `Some` if `self` is a mutable reference of variant [`{variant}`], and `None` otherwise.\n\n\
[`{variant}`]: #variant.{variant}",
variant = v.ident,
);
let docs_of_expect = format!(
"Unwraps the value, yielding the content of [`{variant}`].\n\n\
# Panics\n\n\
Panics if the value is not [`{variant}`], with a panic message including \
the content of `self`.\n\n\
[`{variant}`]: #variant.{variant}",
variant = v.ident,
);
let docs_of_take = format!(
"Returns `Some` if `self` is of variant [`{variant}`], and `None` otherwise.\n\n\
[`{variant}`]: #variant.{variant}",
variant = v.ident,
);
match &v.fields {
Fields::Unnamed(fields) => {
let types = fields.unnamed.iter().map(|f| f.ty.clone());
let cast_ty = types_to_type(types.clone().map(|ty| add_ref(false, ty)));
let cast_ty_mut = types_to_type(types.clone().map(|ty| add_ref(true, ty)));
let ty = types_to_type(types);
let mut fields: Punctuated<Ident, Token![,]> = fields
.unnamed
.clone()
.into_pairs()
.enumerate()
.map(|(i, pair)| {
let handle = |f: Field| {
Ident::new(&format!("v{}", i), f.span())
};
match pair {
Pair::Punctuated(v, p) => Pair::Punctuated(handle(v), p),
Pair::End(v) => Pair::End(handle(v)),
}
})
.collect();
if let Some(mut pair) = fields.pop() {
if let Pair::Punctuated(v, _) = pair {
pair = Pair::End(v);
}
fields.extend(std::iter::once(pair));
}
items.extend(
Quote::new_call_site()
.quote_with(smart_quote!(
Vars {
docs_of_cast,
docs_of_cast_mut,
docs_of_expect,
docs_of_take,
name_of_cast,
name_of_cast_mut,
name_of_expect,
name_of_take,
Variant: &v.ident,
Type: &ty,
CastType: &cast_ty,
CastTypeMut: &cast_ty_mut,
v: &fields,
},
{
impl Type {
#[doc = docs_of_cast]
#[inline]
pub fn name_of_cast(&self) -> Option<CastType> {
match self {
Self::Variant(v) => Some((v)),
_ => None,
}
}
#[doc = docs_of_cast_mut]
#[inline]
pub fn name_of_cast_mut(&mut self) -> Option<CastTypeMut> {
match self {
Self::Variant(v) => Some((v)),
_ => None,
}
}
#[doc = docs_of_expect]
#[inline]
pub fn name_of_expect(self) -> Type
where
Self: ::std::fmt::Debug,
{
match self {
Self::Variant(v) => (v),
_ => panic!("called expect on {:?}", self),
}
}
#[doc = docs_of_take]
#[inline]
pub fn name_of_take(self) -> Option<Type> {
match self {
Self::Variant(v) => Some((v)),
_ => None,
}
}
}
}
))
.parse::<ItemImpl>()
.items,
);
}
_ => {}
}
}
}
items
}
fn types_to_type(types: impl Iterator<Item = Type>) -> Type {
let mut types: Punctuated<_, _> = types.collect();
if types.len() == 1 {
types.pop().expect("len is 1").into_value()
} else {
TypeTuple {
paren_token: Default::default(),
elems: types,
}
.into()
}
}
fn add_ref(mutable: bool, ty: Type) -> Type {
Type::Reference(TypeReference {
and_token: Default::default(),
lifetime: None,
mutability: if mutable {
Some(Default::default())
} else {
None
},
elem: Box::new(ty),
})
}
trait ItemImplExt {
fn with_generics(self, generics: Generics) -> Self;
}
impl ItemImplExt for ItemImpl {
fn with_generics(mut self, mut generics: Generics) -> Self {
let need_new_punct = !generics.params.empty_or_trailing();
if need_new_punct {
generics
.params
.push_punct(syn::token::Comma(Span::call_site()));
}
if let Some(t) = generics.lt_token {
self.generics.lt_token = Some(t)
}
if let Some(t) = generics.gt_token {
self.generics.gt_token = Some(t)
}
let ty = self.self_ty;
let mut item: ItemImpl = {
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let item = if let Some((ref polarity, ref path, ref for_token)) = self.trait_ {
quote! {
impl #impl_generics #polarity #path #for_token #ty #ty_generics #where_clause {}
}
} else {
quote! {
impl #impl_generics #ty #ty_generics #where_clause {}
}
};
parse(item.dump().into())
.unwrap_or_else(|err| panic!("with_generics failed: {}\n{}", err, item.dump()))
};
item.generics
.params
.extend(self.generics.params.into_pairs());
match self.generics.where_clause {
Some(WhereClause {
ref mut predicates, ..
}) => predicates.extend(
generics
.where_clause
.into_iter()
.flat_map(|wc| wc.predicates.into_pairs()),
),
ref mut opt @ None => *opt = generics.where_clause,
}
ItemImpl {
attrs: self.attrs,
defaultness: self.defaultness,
unsafety: self.unsafety,
impl_token: self.impl_token,
brace_token: self.brace_token,
items: self.items,
..item
}
}
}