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
|
// SPDX-License-Identifier: Apache-2.0 OR MIT
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{
parse::{End, Nothing, Parse},
parse_quote, parse_quote_spanned,
spanned::Spanned,
visit_mut::VisitMut,
Attribute, Field, Generics, Ident, Item, PathSegment, Type, TypePath, Visibility, WhereClause,
};
use crate::diagnostics::{DiagCtxt, ErrorGuaranteed};
pub(crate) mod kw {
syn::custom_keyword!(PinnedDrop);
}
pub(crate) enum Args {
Nothing(Nothing),
#[allow(dead_code)]
PinnedDrop(kw::PinnedDrop),
}
impl Parse for Args {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lh = input.lookahead1();
if lh.peek(End) {
input.parse().map(Self::Nothing)
} else if lh.peek(kw::PinnedDrop) {
input.parse().map(Self::PinnedDrop)
} else {
Err(lh.error())
}
}
}
struct FieldInfo<'a> {
field: &'a Field,
pinned: bool,
cfg_attrs: Vec<&'a Attribute>,
}
pub(crate) fn pin_data(
args: Args,
input: Item,
dcx: &mut DiagCtxt,
) -> Result<TokenStream, ErrorGuaranteed> {
let mut struct_ = match input {
Item::Struct(struct_) => struct_,
Item::Enum(enum_) => {
return Err(dcx.error(
enum_.enum_token,
"`#[pin_data]` only supports structs for now",
));
}
Item::Union(union) => {
return Err(dcx.error(
union.union_token,
"`#[pin_data]` only supports structs for now",
));
}
rest => {
return Err(dcx.error(
rest,
"`#[pin_data]` can only be applied to struct, enum and union definitions",
));
}
};
// The generics might contain the `Self` type. Since this macro will define a new type with the
// same generics and bounds, this poses a problem: `Self` will refer to the new type as opposed
// to this struct definition. Therefore we have to replace `Self` with the concrete name.
let mut replacer = {
let name = &struct_.ident;
let (_, ty_generics, _) = struct_.generics.split_for_impl();
SelfReplacer(parse_quote!(#name #ty_generics))
};
replacer.visit_generics_mut(&mut struct_.generics);
replacer.visit_fields_mut(&mut struct_.fields);
let fields: Vec<FieldInfo<'_>> = struct_
.fields
.iter_mut()
.map(|field| {
let len = field.attrs.len();
field.attrs.retain(|a| !a.path().is_ident("pin"));
let pinned = len != field.attrs.len();
let cfg_attrs = field
.attrs
.iter()
.filter(|a| a.path().is_ident("cfg"))
.collect();
FieldInfo {
field: &*field,
pinned,
cfg_attrs,
}
})
.collect();
for field in &fields {
let ident = field.field.ident.as_ref().unwrap();
if !field.pinned && is_phantom_pinned(&field.field.ty) {
dcx.warn(
field.field,
format!(
"The field `{ident}` of type `PhantomPinned` only has an effect \
if it has the `#[pin]` attribute",
),
);
}
}
let unpin_impl = generate_unpin_impl(&struct_.ident, &struct_.generics, &fields);
let drop_impl = generate_drop_impl(&struct_.ident, &struct_.generics, args);
let projections =
generate_projections(&struct_.vis, &struct_.ident, &struct_.generics, &fields);
let the_pin_data =
generate_the_pin_data(&struct_.vis, &struct_.ident, &struct_.generics, &fields);
Ok(quote! {
#struct_
#projections
// We put the rest into this const item, because it then will not be accessible to anything
// outside.
const _: () = {
#the_pin_data
#unpin_impl
#drop_impl
};
})
}
fn is_phantom_pinned(ty: &Type) -> bool {
match ty {
Type::Path(TypePath { qself: None, path }) => {
// Cannot possibly refer to `PhantomPinned` (except alias, but that's on the user).
if path.segments.len() > 3 {
return false;
}
// If there is a `::`, then the path needs to be `::core::marker::PhantomPinned` or
// `::std::marker::PhantomPinned`.
if path.leading_colon.is_some() && path.segments.len() != 3 {
return false;
}
let expected: Vec<&[&str]> = vec![&["PhantomPinned"], &["marker"], &["core", "std"]];
for (actual, expected) in path.segments.iter().rev().zip(expected) {
if !actual.arguments.is_empty() || expected.iter().all(|e| actual.ident != e) {
return false;
}
}
true
}
_ => false,
}
}
fn generate_unpin_impl(
ident: &Ident,
generics: &Generics,
fields: &[FieldInfo<'_>],
) -> TokenStream {
let (_, ty_generics, _) = generics.split_for_impl();
let mut generics_with_pin_lt = generics.clone();
generics_with_pin_lt.params.insert(0, parse_quote!('__pin));
generics_with_pin_lt.make_where_clause();
let (
impl_generics_with_pin_lt,
ty_generics_with_pin_lt,
Some(WhereClause {
where_token,
predicates,
}),
) = generics_with_pin_lt.split_for_impl()
else {
unreachable!()
};
let pinned_fields = fields.iter().filter(|f| f.pinned).map(|f| {
let ident = f.field.ident.as_ref().unwrap();
let ty = &f.field.ty;
let cfg_attrs = &f.cfg_attrs;
quote!(
#(#cfg_attrs)*
#ident: #ty
)
});
quote! {
// This struct will be used for the unpin analysis. It is needed, because only structurally
// pinned fields are relevant whether the struct should implement `Unpin`.
#[allow(
dead_code, // The fields below are never used.
non_snake_case // The warning will be emitted on the struct definition.
)]
struct __Unpin #generics_with_pin_lt
#where_token
#predicates
{
__phantom_pin: ::pin_init::__internal::PhantomInvariantLifetime<'__pin>,
__phantom: ::pin_init::__internal::PhantomInvariant<#ident #ty_generics>,
#(#pinned_fields),*
}
#[doc(hidden)]
impl #impl_generics_with_pin_lt ::core::marker::Unpin for #ident #ty_generics
#where_token
__Unpin #ty_generics_with_pin_lt: ::core::marker::Unpin,
#predicates
{}
}
}
fn generate_drop_impl(ident: &Ident, generics: &Generics, args: Args) -> TokenStream {
let (impl_generics, ty_generics, whr) = generics.split_for_impl();
let has_pinned_drop = matches!(args, Args::PinnedDrop(_));
// We need to disallow normal `Drop` implementation, the exact behavior depends on whether
// `PinnedDrop` was specified in `args`.
if has_pinned_drop {
// When `PinnedDrop` was specified we just implement `Drop` and delegate.
quote! {
impl #impl_generics ::core::ops::Drop for #ident #ty_generics
#whr
{
fn drop(&mut self) {
// SAFETY: Since this is a destructor, `self` will not move after this function
// terminates, since it is inaccessible.
let pinned = unsafe { ::core::pin::Pin::new_unchecked(self) };
// SAFETY: Since this is a drop function, we can create this token to call the
// pinned destructor of this type.
let token = unsafe { ::pin_init::__internal::OnlyCallFromDrop::new() };
::pin_init::PinnedDrop::drop(pinned, token);
}
}
}
} else {
// When no `PinnedDrop` was specified, then we have to prevent implementing drop.
quote! {
// We prevent this by creating a trait that will be implemented for all types implementing
// `Drop`. Additionally we will implement this trait for the struct leading to a conflict,
// if it also implements `Drop`
trait MustNotImplDrop {}
#[expect(drop_bounds)]
impl<T: ::core::ops::Drop + ?::core::marker::Sized> MustNotImplDrop for T {}
impl #impl_generics MustNotImplDrop for #ident #ty_generics
#whr
{}
// We also take care to prevent users from writing a useless `PinnedDrop` implementation.
// They might implement `PinnedDrop` correctly for the struct, but forget to give
// `PinnedDrop` as the parameter to `#[pin_data]`.
#[expect(non_camel_case_types)]
trait UselessPinnedDropImpl_you_need_to_specify_PinnedDrop {}
impl<T: ::pin_init::PinnedDrop + ?::core::marker::Sized>
UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for T {}
impl #impl_generics
UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for #ident #ty_generics
#whr
{}
}
}
}
fn generate_projections(
vis: &Visibility,
ident: &Ident,
generics: &Generics,
fields: &[FieldInfo<'_>],
) -> TokenStream {
let (impl_generics, ty_generics, _) = generics.split_for_impl();
let mut generics_with_pin_lt = generics.clone();
generics_with_pin_lt.params.insert(0, parse_quote!('__pin));
let (_, ty_generics_with_pin_lt, whr) = generics_with_pin_lt.split_for_impl();
let projection = format_ident!("{ident}Projection");
let this = format_ident!("this");
let (fields_decl, fields_proj): (Vec<_>, Vec<_>) = fields
.iter()
.map(|field| {
let Field { vis, ident, ty, .. } = &field.field;
let cfg_attrs = &field.cfg_attrs;
let ident = ident
.as_ref()
.expect("only structs with named fields are supported");
if field.pinned {
(
quote!(
#(#cfg_attrs)*
#vis #ident: ::core::pin::Pin<&'__pin mut #ty>,
),
quote!(
#(#cfg_attrs)*
// SAFETY: this field is structurally pinned.
#ident: unsafe { ::core::pin::Pin::new_unchecked(&mut #this.#ident) },
),
)
} else {
(
quote!(
#(#cfg_attrs)*
#vis #ident: &'__pin mut #ty,
),
quote!(
#(#cfg_attrs)*
#ident: &mut #this.#ident,
),
)
}
})
.collect();
let structurally_pinned_fields_docs = fields
.iter()
.filter(|f| f.pinned)
.map(|f| format!(" - `{}`", f.field.ident.as_ref().unwrap()));
let not_structurally_pinned_fields_docs = fields
.iter()
.filter(|f| !f.pinned)
.map(|f| format!(" - `{}`", f.field.ident.as_ref().unwrap()));
let docs = format!(" Pin-projections of [`{ident}`]");
quote! {
#[doc = #docs]
// Allow `non_snake_case` since the same warning will be emitted on
// the struct definition.
#[allow(dead_code, non_snake_case)]
#[doc(hidden)]
#vis struct #projection #generics_with_pin_lt
#whr
{
#(#fields_decl)*
___pin_phantom_data: ::core::marker::PhantomData<&'__pin mut ()>,
}
impl #impl_generics #ident #ty_generics
#whr
{
/// Pin-projects all fields of `Self`.
///
/// These fields are structurally pinned:
#(#[doc = #structurally_pinned_fields_docs])*
///
/// These fields are **not** structurally pinned:
#(#[doc = #not_structurally_pinned_fields_docs])*
#[inline]
#vis fn project<'__pin>(
self: ::core::pin::Pin<&'__pin mut Self>,
) -> #projection #ty_generics_with_pin_lt {
// SAFETY: we only give access to `&mut` for fields not structurally pinned.
let #this = unsafe { ::core::pin::Pin::get_unchecked_mut(self) };
#projection {
#(#fields_proj)*
___pin_phantom_data: ::core::marker::PhantomData,
}
}
}
}
}
fn generate_the_pin_data(
vis: &Visibility,
struct_name: &Ident,
generics: &Generics,
fields: &[FieldInfo<'_>],
) -> TokenStream {
let (impl_generics, ty_generics, whr) = generics.split_for_impl();
// For every field, we create an initializing projection function according to its projection
// type. If a field is structurally pinned, we create a `Slot` with `Pinned` which must be
// initialized via `PinInit`; if it is not structurally pinned, then we create a `Slot` with
// `Unpinned` which allows initialization via `Init`.
let field_accessors = fields
.iter()
.map(|f| {
let Field { vis, ident, ty, .. } = f.field;
let cfg_attrs = &f.cfg_attrs;
let field_name = ident
.as_ref()
.expect("only structs with named fields are supported");
let pin_marker = if f.pinned {
quote!(Pinned)
} else {
quote!(Unpinned)
};
quote! {
/// # Safety
///
/// - `slot` is valid and properly aligned.
/// - `(*slot).#field_name` is properly aligned.
/// - `(*slot).#field_name` points to uninitialized and exclusively accessed
/// memory.
#(#cfg_attrs)*
// Allow `non_snake_case` since the same warning will be emitted on
// the struct definition.
#[allow(non_snake_case)]
#[inline(always)]
#vis unsafe fn #field_name(
self,
slot: *mut #struct_name #ty_generics,
) -> ::pin_init::__internal::Slot<::pin_init::__internal::#pin_marker, #ty> {
// SAFETY:
// - If `#pin_marker` is `Pinned`, the corresponding field is structurally
// pinned.
// - Other safety requirements follows the safety requirement.
unsafe { ::pin_init::__internal::Slot::new(&raw mut (*slot).#field_name) }
}
}
})
.collect::<TokenStream>();
quote! {
// We declare this struct which will host all of the projection function for our type. It
// will be invariant over all generic parameters which are inherited from the struct.
#[doc(hidden)]
#vis struct __ThePinData #generics
#whr
{
__phantom: ::pin_init::__internal::PhantomInvariant<#struct_name #ty_generics>,
}
impl #impl_generics ::core::clone::Clone for __ThePinData #ty_generics
#whr
{
fn clone(&self) -> Self { *self }
}
impl #impl_generics ::core::marker::Copy for __ThePinData #ty_generics
#whr
{}
#[allow(dead_code)] // Some functions might never be used and private.
#[expect(clippy::missing_safety_doc)]
impl #impl_generics __ThePinData #ty_generics
#whr
{
/// Type inference helper function.
#[inline(always)]
#vis fn __make_closure<__F, __E>(self, f: __F) -> __F
where
__F: FnOnce(*mut #struct_name #ty_generics) ->
::core::result::Result<::pin_init::__internal::InitOk, __E>,
{
f
}
#field_accessors
}
// SAFETY: We have added the correct projection functions above to `__ThePinData` and
// we also use the least restrictive generics possible.
unsafe impl #impl_generics ::pin_init::__internal::HasPinData for #struct_name #ty_generics
#whr
{
type PinData = __ThePinData #ty_generics;
unsafe fn __pin_data() -> Self::PinData {
__ThePinData { __phantom: ::pin_init::__internal::PhantomInvariant::new() }
}
}
}
}
struct SelfReplacer(PathSegment);
impl VisitMut for SelfReplacer {
fn visit_path_mut(&mut self, i: &mut syn::Path) {
if i.is_ident("Self") {
let span = i.span();
let seg = &self.0;
*i = parse_quote_spanned!(span=> #seg);
} else {
syn::visit_mut::visit_path_mut(self, i);
}
}
fn visit_path_segment_mut(&mut self, seg: &mut PathSegment) {
if seg.ident == "Self" {
let span = seg.span();
let this = &self.0;
*seg = parse_quote_spanned!(span=> #this);
} else {
syn::visit_mut::visit_path_segment_mut(self, seg);
}
}
fn visit_item_mut(&mut self, _: &mut Item) {
// Do not descend into items, since items reset/change what `Self` refers to.
}
}
|