pin_project_internal/
lib.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! Implementation detail of the `pin-project` crate. - **do not use directly**
4
5#![doc(test(
6    no_crate_inject,
7    attr(allow(
8        dead_code,
9        unused_variables,
10        clippy::undocumented_unsafe_blocks,
11        clippy::unused_trait_names,
12    ))
13))]
14#![forbid(unsafe_code)]
15#![allow(clippy::needless_doctest_main)]
16#![allow(clippy::expl_impl_clone_on_copy)] // https://github.com/rust-lang/rust-clippy/issues/15842
17
18#[macro_use]
19mod error;
20
21#[macro_use]
22mod utils;
23
24mod pin_project;
25mod pinned_drop;
26
27use proc_macro::TokenStream;
28
29/// An attribute that creates projection types covering all the fields of
30/// struct or enum.
31///
32/// This attribute creates projection types according to the following rules:
33///
34/// - For the fields that use `#[pin]` attribute, create the pinned reference to
35///   the field.
36/// - For the other fields, create a normal reference to the field.
37///
38/// And the following methods are implemented on the original type:
39///
40/// ```
41/// # use std::pin::Pin;
42/// # type Projection<'a> = &'a ();
43/// # type ProjectionRef<'a> = &'a ();
44/// # trait Dox {
45/// fn project(self: Pin<&mut Self>) -> Projection<'_>;
46/// fn project_ref(self: Pin<&Self>) -> ProjectionRef<'_>;
47/// # }
48/// ```
49///
50/// By passing an argument with the same name as the method to the attribute,
51/// you can name the projection type returned from the method. This allows you
52/// to use pattern matching on the projected types.
53///
54/// ```
55/// # use pin_project::pin_project;
56/// # use std::pin::Pin;
57/// #[pin_project(project = EnumProj)]
58/// enum Enum<T> {
59///     Variant(#[pin] T),
60/// }
61///
62/// impl<T> Enum<T> {
63///     fn method(self: Pin<&mut Self>) {
64///         let this: EnumProj<'_, T> = self.project();
65///         match this {
66///             EnumProj::Variant(x) => {
67///                 let _: Pin<&mut T> = x;
68///             }
69///         }
70///     }
71/// }
72/// ```
73///
74/// Note that the projection types returned by `project` and `project_ref` have
75/// an additional lifetime at the beginning of generics.
76///
77/// ```text
78/// let this: EnumProj<'_, T> = self.project();
79///                    ^^
80/// ```
81///
82/// The visibility of the projected types and projection methods is based on the
83/// original type. However, if the visibility of the original type is `pub`, the
84/// visibility of the projected types and the projection methods is downgraded
85/// to `pub(crate)`.
86///
87/// # Safety
88///
89/// This attribute is completely safe. In the absence of other `unsafe` code
90/// *that you write*, it is impossible to cause [undefined
91/// behavior][undefined-behavior] with this attribute.
92///
93/// This is accomplished by enforcing the four requirements for pin projection
94/// stated in [the Rust documentation][pin-projection]:
95///
96/// 1. The struct must only be [`Unpin`] if all the structural fields are
97///    [`Unpin`].
98///
99///    To enforce this, this attribute will automatically generate an [`Unpin`]
100///    implementation for you, which will require that all structurally pinned
101///    fields be [`Unpin`].
102///
103///    If you attempt to provide an [`Unpin`] impl, the blanket impl will then
104///    apply to your type, causing a compile-time error due to the conflict with
105///    the second impl.
106///
107///    If you wish to provide a manual [`Unpin`] impl, you can do so via the
108///    [`UnsafeUnpin`][unsafe-unpin] argument.
109///
110/// 2. The destructor of the struct must not move structural fields out of its
111///    argument.
112///
113///    To enforce this, this attribute will generate code like this:
114///
115///    ```
116///    struct MyStruct {}
117///    trait MyStructMustNotImplDrop {}
118///    # #[allow(unknown_lints, drop_bounds)]
119///    impl<T: Drop> MyStructMustNotImplDrop for T {}
120///    impl MyStructMustNotImplDrop for MyStruct {}
121///    ```
122///
123///    If you attempt to provide an [`Drop`] impl, the blanket impl will then
124///    apply to your type, causing a compile-time error due to the conflict with
125///    the second impl.
126///
127///    If you wish to provide a custom [`Drop`] impl, you can annotate an impl
128///    with [`#[pinned_drop]`][pinned-drop]. This impl takes a pinned version of
129///    your struct - that is, [`Pin`]`<&mut MyStruct>` where `MyStruct` is the
130///    type of your struct.
131///
132///    You can call `.project()` on this type as usual, along with any other
133///    methods you have defined. Because your code is never provided with
134///    a `&mut MyStruct`, it is impossible to move out of pin-projectable
135///    fields in safe code in your destructor.
136///
137/// 3. You must make sure that you uphold the [`Drop`
138///    guarantee][drop-guarantee]: once your struct is pinned, the memory that
139///    contains the content is not overwritten or deallocated without calling
140///    the content's destructors.
141///
142///    Safe code doesn't need to worry about this - the only way to violate
143///    this requirement is to manually deallocate memory (which is `unsafe`),
144///    or to overwrite a field with something else.
145///    Because your custom destructor takes [`Pin`]`<&mut MyStruct>`, it's
146///    impossible to obtain a mutable reference to a pin-projected field in safe
147///    code.
148///
149/// 4. You must not offer any other operations that could lead to data being
150///    moved out of the structural fields when your type is pinned.
151///
152///    As with requirement 3, it is impossible for safe code to violate this.
153///    This crate ensures that safe code can never obtain a mutable reference to
154///    `#[pin]` fields, which prevents you from ever moving out of them in safe
155///    code.
156///
157/// Pin projections are also incompatible with [`#[repr(packed)]`][repr-packed]
158/// types. Attempting to use this attribute on a `#[repr(packed)]` type results
159/// in a compile-time error.
160///
161/// # Examples
162///
163/// `#[pin_project]` can be used on structs and enums.
164///
165/// ```
166/// use std::pin::Pin;
167///
168/// use pin_project::pin_project;
169///
170/// #[pin_project]
171/// struct Struct<T, U> {
172///     #[pin]
173///     pinned: T,
174///     unpinned: U,
175/// }
176///
177/// impl<T, U> Struct<T, U> {
178///     fn method(self: Pin<&mut Self>) {
179///         let this = self.project();
180///         let _: Pin<&mut T> = this.pinned;
181///         let _: &mut U = this.unpinned;
182///     }
183/// }
184/// ```
185///
186/// ```
187/// use std::pin::Pin;
188///
189/// use pin_project::pin_project;
190///
191/// #[pin_project]
192/// struct TupleStruct<T, U>(#[pin] T, U);
193///
194/// impl<T, U> TupleStruct<T, U> {
195///     fn method(self: Pin<&mut Self>) {
196///         let this = self.project();
197///         let _: Pin<&mut T> = this.0;
198///         let _: &mut U = this.1;
199///     }
200/// }
201/// ```
202///
203/// To use `#[pin_project]` on enums, you need to name the projection type
204/// returned from the method.
205///
206/// ```
207/// use std::pin::Pin;
208///
209/// use pin_project::pin_project;
210///
211/// #[pin_project(project = EnumProj)]
212/// enum Enum<T, U> {
213///     Tuple(#[pin] T),
214///     Struct { field: U },
215///     Unit,
216/// }
217///
218/// impl<T, U> Enum<T, U> {
219///     fn method(self: Pin<&mut Self>) {
220///         match self.project() {
221///             EnumProj::Tuple(x) => {
222///                 let _: Pin<&mut T> = x;
223///             }
224///             EnumProj::Struct { field } => {
225///                 let _: &mut U = field;
226///             }
227///             EnumProj::Unit => {}
228///         }
229///     }
230/// }
231/// ```
232///
233/// When `#[pin_project]` is used on enums, only named projection types and
234/// methods are generated because there is no way to access variants of
235/// projected types without naming it.
236/// For example, in the above example, only the `project` method is generated,
237/// and the `project_ref` method is not generated.
238/// (When `#[pin_project]` is used on structs, both methods are always generated.)
239///
240/// ```compile_fail,E0599
241/// # use pin_project::pin_project;
242/// # use std::pin::Pin;
243/// #
244/// # #[pin_project(project = EnumProj)]
245/// # enum Enum<T, U> {
246/// #     Tuple(#[pin] T),
247/// #     Struct { field: U },
248/// #     Unit,
249/// # }
250/// #
251/// impl<T, U> Enum<T, U> {
252///     fn call_project_ref(self: Pin<&Self>) {
253///         let _this = self.project_ref();
254///         //~^ ERROR no method named `project_ref` found for struct `Pin<&Enum<T, U>>` in the current scope
255///     }
256/// }
257/// ```
258///
259/// If you want to call `.project()` multiple times or later use the
260/// original [`Pin`] type, it needs to use [`.as_mut()`][`Pin::as_mut`] to avoid
261/// consuming the [`Pin`].
262///
263/// ```
264/// use std::pin::Pin;
265///
266/// use pin_project::pin_project;
267///
268/// #[pin_project]
269/// struct Struct<T> {
270///     #[pin]
271///     field: T,
272/// }
273///
274/// impl<T> Struct<T> {
275///     fn call_project_twice(mut self: Pin<&mut Self>) {
276///         // `project` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`.
277///         self.as_mut().project();
278///         self.as_mut().project();
279///     }
280/// }
281/// ```
282///
283/// # `!Unpin`
284///
285/// If you want to ensure that [`Unpin`] is not implemented, use the `!Unpin`
286/// argument to `#[pin_project]`.
287///
288/// ```
289/// use pin_project::pin_project;
290///
291/// #[pin_project(!Unpin)]
292/// struct Struct<T> {
293///     field: T,
294/// }
295/// ```
296///
297/// This is equivalent to using `#[pin]` attribute for the [`PhantomPinned`]
298/// field.
299///
300/// ```
301/// use std::marker::PhantomPinned;
302///
303/// use pin_project::pin_project;
304///
305/// #[pin_project]
306/// struct Struct<T> {
307///     field: T,
308///     #[pin] // <------ This `#[pin]` is required to make `Struct` to `!Unpin`.
309///     _pin: PhantomPinned,
310/// }
311/// ```
312///
313/// Note that using [`PhantomPinned`] without `#[pin]` attribute has no effect.
314///
315/// # `UnsafeUnpin`
316///
317/// If you want to implement [`Unpin`] manually, you must use the `UnsafeUnpin`
318/// argument to `#[pin_project]`.
319///
320/// ```
321/// use pin_project::{UnsafeUnpin, pin_project};
322///
323/// #[pin_project(UnsafeUnpin)]
324/// struct Struct<T, U> {
325///     #[pin]
326///     pinned: T,
327///     unpinned: U,
328/// }
329///
330/// # #[allow(clippy::undocumented_unsafe_blocks)]
331/// unsafe impl<T: Unpin, U> UnsafeUnpin for Struct<T, U> {}
332/// ```
333///
334/// Note the usage of the unsafe [`UnsafeUnpin`] trait, instead of the usual
335/// [`Unpin`] trait. [`UnsafeUnpin`] behaves exactly like [`Unpin`], except that
336/// is unsafe to implement. This unsafety comes from the fact that pin
337/// projections are being used. If you implement [`UnsafeUnpin`], you must
338/// ensure that it is only implemented when all pin-projected fields implement
339/// [`Unpin`].
340///
341/// See [`UnsafeUnpin`] trait for more details.
342///
343/// # `#[pinned_drop]`
344///
345/// In order to correctly implement pin projections, a type's [`Drop`] impl must
346/// not move out of any structurally pinned fields. Unfortunately,
347/// [`Drop::drop`] takes `&mut Self`, not [`Pin`]`<&mut Self>`.
348///
349/// To ensure that this requirement is upheld, the `#[pin_project]` attribute
350/// will provide a [`Drop`] impl for you. This [`Drop`] impl will delegate to
351/// an impl block annotated with `#[pinned_drop]` if you use the `PinnedDrop`
352/// argument to `#[pin_project]`.
353///
354/// This impl block acts just like a normal [`Drop`] impl,
355/// except for the following two:
356///
357/// - `drop` method takes [`Pin`]`<&mut Self>`
358/// - Name of the trait is `PinnedDrop`.
359///
360/// ```
361/// # use std::pin::Pin;
362/// # #[allow(unreachable_pub)]
363/// pub trait PinnedDrop {
364///     fn drop(self: Pin<&mut Self>);
365/// }
366/// ```
367///
368/// `#[pin_project]` implements the actual [`Drop`] trait via `PinnedDrop` you
369/// implemented. To drop a type that implements `PinnedDrop`, use the [`drop`]
370/// function just like dropping a type that directly implements [`Drop`].
371///
372/// In particular, it will never be called more than once, just like
373/// [`Drop::drop`].
374///
375/// For example:
376///
377/// ```
378/// use std::{fmt::Debug, pin::Pin};
379///
380/// use pin_project::{pin_project, pinned_drop};
381///
382/// #[pin_project(PinnedDrop)]
383/// struct PrintOnDrop<T: Debug, U: Debug> {
384///     #[pin]
385///     pinned_field: T,
386///     unpin_field: U,
387/// }
388///
389/// #[pinned_drop]
390/// impl<T: Debug, U: Debug> PinnedDrop for PrintOnDrop<T, U> {
391///     fn drop(self: Pin<&mut Self>) {
392///         println!("Dropping pinned field: {:?}", self.pinned_field);
393///         println!("Dropping unpin field: {:?}", self.unpin_field);
394///     }
395/// }
396///
397/// fn main() {
398///     let _x = PrintOnDrop { pinned_field: true, unpin_field: 40 };
399/// }
400/// ```
401///
402/// See also [`#[pinned_drop]`][macro@pinned_drop] attribute.
403///
404/// # `project_replace` method
405///
406/// In addition to the `project` and `project_ref` methods which are always
407/// provided when you use the `#[pin_project]` attribute, there is a third
408/// method, `project_replace` which can be useful in some situations. It is
409/// equivalent to [`Pin::set`], except that the unpinned fields are moved and
410/// returned, instead of being dropped in-place.
411///
412/// ```
413/// # use std::pin::Pin;
414/// # type ProjectionOwned = ();
415/// # trait Dox {
416/// fn project_replace(self: Pin<&mut Self>, other: Self) -> ProjectionOwned;
417/// # }
418/// ```
419///
420/// The `ProjectionOwned` type is identical to the `Self` type, except that
421/// all pinned fields have been replaced by equivalent [`PhantomData`] types.
422///
423/// This method is opt-in, because it is only supported for [`Sized`] types, and
424/// because it is incompatible with the [`#[pinned_drop]`][pinned-drop]
425/// attribute described above. It can be enabled by using
426/// `#[pin_project(project_replace)]`.
427///
428/// For example:
429///
430/// ```
431/// use std::{marker::PhantomData, pin::Pin};
432///
433/// use pin_project::pin_project;
434///
435/// #[pin_project(project_replace)]
436/// struct Struct<T, U> {
437///     #[pin]
438///     pinned_field: T,
439///     unpinned_field: U,
440/// }
441///
442/// impl<T, U> Struct<T, U> {
443///     fn method(self: Pin<&mut Self>, other: Self) {
444///         let this = self.project_replace(other);
445///         let _: U = this.unpinned_field;
446///         let _: PhantomData<T> = this.pinned_field;
447///     }
448/// }
449/// ```
450///
451/// By passing the value to the `project_replace` argument, you can name the
452/// returned type of the `project_replace` method. This is necessary whenever
453/// destructuring the return type of the `project_replace` method, and work in exactly
454/// the same way as the `project` and `project_ref` arguments.
455///
456/// ```
457/// use pin_project::pin_project;
458///
459/// #[pin_project(project_replace = EnumProjOwn)]
460/// enum Enum<T, U> {
461///     A {
462///         #[pin]
463///         pinned_field: T,
464///         unpinned_field: U,
465///     },
466///     B,
467/// }
468///
469/// let mut x = Box::pin(Enum::A { pinned_field: 42, unpinned_field: "hello" });
470///
471/// match x.as_mut().project_replace(Enum::B) {
472///     EnumProjOwn::A { unpinned_field, .. } => assert_eq!(unpinned_field, "hello"),
473///     EnumProjOwn::B => unreachable!(),
474/// }
475/// ```
476///
477/// [`PhantomData`]: core::marker::PhantomData
478/// [`PhantomPinned`]: core::marker::PhantomPinned
479/// [`Pin::as_mut`]: core::pin::Pin::as_mut
480/// [`Pin::set`]: core::pin::Pin::set
481/// [`Pin`]: core::pin::Pin
482/// [`UnsafeUnpin`]: https://docs.rs/pin-project/latest/pin_project/trait.UnsafeUnpin.html
483/// [drop-guarantee]: core::pin#drop-guarantee
484/// [pin-projection]: core::pin#projections-and-structural-pinning
485/// [pinned-drop]: macro@pin_project#pinned_drop
486/// [repr-packed]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprpacked
487/// [undefined-behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
488/// [unsafe-unpin]: macro@pin_project#unsafeunpin
489#[proc_macro_attribute]
490pub fn pin_project(args: TokenStream, input: TokenStream) -> TokenStream {
491    pin_project::attribute(&args.into(), input.into()).into()
492}
493
494/// An attribute used for custom implementations of [`Drop`].
495///
496/// This attribute is used in conjunction with the `PinnedDrop` argument to
497/// the [`#[pin_project]`][macro@pin_project] attribute.
498///
499/// The impl block annotated with this attribute acts just like a normal
500/// [`Drop`] impl, except for the following two:
501///
502/// - `drop` method takes [`Pin`]`<&mut Self>`
503/// - Name of the trait is `PinnedDrop`.
504///
505/// ```
506/// # use std::pin::Pin;
507/// # #[allow(unreachable_pub)]
508/// pub trait PinnedDrop {
509///     fn drop(self: Pin<&mut Self>);
510/// }
511/// ```
512///
513/// `#[pin_project]` implements the actual [`Drop`] trait via `PinnedDrop` you
514/// implemented. To drop a type that implements `PinnedDrop`, use the [`drop`]
515/// function just like dropping a type that directly implements [`Drop`].
516///
517/// In particular, it will never be called more than once, just like
518/// [`Drop::drop`].
519///
520/// # Examples
521///
522/// ```
523/// use std::pin::Pin;
524///
525/// use pin_project::{pin_project, pinned_drop};
526///
527/// #[pin_project(PinnedDrop)]
528/// struct PrintOnDrop {
529///     #[pin]
530///     field: u8,
531/// }
532///
533/// #[pinned_drop]
534/// impl PinnedDrop for PrintOnDrop {
535///     fn drop(self: Pin<&mut Self>) {
536///         println!("Dropping: {}", self.field);
537///     }
538/// }
539///
540/// fn main() {
541///     let _x = PrintOnDrop { field: 50 };
542/// }
543/// ```
544///
545/// See also ["pinned-drop" section of `#[pin_project]` attribute][pinned-drop].
546///
547/// # Why `#[pinned_drop]` attribute is needed?
548///
549/// Implementing `PinnedDrop::drop` is safe, but calling it is not safe.
550/// This is because destructors can be called multiple times in safe code and
551/// [double dropping is unsound][rust-lang/rust#62360].
552///
553/// Ideally, it would be desirable to be able to forbid manual calls in
554/// the same way as [`Drop::drop`], but the library cannot do it. So, by using
555/// macros and replacing them with private traits like the following,
556/// this crate prevent users from calling `PinnedDrop::drop` in safe code.
557///
558/// ```
559/// # use std::pin::Pin;
560/// # #[allow(unreachable_pub)]
561/// pub trait PinnedDrop {
562///     unsafe fn drop(self: Pin<&mut Self>);
563/// }
564/// ```
565///
566/// This allows implementing [`Drop`] safely using `#[pinned_drop]`.
567/// Also by using the [`drop`] function just like dropping a type that directly
568/// implements [`Drop`], can drop safely a type that implements `PinnedDrop`.
569///
570/// [rust-lang/rust#62360]: https://github.com/rust-lang/rust/pull/62360
571/// [`Pin`]: core::pin::Pin
572/// [pinned-drop]: macro@pin_project#pinned_drop
573#[proc_macro_attribute]
574pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
575    let input = syn::parse_macro_input!(input);
576    pinned_drop::attribute(&args.into(), input).into()
577}
578
579// Not public API.
580#[doc(hidden)]
581#[proc_macro_derive(__PinProjectInternalDerive, attributes(pin))]
582pub fn __pin_project_internal_derive(input: TokenStream) -> TokenStream {
583    pin_project::derive(input.into()).into()
584}