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
//! Helpers for generating `impl` blocks.
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, format_ident, quote};
use syn::{
ConstParam, GenericArgument, GenericParam, Ident, Lifetime,
LifetimeParam, Token, TypeParam, TypeParamBound, WhereClause,
WherePredicate, punctuated::Punctuated, visit::Visit,
};
//----------- ImplSkeleton ---------------------------------------------------
/// The skeleton of an `impl` block.
pub struct ImplSkeleton {
/// Lifetime parameters for the `impl` block.
pub lifetimes: Vec<LifetimeParam>,
/// Type parameters for the `impl` block.
pub types: Vec<TypeParam>,
/// Const generic parameters for the `impl` block.
pub consts: Vec<ConstParam>,
/// Whether the `impl` is unsafe.
pub unsafety: Option<Token![unsafe]>,
/// The trait being implemented.
pub bound: Option<syn::Path>,
/// The type being implemented on.
pub subject: syn::Path,
/// The where clause of the `impl` block.
pub where_clause: WhereClause,
/// The contents of the `impl`.
pub contents: syn::Block,
/// A `const` block for asserting requirements.
pub requirements: syn::Block,
}
impl ImplSkeleton {
/// Construct an [`ImplSkeleton`] for a [`DeriveInput`].
pub fn new(input: &syn::DeriveInput, unsafety: bool) -> Self {
let mut lifetimes = Vec::new();
let mut types = Vec::new();
let mut consts = Vec::new();
let mut subject_args = Punctuated::new();
for param in &input.generics.params {
match param {
GenericParam::Lifetime(value) => {
lifetimes.push(value.clone());
let id = value.lifetime.clone();
subject_args.push(GenericArgument::Lifetime(id));
}
GenericParam::Type(value) => {
types.push(TypeParam {
// Defaults are not allowed in 'impl' blocks.
eq_token: None,
default: None,
..value.clone()
});
let id = value.ident.clone();
let id = syn::TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: [syn::PathSegment {
ident: id,
arguments: syn::PathArguments::None,
}]
.into_iter()
.collect(),
},
};
subject_args.push(GenericArgument::Type(id.into()));
}
GenericParam::Const(value) => {
consts.push(value.clone());
let id = value.ident.clone();
let id = syn::TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: [syn::PathSegment {
ident: id,
arguments: syn::PathArguments::None,
}]
.into_iter()
.collect(),
},
};
subject_args.push(GenericArgument::Type(id.into()));
}
}
}
let unsafety = unsafety.then_some(<Token![unsafe]>::default());
let subject = syn::Path {
leading_colon: None,
segments: [syn::PathSegment {
ident: input.ident.clone(),
arguments: syn::PathArguments::AngleBracketed(
syn::AngleBracketedGenericArguments {
colon2_token: None,
lt_token: Default::default(),
args: subject_args,
gt_token: Default::default(),
},
),
}]
.into_iter()
.collect(),
};
let where_clause =
input.generics.where_clause.clone().unwrap_or(WhereClause {
where_token: Default::default(),
predicates: Punctuated::new(),
});
let contents = syn::Block {
brace_token: Default::default(),
stmts: Vec::new(),
};
let requirements = syn::Block {
brace_token: Default::default(),
stmts: Vec::new(),
};
Self {
lifetimes,
types,
consts,
unsafety,
bound: None,
subject,
where_clause,
contents,
requirements,
}
}
/// Require a bound for a type.
///
/// If the type is concrete, a verifying statement is added for it.
/// Otherwise, it is added to the where clause.
pub fn require_bound(
&mut self,
target: syn::Type,
bound: TypeParamBound,
) {
let mut visitor = ConcretenessVisitor {
skeleton: self,
is_concrete: true,
};
// Concreteness applies to both the type and the bound.
visitor.visit_type(&target);
visitor.visit_type_param_bound(&bound);
if visitor.is_concrete {
// Add a concrete requirement for this bound.
self.requirements.stmts.push(syn::parse_quote! {
const _: fn() = || {
fn assert_impl<T: ?Sized + #bound>() {}
assert_impl::<#target>();
};
});
} else {
// Add this bound to the `where` clause.
let mut bounds = Punctuated::new();
bounds.push(bound);
let pred = WherePredicate::Type(syn::PredicateType {
lifetimes: None,
bounded_ty: target,
colon_token: Default::default(),
bounds,
});
self.where_clause.predicates.push(pred);
}
}
/// Generate a unique lifetime with the given prefix.
pub fn new_lifetime(&self, prefix: &str) -> Lifetime {
[format_ident!("{}", prefix)]
.into_iter()
.chain((0u32..).map(|i| format_ident!("{}_{}", prefix, i)))
.find(|id| self.lifetimes.iter().all(|l| l.lifetime.ident != *id))
.map(|ident| Lifetime {
apostrophe: Span::call_site(),
ident,
})
.unwrap()
}
/// Generate a unique lifetime parameter with the given prefix and bounds.
pub fn new_lifetime_param(
&self,
prefix: &str,
bounds: impl IntoIterator<Item = Lifetime>,
) -> (Lifetime, LifetimeParam) {
let lifetime = self.new_lifetime(prefix);
let mut bounds = bounds.into_iter().peekable();
let param = if bounds.peek().is_some() {
syn::parse_quote! { #lifetime: #(#bounds)+* }
} else {
syn::parse_quote! { #lifetime }
};
(lifetime, param)
}
}
impl ToTokens for ImplSkeleton {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self {
lifetimes,
types,
consts,
unsafety,
bound,
subject,
where_clause,
contents,
requirements,
} = self;
let target = match bound {
Some(bound) => quote!(#bound for #subject),
None => quote!(#subject),
};
quote! {
#unsafety
impl<#(#lifetimes,)* #(#types,)* #(#consts,)*>
#target
#where_clause
#contents
}
.to_tokens(tokens);
if !requirements.stmts.is_empty() {
quote! {
const _: () = #requirements;
}
.to_tokens(tokens);
}
}
}
//----------- ConcretenessVisitor --------------------------------------------
struct ConcretenessVisitor<'a> {
/// The `impl` skeleton being added to.
skeleton: &'a ImplSkeleton,
/// Whether the visited type is concrete.
is_concrete: bool,
}
impl<'ast> Visit<'ast> for ConcretenessVisitor<'_> {
fn visit_lifetime(&mut self, i: &'ast Lifetime) {
self.is_concrete = self.is_concrete
&& self.skeleton.lifetimes.iter().all(|l| l.lifetime != *i);
}
fn visit_ident(&mut self, i: &'ast Ident) {
self.is_concrete = self.is_concrete
&& self.skeleton.types.iter().all(|t| t.ident != *i);
self.is_concrete = self.is_concrete
&& self.skeleton.consts.iter().all(|c| c.ident != *i);
}
}