[PATCH] rust: pin-init: document self-referential feature

From: Gary Guo

Date: Tue Nov 24 2026 - 17:16:40 EST


From: Gary Guo <gary@xxxxxxxxxxx>

Add a section to the documentation of `#[pin_data]` macro about
the safe self-referential creation feature.

Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
---
rust/pin-init/src/lib.rs | 176 +++++++++++++++++++++++++++++++++++++++++++++--
1 file changed, 171 insertions(+), 5 deletions(-)

diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs
index 9ffa76434310..c0e87586b072 100644
--- a/rust/pin-init/src/lib.rs
+++ b/rust/pin-init/src/lib.rs
@@ -307,6 +307,9 @@
/// Tuple structs are supported as well. Their fields have no names, so the generated projection
/// is a tuple struct too and its fields are accessed by index.
///
+/// Self-referential structs, where a field borrows another field of the same struct, are also
+/// supported. See the [section on self-referential structs](#self-referential-structs) below.
+///
/// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
/// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
/// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
@@ -376,6 +379,170 @@
/// }
/// }
/// ```
+///
+/// # Self-Referential Structs
+///
+/// This macro also supports structs where a field borrows another field of the same struct. To do
+/// that, use the name of the borrowed field as a lifetime (a *field lifetime*) in the type of the
+/// borrowing field:
+///
+/// ```
+/// # use pin_init::*;
+/// #[pin_data]
+/// struct SelfRef {
+/// part: &'msg str,
+/// msg: String,
+/// }
+/// ```
+///
+/// Here the field `part` captures the field lifetime `'msg` and thereby borrows the field `msg`.
+/// A field may only borrow from fields declared after it: fields are dropped in declaration
+/// order, so the borrowing field is then always dropped before the field it borrows. Structs
+/// with borrowed fields or captured lifetimes do not implement `Unpin`.
+///
+/// When initializing such a struct with [`pin_init!`], every named initialized field have a
+/// binding generated for it (as `&T`/`Pin<&T>` for fields share-borrowed, or `&mut`/`Pin<&mut T>`
+/// for fields mutably-borrowed), so a field can borrow from the fields initialized before it:
+///
+/// ```
+/// # use pin_init::*;
+/// # #[pin_data]
+/// # struct SelfRef {
+/// # part: &'msg str,
+/// # msg: String,
+/// # }
+/// stack_pin_init!(let foo = pin_init!(SelfRef {
+/// msg: "hello world".to_owned(),
+/// part: &msg[..5],
+/// }));
+/// assert_eq!(*foo.part(), "hello");
+/// ```
+///
+/// Note that `&mut`/`Pin<&mut T>` bindings are also generated for non-borrowed field, but access to
+/// them are limited to within the initializer.
+///
+/// ## Mutable Borrows
+///
+/// A field is only shared-borrowed by default. To also allow `&mut` borrows, mark the borrowed
+/// field with `#[borrowed(mut)]`:
+///
+/// ```
+/// # use pin_init::*;
+/// #[pin_data]
+/// struct MutSelfRef {
+/// part: &'mut_msg mut str,
+/// #[borrowed(mut)]
+/// mut_msg: String,
+/// }
+///
+/// stack_pin_init!(let foo = pin_init!(MutSelfRef {
+/// mut_msg: "hello world".to_owned(),
+/// part: &mut mut_msg[..5],
+/// }));
+/// foo.as_mut().with_project(|proj| proj.part.make_ascii_uppercase());
+/// assert_eq!(*foo.part(), "HELLO");
+/// ```
+///
+/// Shared borrows are inferred automatically whenever a field lifetime is used, but they can also
+/// be requested explicitly with `#[borrowed]`.
+///
+/// ## Variance
+///
+/// A captured field lifetime is *covariant* by default: just like a normal reference, the field
+/// type allows the captured lifetime to be shortened. If the field type does not allow that (for
+/// example because the borrow is stored behind a `Mutex`), the capture has to be marked as
+/// *invariant* using the `#[uses]` attribute:
+///
+/// ```
+/// # use pin_init::*;
+/// # use std::sync::Mutex;
+/// #[pin_data]
+/// struct InvariantSelfRef {
+/// #[uses('owner: invariant)]
+/// part: Mutex<&'owner str>,
+/// owner: String,
+/// }
+/// ```
+///
+/// The macro verifies that captures marked covariant really are covariant. `#[uses]` accepts a
+/// comma-separated list of lifetimes, each with an optional variance (the default being
+/// `covariant`). The special lifetime `'_` stands for all field lifetimes mentioned in the type
+/// of the field, e.g. `#[uses('_: invariant)]`.
+///
+/// ## Existential Lifetimes
+///
+/// A field lifetime ties a borrow to a specific field. Sometimes a field should instead borrow
+/// from something outside the struct that merely outlives one of the struct's lifetime
+/// parameters. Such lifetimes are declared in the where clause of the struct using `exists`:
+///
+/// ```
+/// # use pin_init::*;
+/// # use std::marker::PhantomData;
+/// # use std::sync::Mutex;
+/// struct CoherentBox<'a>(PhantomData<&'a ()>);
+///
+/// #[pin_data]
+/// struct DeviceBox<'a>
+/// where
+/// exists<'x>: 'a,
+/// {
+/// #[uses('x: invariant)]
+/// m: Mutex<CoherentBox<'x>>,
+/// p: PhantomData<&'a ()>,
+/// }
+///
+/// // The struct is covariant in `'a`, so it can be shortened:
+/// fn shorten<'long: 'short, 'short>(f: DeviceBox<'long>) -> DeviceBox<'short> {
+/// f
+/// }
+/// # let _ = shorten;
+/// ```
+///
+/// An existential lifetime is not a parameter of the struct, so just like a field lifetime it is
+/// hidden from the type of the struct. Unlike a field lifetime, it is not tied to a field; the
+/// only bounds placed on it are those written in the where clause (here `'x: 'a`).
+///
+/// ## Projections and Accessors
+///
+/// Since field lifetimes are not parameters of the struct, borrows of the struct cannot carry
+/// them. This macro therefore generates several methods for accessing the fields:
+///
+/// - `project(self: Pin<&mut Self>)` — the pin projection: `#[pin]` fields are projected as
+/// `Pin<&mut T>`, all other fields as `&mut T`. Fields that capture a field lifetime covariantly
+/// are only projected as (possibly pinned) shared references; fields with invariant field
+/// lifetime capture are omitted entirely.
+/// - `with_project(self: Pin<&mut Self>, f)` — calls `f` with a projection in which every
+/// visible field has its actual field lifetime, so even invariant captures are visible.
+/// - `with_project_ref(self: Pin<&Self>, f)` — the shared version of `with_project`.
+///
+/// For all projections, shared borrow fields are only accessible with shared references, and
+/// mutably borrowed fields are omitted (they are only accessible through the fields that borrow
+/// them).
+///
+/// Every field (except those borrowed mutably) that captures field lifetimes also gets an accessor
+/// method, because they cannot be directly accessed. `fn field(&self)` is generated if all of its
+/// captures are covariant, otherwise `fn with_field(&self, f)` is generated where `f` is called
+/// with the field at its captured lifetimes.
+///
+/// ```
+/// # use pin_init::*;
+/// # #[pin_data]
+/// # struct SelfRef {
+/// # part: &'msg str,
+/// # msg: String,
+/// # }
+/// # stack_pin_init!(let foo = pin_init!(SelfRef {
+/// # msg: "hello world".to_owned(),
+/// # part: &msg[..5],
+/// # }));
+/// foo.as_mut().with_project(|proj| {
+/// *proj.part = &proj.msg[6..];
+/// });
+/// assert_eq!(*foo.part(), "world");
+/// foo.as_ref().with_project_ref(|proj| {
+/// assert_eq!(*proj.part, "world");
+/// });
+/// ```
pub use ::pin_init_internal::pin_data;

/// Used to implement `PinnedDrop` safely.
@@ -664,11 +831,10 @@ macro_rules! stack_try_pin_init {
///
/// Arbitrary Rust expressions can be used to set the value of a variable.
///
-/// The fields are initialized in the order that they appear in the initializer. So it is possible
-/// to read already initialized fields using raw pointers.
-///
-/// IMPORTANT: You are not allowed to create references to fields of the struct inside of the
-/// initializer.
+/// The fields are initialized in the order that they appear in the initializer. A let binding
+/// is generated so already initialized fields can be read. For [self-referential
+/// structs](pin_data#self-referential-structs), you may also use such generated bindings to
+/// initialize fields that borrow from them.
///
/// # Init-functions
///

---
base-commit: 5eb5b404e6e7631a986333f00e7b3b18aafcfaa8
change-id: 20261124-dev-pin-init-doc-c488879a1c79

Best regards,
--
Gary Guo <gary@xxxxxxxxxxx>