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
extern crate proc_macro;
use proc_macro::{TokenStream, TokenTree, Delimiter, Span};
use syn::{Generics, GenericParam};
use std::cmp::Ordering;
use quote::ToTokens;
#[proc_macro]
#[allow(unreachable_code)]
pub fn impl_trait(item: TokenStream) -> TokenStream {
let mut output: Vec<_> = item.into_iter().collect();
let attributes: Vec<TokenTree> = {
let mut pos = 0;
let mut len = 0;
let mut in_attr = false;
while pos != output.len() {
let tt = &output[pos];
pos += 1;
match tt {
&TokenTree::Punct(ref punct) => {
if punct.as_char() == '#' && !in_attr {
in_attr = true;
continue;
}
}
&TokenTree::Group(ref group) => {
if group.delimiter() == Delimiter::Bracket && in_attr {
in_attr = false;
len = pos;
continue;
}
}
_ => {}
}
break;
}
output.drain(0..len).collect()
};
'check_impl: loop { break {
if let &TokenTree::Ident(ref ident) = &output[0] {
if format!("{}", ident) == "impl" {
break 'check_impl;
}
}
panic!("impl_trait! may only be applied to inherent impls");
} }
let mut has_where: Option<&TokenTree> = None;
'check_no_for_before_where: loop { break {
for tt in &output {
if let &TokenTree::Ident(ref ident) = tt {
let formatted = format!("{}", ident);
if formatted == "where" {
has_where = Some(tt);
break 'check_no_for_before_where;
} else if formatted == "for" {
panic!("impl_trait! may only be applied to inherent impls");
}
}
}
} }
let mut where_bounds = Vec::new();
if let Some(where_in) = has_where {
where_bounds = output.split_last().unwrap().1.into_iter().skip_while(|&tt| {
!std::ptr::eq(tt, where_in)
}).cloned().collect();
}
let where_bounds = where_bounds;
drop(has_where);
let mut count = 0;
let generics = output.split_first().unwrap().1.into_iter().take_while(|&tt| {
let mut result = count > 0;
if let &TokenTree::Punct(ref punct) = tt {
let c = punct.as_char();
if c == '<' {
count += 1;
result = true;
} else if c == '>' {
count -= 1;
}
}
result
}).cloned().collect::<Vec<_>>();
let target_start = 1 + generics.len();
let target_end = output.len() - 1 - where_bounds.len();
let target_range = target_start..target_end;
let target = (&output[target_range]).into_iter().cloned().collect::<Vec<_>>();
let items = output.last_mut();
if let &mut TokenTree::Group(ref mut group) = items.unwrap() {
let span = group.span();
let mut items = group.stream().into_iter().collect::<Vec<_>>();
let mut in_unsafe = false;
let mut in_impl = false;
let mut in_path = false;
let mut in_generic = false;
let mut in_attr = false;
let mut in_attr_cont = false;
let mut has_injected_generics = false;
let mut in_where = false;
let mut start = 0;
let mut found: Vec<Vec<TokenTree>> = Vec::new();
let mut to_remove: Vec<std::ops::Range<usize>> = Vec::new();
let mut generics_scratchpad = Vec::new();
let mut count = 0;
let mut trait_span: Option<Span> = None;
'main_loop: for (pos, tt) in (&items).into_iter().enumerate() {
if in_generic {
let mut result = count > 0;
if let &TokenTree::Punct(ref punct) = tt {
let c = punct.as_char();
if c == '<' {
count += 1;
result = true;
} else if c == '>' {
count -= 1;
if count == 0 {
in_generic = false;
in_path = true;
}
}
}
if result {
generics_scratchpad.push(tt.clone());
continue;
}
}
if in_path {
if !has_injected_generics {
has_injected_generics = true;
if generics_scratchpad.is_empty() {
found.last_mut().unwrap().extend(generics.clone());
} else if generics.is_empty() {
found.last_mut().unwrap().extend(generics_scratchpad.clone());
} else {
let mut this_generics: Generics = syn::parse(generics_scratchpad.drain(..).collect()).unwrap();
let parent_generics: Generics = syn::parse(generics.clone().into_iter().collect()).unwrap();
let mut target = parent_generics.params.into_pairs().chain(this_generics.params.clone().into_pairs()).collect::<Vec<_>>();
target.sort_by(|a, b| {
match (a.value(), b.value()) {
(&GenericParam::Lifetime(_), &GenericParam::Const(_)) => Ordering::Less,
(&GenericParam::Type(_), &GenericParam::Const(_)) => Ordering::Less,
(&GenericParam::Lifetime(_), &GenericParam::Type(_)) => Ordering::Less,
(&GenericParam::Lifetime(_), &GenericParam::Lifetime(_)) => Ordering::Equal,
(&GenericParam::Type(_), &GenericParam::Type(_)) => Ordering::Equal,
(&GenericParam::Const(_), &GenericParam::Const(_)) => Ordering::Equal,
(&GenericParam::Type(_), &GenericParam::Lifetime(_)) => Ordering::Greater,
(&GenericParam::Const(_), &GenericParam::Type(_)) => Ordering::Greater,
(&GenericParam::Const(_), &GenericParam::Lifetime(_)) => Ordering::Greater,
}
});
for item in &mut target {
if matches!(item, syn::punctuated::Pair::End(_)) {
let value = item.value().clone();
*item = syn::punctuated::Pair::Punctuated(value, syn::token::Comma { spans: [trait_span.unwrap().into()] });
break;
}
}
this_generics.params = target.into_iter().collect();
let new_generics = TokenStream::from(this_generics.into_token_stream());
found.last_mut().unwrap().extend(new_generics);
}
}
in_generic = false;
if let &TokenTree::Ident(ref ident) = tt {
let formatted = format!("{}", ident);
if count == 0 && formatted == "where" {
in_path = false;
in_where = true;
found.last_mut().unwrap().push(proc_macro::Ident::new("for", trait_span.unwrap()).into());
found.last_mut().unwrap().extend(target.clone());
found.last_mut().unwrap().push(tt.clone());
if !where_bounds.is_empty() {
found.last_mut().unwrap().extend((&where_bounds).into_iter().skip(1).cloned());
if let Some(&TokenTree::Punct(ref x)) = where_bounds.last() {
if x.as_char() == ',' {
continue 'main_loop;
}
}
found.last_mut().unwrap().push(proc_macro::Punct::new(',', proc_macro::Spacing::Alone).into());
}
continue 'main_loop;
}
}
if let &TokenTree::Punct(ref punct) = tt {
let c = punct.as_char();
if c == '<' {
count += 1;
} else if c == '>' {
if count == 0 {
in_path = false;
continue 'main_loop;
}
count -= 1;
}
}
if let &TokenTree::Group(ref group) = tt {
if group.delimiter() == Delimiter::Brace && count == 0 {
to_remove.push(start..pos+1);
found.last_mut().unwrap().push(proc_macro::Ident::new("for", tt.span()).into());
found.last_mut().unwrap().extend(target.clone());
found.last_mut().unwrap().extend(where_bounds.clone());
in_path = false;
in_where = false;
}
}
found.last_mut().unwrap().push(tt.clone());
continue 'main_loop;
}
if in_where {
if let &TokenTree::Punct(ref punct) = tt {
let c = punct.as_char();
if c == '<' {
count += 1;
} else if c == '>' {
if count == 0 {
in_where = false;
continue 'main_loop;
}
count -= 1;
}
}
if let &TokenTree::Group(ref group) = tt {
if group.delimiter() == Delimiter::Brace && count == 0 {
to_remove.push(start..pos+1);
in_where = false;
}
}
found.last_mut().unwrap().push(tt.clone());
continue 'main_loop;
}
if found.len() == to_remove.len() {
found.push(Vec::new());
in_unsafe = false;
in_impl = false;
in_where = false;
in_path = false;
in_attr_cont = false;
in_generic = false;
has_injected_generics = false;
count = 0;
}
match tt {
&TokenTree::Ident(ref ident) => {
let formatted = format!("{}", ident);
if formatted == "unsafe" && !in_impl {
found.last_mut().unwrap().push(tt.clone());
if !in_attr_cont {
start = pos;
}
in_attr = false;
in_unsafe = true;
continue;
} else if formatted == "impl" && !in_impl {
if !in_attr_cont && !in_unsafe {
start = pos;
}
found.last_mut().unwrap().push(tt.clone());
in_unsafe = false;
in_attr = false;
in_impl = true;
continue;
} else if formatted == "trait" && in_impl {
trait_span = Some(tt.span());
in_generic = true;
in_path = true;
in_impl = false;
has_injected_generics = false;
continue;
}
},
&TokenTree::Punct(ref punct) => {
if punct.as_char() == '#' && !in_attr {
found.last_mut().unwrap().push(tt.clone());
if !in_attr_cont {
start = pos;
}
in_attr = true;
continue;
}
}
&TokenTree::Group(ref group) => {
if group.delimiter() == Delimiter::Bracket && in_attr {
found.last_mut().unwrap().push(tt.clone());
in_attr = false;
in_attr_cont = true;
continue;
}
}
_ => {}
}
found.truncate(to_remove.len());
in_unsafe = false;
in_impl = false;
in_where = false;
in_path = false;
in_attr_cont = false;
in_generic = false;
has_injected_generics = false;
count = 0;
}
for range in to_remove.into_iter().rev() {
items.drain(range);
}
*group = proc_macro::Group::new(group.delimiter(), items.into_iter().collect());
group.set_span(span);
output.extend(found.into_iter().flatten());
}
drop(generics);
drop(target);
drop(where_bounds);
attributes.into_iter().chain(output.into_iter()).collect()
}