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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
|
// SPDX-License-Identifier: Apache-2.0 OR MIT
use std::collections::{BTreeMap, BTreeSet};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, ToTokens};
use syn::{
parse_quote, visit::Visit, visit_mut::VisitMut, Attribute, BoundLifetimes, GenericParam,
Generics, Index, Lifetime, Member, Token, Type, TypePath,
};
use crate::DiagCtxt;
pub(crate) trait AttrListExt {
fn extract_cfg_attrs(&mut self) -> Vec<TokenStream>;
/// Extract attribute with identifier `path`.
///
/// Report error if the attribute appears multiple times.
fn extract_single_attr(&mut self, dcx: &DiagCtxt, path: &str) -> Option<Attribute>;
}
impl AttrListExt for Vec<Attribute> {
fn extract_cfg_attrs(&mut self) -> Vec<TokenStream> {
let cfg: Vec<_> = self
.iter()
.filter(|a| a.path().is_ident("cfg"))
.map(|a| {
a.parse_args::<TokenStream>()
.expect("parse as token stream cannot fail")
})
.collect();
if !cfg.is_empty() {
self.retain(|a| !a.path().is_ident("cfg"));
}
cfg
}
fn extract_single_attr(&mut self, dcx: &DiagCtxt, path: &str) -> Option<Attribute> {
// FIXME: Replace with `extract_if` when MSRV >= 1.85.
let attr_pos = self.iter().position(|attr| attr.path().is_ident(path))?;
let attr = self.remove(attr_pos);
self.retain(|attr| {
if !attr.path().is_ident(path) {
return true;
}
dcx.error(
attr,
format!("`#[{path}]` attribute specified more than once"),
);
false
});
Some(attr)
}
}
pub(crate) trait MemberExt {
/// Returns an identifier for the member.
///
/// Tuple fields have no name of their own, so they are named `_0`, `_1`, ... instead.
fn as_ident(&self) -> Ident;
/// Obtain a display name for the member in diagnostics.
fn display_name(&self) -> String;
}
impl MemberExt for Member {
fn as_ident(&self) -> Ident {
match self {
Member::Named(ident) => ident.clone(),
Member::Unnamed(Index { index, span }) => format_ident!("_{index}", span = *span),
}
}
fn display_name(&self) -> String {
match self {
Member::Named(ident) => format!("`{ident}`"),
Member::Unnamed(Index { index, .. }) => format!("index `{index}`"),
}
}
}
pub(crate) struct CombinedGenerics<'a>(pub(crate) Vec<&'a Generics>);
pub(crate) struct CombinedImplGenerics<'a>(&'a CombinedGenerics<'a>);
pub(crate) struct CombinedTypeGenerics<'a>(&'a CombinedGenerics<'a>);
pub(crate) struct CombinedWhereClauses<'a>(&'a CombinedGenerics<'a>);
impl CombinedGenerics<'_> {
pub(crate) fn split_for_impl(
&self,
) -> (
CombinedImplGenerics<'_>,
CombinedTypeGenerics<'_>,
CombinedWhereClauses<'_>,
) {
(
CombinedImplGenerics(self),
CombinedTypeGenerics(self),
CombinedWhereClauses(self),
)
}
}
impl ToTokens for CombinedGenerics<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) {
// Most of the time we are only adding lifetimes, so we prefer to place
// the user provided generics last.
self.0
.last()
.and_then(|x| x.lt_token)
.unwrap_or_default()
.to_tokens(tokens);
let comma: Token![,] = Default::default();
// Output lifetimes first.
for generics in self.0.iter() {
for param in generics.params.pairs() {
if let GenericParam::Lifetime(lt) = param.value() {
lt.to_tokens(tokens);
param.punct().unwrap_or(&&comma).to_tokens(tokens);
}
}
}
for generics in self.0.iter() {
for param in generics.params.pairs() {
if let GenericParam::Lifetime(_) = param.value() {
continue;
};
param.value().to_tokens(tokens);
param.punct().unwrap_or(&&comma).to_tokens(tokens);
}
}
self.0
.last()
.and_then(|x| x.gt_token)
.unwrap_or_default()
.to_tokens(tokens);
}
}
impl ToTokens for CombinedImplGenerics<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.0
.0
.last()
.and_then(|x| x.lt_token)
.unwrap_or_default()
.to_tokens(tokens);
let comma: Token![,] = Default::default();
// Output lifetimes first.
for generics in self.0 .0.iter() {
for param in generics.params.pairs() {
if let GenericParam::Lifetime(lt) = param.value() {
lt.to_tokens(tokens);
param.punct().unwrap_or(&&comma).to_tokens(tokens);
}
}
}
for generics in self.0 .0.iter() {
for param in generics.params.pairs() {
// Leave out defaults.
match param.value() {
GenericParam::Lifetime(_) => continue,
GenericParam::Type(param) => {
param.ident.to_tokens(tokens);
if !param.bounds.is_empty() {
param
.colon_token
.unwrap_or_else(Default::default)
.to_tokens(tokens);
param.bounds.to_tokens(tokens);
}
}
GenericParam::Const(param) => {
param.const_token.to_tokens(tokens);
param.ident.to_tokens(tokens);
param.colon_token.to_tokens(tokens);
param.ty.to_tokens(tokens);
}
}
param.punct().unwrap_or(&&comma).to_tokens(tokens);
}
}
self.0
.0
.last()
.and_then(|x| x.gt_token)
.unwrap_or_default()
.to_tokens(tokens);
}
}
impl ToTokens for CombinedTypeGenerics<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.0
.0
.last()
.and_then(|x| x.lt_token)
.unwrap_or_default()
.to_tokens(tokens);
let comma: Token![,] = Default::default();
// Output lifetimes first.
for generics in self.0 .0.iter() {
for param in generics.params.pairs() {
if let GenericParam::Lifetime(lt) = param.value() {
// Leave out bounds
lt.lifetime.to_tokens(tokens);
param.punct().unwrap_or(&&comma).to_tokens(tokens);
}
}
}
for generics in self.0 .0.iter() {
for param in generics.params.pairs() {
// Leave out bounds and defaults.
match param.value() {
GenericParam::Lifetime(_) => continue,
GenericParam::Type(param) => {
param.ident.to_tokens(tokens);
}
GenericParam::Const(param) => {
param.ident.to_tokens(tokens);
}
}
param.punct().unwrap_or(&&comma).to_tokens(tokens);
}
}
self.0
.0
.last()
.and_then(|x| x.gt_token)
.unwrap_or_default()
.to_tokens(tokens);
}
}
impl ToTokens for CombinedWhereClauses<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.0
.0
.iter()
.filter_map(|x| Some(x.where_clause.as_ref()?.where_token))
.next_back()
.unwrap_or_default()
.to_tokens(tokens);
let comma: Token![,] = Default::default();
for generics in self.0 .0.iter() {
let Some(where_clause) = &generics.where_clause else {
continue;
};
where_clause.predicates.to_tokens(tokens);
if !where_clause.predicates.empty_or_trailing() {
comma.to_tokens(tokens);
}
}
}
}
pub(crate) trait LifetimeExt {
/// Get a visitor that call the provided function for all unbound lifetimes.
fn visitor<'a>(f: impl FnMut(&'a Lifetime)) -> impl Visit<'a>;
/// Obtain a lifetime from a identifier.
///
/// The created lifetime has the same span.
fn from_ident(ident: &Ident) -> Self;
}
impl LifetimeExt for Lifetime {
fn visitor<'a>(f: impl FnMut(&'a Lifetime)) -> impl Visit<'a> {
LifetimeVisitor {
bound: BTreeSet::new(),
visit: f,
}
}
fn from_ident(ident: &Ident) -> Self {
Lifetime {
apostrophe: ident.span(),
ident: ident.clone(),
}
}
}
struct LifetimeVisitor<'a, F> {
bound: BTreeSet<&'a Lifetime>,
visit: F,
}
impl<'a, F> LifetimeVisitor<'a, F> {
fn with_bound_lifetimes(
&mut self,
bound: Option<&'a BoundLifetimes>,
f: impl FnOnce(&mut Self),
) {
// In case the type includes a lifetime binder, e.g. `dyn for<'a> Foo`,
// the lifetimes in the binder are bound and should not be visited.
let mut to_remove = Vec::new();
if let Some(bound) = bound {
for lt in &bound.lifetimes {
let GenericParam::Lifetime(lt) = lt else {
continue;
};
if !self.bound.contains(&<.lifetime) {
self.bound.insert(<.lifetime);
to_remove.push(<.lifetime);
}
}
}
f(self);
for lt in to_remove {
self.bound.remove(lt);
}
}
}
impl<'a, F: FnMut(&'a Lifetime)> Visit<'a> for LifetimeVisitor<'a, F> {
fn visit_lifetime(&mut self, lt: &'a Lifetime) {
if lt.ident == "static" {
return;
}
if !self.bound.contains(lt) {
(self.visit)(lt);
}
}
fn visit_trait_bound(&mut self, bound: &'a syn::TraitBound) {
self.with_bound_lifetimes(bound.lifetimes.as_ref(), |this| {
this.visit_path(&bound.path)
});
}
fn visit_type_bare_fn(&mut self, bare_fn: &'a syn::TypeBareFn) {
self.with_bound_lifetimes(bare_fn.lifetimes.as_ref(), |this| {
for input in bare_fn.inputs.iter() {
this.visit_bare_fn_arg(input);
}
this.visit_return_type(&bare_fn.output);
});
}
}
pub(crate) trait GenericParamExt {
fn maybe_type_params_visitor<'a>(f: impl FnMut(&'a Ident)) -> impl Visit<'a>;
}
impl GenericParamExt for GenericParam {
fn maybe_type_params_visitor<'a>(f: impl FnMut(&'a Ident)) -> impl Visit<'a> {
struct TypeParamVisitor<F>(F);
impl<'a, F> Visit<'a> for TypeParamVisitor<F>
where
F: FnMut(&'a Ident),
{
fn visit_type_path(&mut self, ty: &'a TypePath) {
if ty.qself.is_none()
&& ty.path.leading_colon.is_none()
&& ty.path.segments[0].arguments.is_none()
{
(self.0)(&ty.path.segments[0].ident);
}
syn::visit::visit_type_path(self, ty);
}
}
TypeParamVisitor(f)
}
}
pub(crate) trait TypeExt {
/// Check if the type includes macro invocations.
///
/// Proc-macros cannot expand macros and peek into them, so if macro is involved sometimes
/// special handling is required.
fn has_macro(&self) -> bool;
fn replace_lifetimes(&self, needle: &[&Lifetime], replacement: &[&Lifetime]) -> Type;
}
impl TypeExt for Type {
fn has_macro(&self) -> bool {
struct HasMacro(bool);
impl<'ast> Visit<'ast> for HasMacro {
fn visit_macro(&mut self, _: &'ast syn::Macro) {
self.0 = true;
}
}
let mut visitor = HasMacro(false);
visitor.visit_type(self);
visitor.0
}
fn replace_lifetimes(&self, needle: &[&Lifetime], replacement: &[&Lifetime]) -> Type {
if needle.is_empty() {
return self.clone();
}
// If the type has macro, we cannot peek into it. Use some different approach to replace
// the type using GAT.
if self.has_macro() {
return parse_quote!(
<
for<#(#needle,)*> fn(#(&#needle (),)*) -> #self
as
::pin_init::__internal::FnOutput<(#(&#replacement (),)*)>
>::Output
);
}
struct LifetimeReplacer<'a> {
to_replace: BTreeMap<&'a Lifetime, &'a Lifetime>,
}
impl<'a> LifetimeReplacer<'a> {
fn with_bound_lifetimes(
&mut self,
bound: Option<&BoundLifetimes>,
f: impl FnOnce(&mut Self),
) {
// In case the type includes a lifetime binder, e.g. `dyn for<'a> Foo`,
// temporarily remove them from to_replace if they're.
let mut removed = Vec::new();
if let Some(bound) = bound {
for lt in &bound.lifetimes {
let GenericParam::Lifetime(lt) = lt else {
continue;
};
if let Some(entry) = self.to_replace.remove_entry(<.lifetime) {
removed.push(entry);
}
}
}
f(self);
for (key, val) in removed {
self.to_replace.insert(key, val);
}
}
}
impl VisitMut for LifetimeReplacer<'_> {
fn visit_lifetime_mut(&mut self, lt: &mut syn::Lifetime) {
if let Some(&replacement) = self.to_replace.get(lt) {
*lt = replacement.clone();
}
}
fn visit_trait_bound_mut(&mut self, bound: &mut syn::TraitBound) {
self.with_bound_lifetimes(bound.lifetimes.as_ref(), |this| {
this.visit_path_mut(&mut bound.path)
});
}
fn visit_type_bare_fn_mut(&mut self, bare_fn: &mut syn::TypeBareFn) {
self.with_bound_lifetimes(bare_fn.lifetimes.as_ref(), |this| {
for input in bare_fn.inputs.iter_mut() {
this.visit_bare_fn_arg_mut(input);
}
this.visit_return_type_mut(&mut bare_fn.output);
});
}
}
let mut ret = self.clone();
LifetimeReplacer {
to_replace: needle
.iter()
.copied()
.zip(replacement.iter().copied())
.collect(),
}
.visit_type_mut(&mut ret);
ret
}
}
|