mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Gary Guo <gary@garyguo.net>
To: "Benno Lossin" <lossin@kernel.org>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
	 Gary Guo <gary@garyguo.net>
Subject: [PATCH v2] rust: pin-init: document self-referential feature
Date: Wed, 02 Dec 2026 16:42:53 +0000	[thread overview]
Message-ID: <20261202-dev-pin-init-doc-v2-1-987d6f92adca@garyguo.net> (raw)

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

Signed-off-by: Gary Guo <gary@garyguo.net>
---
Changes in v2:
- Fix various typos (Alice)
- Add an example of invariant capture and accessor (Philipp)
- Link to v1: https://patch.msgid.link/20261124-dev-pin-init-doc-v1-1-dd0a3eda9018@garyguo.net
---
 rust/pin-init/src/lib.rs | 189 +++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 183 insertions(+), 6 deletions(-)

diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs
index 9ffa76434310..724b67a92cb5 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,179 @@
 ///     }
 /// }
 /// ```
+///
+/// # 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 has a
+/// binding generated for it (as `&T`/`Pin<&T>` for fields shared-borrowed, or
+/// `&mut T`/`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 T`/`Pin<&mut T>` bindings are also generated for non-borrowed fields, but access
+/// to them is limited to within the initializer.
+///
+/// ## Mutable Borrows
+///
+/// A field is only shared-borrowed by default. To also allow for `&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 (and existential) 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`, i.e. `'x` lives
+/// longer than `'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 or existential
+///   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-borrowed 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 or existential 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::*;
+/// # use std::sync::Mutex;
+/// #[pin_data]
+/// struct SelfRef {
+///     #[uses('_: invariant)]
+///     inv_part: Mutex<&'msg str>,
+///     part: &'msg str,
+///     msg: String,
+/// }
+/// # stack_pin_init!(let foo = pin_init!(SelfRef {
+/// #    msg: "hello world".to_owned(),
+/// #    part: &msg[..5],
+/// #    inv_part: Mutex::new(&msg[..5]),
+/// # }));
+/// foo.as_mut().with_project(|proj| {
+///     *proj.part = &proj.msg[6..];
+/// });
+/// foo.as_ref().with_project_ref(|proj| {
+///     *proj.inv_part.lock().unwrap() = &proj.msg[6..];
+/// });
+/// // Individual covariant field access
+/// assert_eq!(*foo.part(), "world");
+/// // Individual invariant field access
+/// foo.with_inv_part(|part| assert_eq!(*part.lock().unwrap(), "world"));
+/// ```
 pub use ::pin_init_internal::pin_data;
 
 /// Used to implement `PinnedDrop` safely.
@@ -664,11 +840,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 named 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
 ///
@@ -834,7 +1009,9 @@ macro_rules! stack_try_pin_init {
 /// - `unsafe` code must guarantee either full initialization or return an error and allow
 ///   deallocation of the memory.
 /// - the fields are initialized in the order given in the initializer.
-/// - no references to fields are allowed to be created inside of the initializer.
+/// - let bindings are generated for already initialized named fields for access within the
+///   initializer; unlike [`pin_init!`], creation of self-referential struct is not permitted with
+///   `init!`.
 ///
 /// This initializer is for initializing data in-place that might later be moved. If you want to
 /// pin-initialize, use [`pin_init!`].

---
base-commit: 246f6b0262bae1c4a8145804713c0a338f907bc4
change-id: 20261124-dev-pin-init-doc-c488879a1c79

Best regards,
--  
Gary Guo <gary@garyguo.net>


                 reply	other threads:[~2026-12-02 16:43 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261202-dev-pin-init-doc-v2-1-987d6f92adca@garyguo.net \
    --to=gary@garyguo.net \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=work@onurozkan.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®