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
use std::mem;
use proc_macro2::{Group, TokenStream, TokenTree};
use quote::{format_ident, quote_spanned};
use syn::{
parse::{ParseBuffer, ParseStream},
punctuated::Punctuated,
token::{self, Comma},
visit_mut::{self, VisitMut},
*,
};
pub(crate) const DEFAULT_LIFETIME_NAME: &str = "'pin";
pub(crate) const CURRENT_PRIVATE_MODULE: &str = "__private";
pub(crate) type Variants = Punctuated<Variant, token::Comma>;
pub(crate) use Mutability::{Immutable, Mutable};
macro_rules! error {
($span:expr, $msg:expr) => {
syn::Error::new_spanned(&$span, $msg)
};
($span:expr, $($tt:tt)*) => {
error!($span, format!($($tt)*))
};
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum Mutability {
Mutable,
Immutable,
}
pub(crate) fn proj_ident(ident: &Ident, mutability: Mutability) -> Ident {
if mutability == Mutable {
format_ident!("__{}Projection", ident)
} else {
format_ident!("__{}ProjectionRef", ident)
}
}
pub(crate) fn determine_lifetime_name(
lifetime_name: &mut String,
generics: &Punctuated<GenericParam, Comma>,
) {
let existing_lifetimes: Vec<String> = generics
.iter()
.filter_map(|param| {
if let GenericParam::Lifetime(LifetimeDef { lifetime, .. }) = param {
Some(lifetime.to_string())
} else {
None
}
})
.collect();
while existing_lifetimes.iter().any(|name| name.starts_with(&**lifetime_name)) {
lifetime_name.push('_');
}
}
pub(crate) fn insert_lifetime(generics: &mut Generics, lifetime: Lifetime) {
if generics.lt_token.is_none() {
generics.lt_token = Some(token::Lt::default())
}
if generics.gt_token.is_none() {
generics.gt_token = Some(token::Gt::default())
}
generics.params.insert(
0,
GenericParam::Lifetime(LifetimeDef {
attrs: Vec::new(),
lifetime,
colon_token: None,
bounds: Punctuated::new(),
}),
);
}
pub(crate) fn determine_visibility(vis: &Visibility) -> Visibility {
if let Visibility::Public(token) = vis {
syn::parse2(quote_spanned! { token.pub_token.span =>
pub(crate)
})
.unwrap()
} else {
vis.clone()
}
}
pub(crate) fn parse_as_empty(tokens: &TokenStream) -> Result<()> {
if tokens.is_empty() { Ok(()) } else { Err(error!(tokens, "unexpected token: {}", tokens)) }
}
pub(crate) trait SliceExt {
fn position_exact(&self, ident: &str) -> Result<Option<usize>>;
fn find(&self, ident: &str) -> Option<&Attribute>;
fn find_exact(&self, ident: &str) -> Result<Option<&Attribute>>;
}
pub(crate) trait VecExt {
fn find_remove(&mut self, ident: &str) -> Result<Option<Attribute>>;
}
impl SliceExt for [Attribute] {
fn position_exact(&self, ident: &str) -> Result<Option<usize>> {
self.iter()
.try_fold((0, None), |(i, mut prev), attr| {
if attr.path.is_ident(ident) {
if prev.is_some() {
return Err(error!(attr, "duplicate #[{}] attribute", ident));
}
parse_as_empty(&attr.tokens)?;
prev = Some(i);
}
Ok((i + 1, prev))
})
.map(|(_, pos)| pos)
}
fn find(&self, ident: &str) -> Option<&Attribute> {
self.iter().position(|attr| attr.path.is_ident(ident)).and_then(|i| self.get(i))
}
fn find_exact(&self, ident: &str) -> Result<Option<&Attribute>> {
self.position_exact(ident).map(|pos| pos.and_then(|i| self.get(i)))
}
}
impl VecExt for Vec<Attribute> {
fn find_remove(&mut self, ident: &str) -> Result<Option<Attribute>> {
self.position_exact(ident).map(|pos| pos.map(|i| self.remove(i)))
}
}
pub(crate) trait ParseBufferExt<'a> {
fn parenthesized(self) -> Result<ParseBuffer<'a>>;
}
impl<'a> ParseBufferExt<'a> for ParseStream<'a> {
fn parenthesized(self) -> Result<ParseBuffer<'a>> {
let content;
let _: token::Paren = syn::parenthesized!(content in self);
Ok(content)
}
}
impl<'a> ParseBufferExt<'a> for ParseBuffer<'a> {
fn parenthesized(self) -> Result<ParseBuffer<'a>> {
let content;
let _: token::Paren = syn::parenthesized!(content in self);
Ok(content)
}
}
pub(crate) struct ReplaceReceiver<'a> {
self_ty: &'a Type,
}
impl<'a> ReplaceReceiver<'a> {
pub(crate) fn new(self_ty: &'a Type) -> Self {
Self { self_ty }
}
fn self_to_qself(&mut self, qself: &mut Option<QSelf>, path: &mut Path) {
if path.leading_colon.is_some() {
return;
}
let first = &path.segments[0];
if first.ident != "Self" || !first.arguments.is_empty() {
return;
}
if path.segments.len() == 1 {
self.self_to_expr_path(path);
return;
}
*qself = Some(QSelf {
lt_token: token::Lt::default(),
ty: Box::new(self.self_ty.clone()),
position: 0,
as_token: None,
gt_token: token::Gt::default(),
});
match path.segments.pairs().next().unwrap().punct() {
Some(&&colon) => path.leading_colon = Some(colon),
None => return,
}
let segments = mem::replace(&mut path.segments, Punctuated::new());
path.segments = segments.into_pairs().skip(1).collect();
}
fn self_to_expr_path(&self, path: &mut Path) {
if let Type::Path(self_ty) = &self.self_ty {
*path = self_ty.path.clone();
for segment in &mut path.segments {
if let PathArguments::AngleBracketed(bracketed) = &mut segment.arguments {
if bracketed.colon2_token.is_none() && !bracketed.args.is_empty() {
bracketed.colon2_token = Some(token::Colon2::default());
}
}
}
} else {
let span = path.segments[0].ident.span();
let msg = "Self type of this impl is unsupported in expression position";
let error = Error::new(span, msg).to_compile_error();
*path = parse_quote!(::core::marker::PhantomData::<#error>);
}
}
}
impl VisitMut for ReplaceReceiver<'_> {
fn visit_type_mut(&mut self, ty: &mut Type) {
if let Type::Path(node) = ty {
if node.qself.is_none() && node.path.is_ident("Self") {
*ty = self.self_ty.clone();
} else {
self.visit_type_path_mut(node);
}
} else {
visit_mut::visit_type_mut(self, ty);
}
}
fn visit_type_path_mut(&mut self, ty: &mut TypePath) {
if ty.qself.is_none() {
self.self_to_qself(&mut ty.qself, &mut ty.path);
}
visit_mut::visit_type_path_mut(self, ty);
}
fn visit_expr_path_mut(&mut self, expr: &mut ExprPath) {
if expr.qself.is_none() {
prepend_underscore_to_self(&mut expr.path.segments[0].ident);
self.self_to_qself(&mut expr.qself, &mut expr.path);
}
visit_mut::visit_expr_path_mut(self, expr);
}
fn visit_expr_struct_mut(&mut self, expr: &mut ExprStruct) {
if expr.path.is_ident("Self") {
self.self_to_expr_path(&mut expr.path);
}
visit_mut::visit_expr_struct_mut(self, expr);
}
fn visit_macro_mut(&mut self, node: &mut Macro) {
if !contains_fn(node.tokens.clone()) {
node.tokens = fold_token_stream(node.tokens.clone());
}
}
fn visit_item_mut(&mut self, _: &mut Item) {
}
}
fn contains_fn(tokens: TokenStream) -> bool {
tokens.into_iter().any(|tt| match tt {
TokenTree::Ident(ident) => ident == "fn",
TokenTree::Group(group) => contains_fn(group.stream()),
_ => false,
})
}
fn fold_token_stream(tokens: TokenStream) -> TokenStream {
tokens
.into_iter()
.map(|tt| match tt {
TokenTree::Ident(mut ident) => {
prepend_underscore_to_self(&mut ident);
TokenTree::Ident(ident)
}
TokenTree::Group(group) => {
let content = fold_token_stream(group.stream());
TokenTree::Group(Group::new(group.delimiter(), content))
}
other => other,
})
.collect()
}
pub(crate) fn prepend_underscore_to_self(ident: &mut Ident) {
if ident == "self" {
*ident = Ident::new("__self", ident.span());
}
}