* [PATCH] rust: pin-init: document self-referential feature
@ 2026-11-24 22:16 Gary Guo
2026-11-26 8:13 ` Alice Ryhl
2026-11-26 9:56 ` Philipp Stanner
0 siblings, 2 replies; 3+ messages in thread
From: Gary Guo @ 2026-11-24 22:16 UTC (permalink / raw)
To: Benno Lossin, Miguel Ojeda, Boqun Feng, Björn Roy Baron,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Daniel Almeida, Tamir Duberstein, Alexandre Courbot,
Onur Özkan
Cc: rust-for-linux, linux-kernel, Gary Guo
From: Gary Guo <gary@garyguo.net>
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>
---
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@garyguo.net>
^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [PATCH] rust: pin-init: document self-referential feature
2026-11-24 22:16 [PATCH] rust: pin-init: document self-referential feature Gary Guo
@ 2026-11-26 8:13 ` Alice Ryhl
2026-11-26 9:56 ` Philipp Stanner
1 sibling, 0 replies; 3+ messages in thread
From: Alice Ryhl @ 2026-11-26 8:13 UTC (permalink / raw)
To: Gary Guo
Cc: Alice Ryhl, Benno Lossin, Miguel Ojeda, Boqun Feng,
Björn Roy Baron, Andreas Hindborg, Trevor Gross,
Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan, rust-for-linux, linux-kernel,
Gary Guo
On Tue, Nov 24, 2026 at 10:16:23PM +0000, Gary Guo wrote:
> +/// 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:
A couple of minor typos here:
- "have a" -> "has a"
- "share-borrowed" -> "shared-borrowed" (to match "Mutable Borrows" below)
- "`&mut`/`Pin<&mut T>`" -> "`&mut T`/`Pin<&mut T>`"
> +/// Note that `&mut`/`Pin<&mut T>` bindings are also generated for non-borrowed field, but access to
> +/// them are limited to within the initializer.
Same here:
- "`&mut`/`Pin<&mut T>`" -> "`&mut T`/`Pin<&mut T>`"
- "non-borrowed field" -> "non-borrowed fields"
- "access to them are" -> "access to them is"
> +/// 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)]`.
I think `'_` also applies to existential lifetimes mentioned in the
field type, not just field lifetimes.
> +/// 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 think it'd be useful to explicitly say:
are those written in the where clause (here `'x: 'a`, i.e. 'x is
shorter than 'a).
> +/// - `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).
"shared borrow fields" -> "shared-borrowed fields" (to match "mutably
borrowed fields" and avoid sounding like fields that hold a borrow).
> +/// 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!` just below still has `- no references to fields are allowed to
be created inside of the initializer.` even though `init!` generates the
same `let` bindings for named fields.
Alice
^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [PATCH] rust: pin-init: document self-referential feature
2026-11-24 22:16 [PATCH] rust: pin-init: document self-referential feature Gary Guo
2026-11-26 8:13 ` Alice Ryhl
@ 2026-11-26 9:56 ` Philipp Stanner
1 sibling, 0 replies; 3+ messages in thread
From: Philipp Stanner @ 2026-11-26 9:56 UTC (permalink / raw)
To: Gary Guo, Benno Lossin, Miguel Ojeda, Boqun Feng,
Björn Roy Baron, Andreas Hindborg, Alice Ryhl, Trevor Gross,
Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
Alexandre Courbot, Onur Özkan
Cc: rust-for-linux, linux-kernel, Gary Guo
On Tue, 2026-11-24 at 22:16 +0000, Gary Guo wrote:
> From: Gary Guo <gary@garyguo.net>
>
> Add a section to the documentation of `#[pin_data]` macro about
> the safe self-referential creation feature.
Thx for writing this, that's very useful. I read through it. Just some
comments below:
> +/// 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`.
Unpin is something the user would have to implement for his struct,
isn't it? So are you saying here that the macros do not generate Unpin?
Why's that mentioned, do you expect anyone to need / expect to have
Unpin?
> +/// ## Mutable Borrows
> +///
> +/// A field is only shared-borrowed by default. To also allow `&mut` borrows, mark the borrowed
I think the English-bros say "To also allow *for* …"
> +/// 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");
Is #[borrowed(mut)] basically a better alternative to UnsafeCell?
> +/// ## 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.
>
"the struct's lifetime parameters" == "the struct's members' lifetime
parameters" ?
It doesn't get fully clear to me why you mention "sometimes should
instead borrow from sth outside the struct". You seem to be referring
to "normal" structs that borrow something with a normal lifetime. So it
reads as if you fear that users might use self-referencial structs when
really their struct should just borrow something from the outside.. why
do you mention that, when would the user borrow something that the
struct already has which shouldn't be in there?
> +/// ## Projections and Accessors
> +///
> +/// Since field lifetimes are not parameters of the struct, borrows of the struct cannot carry
s/parameters/members ?
> +/// 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.
Means all self-referential fields are invisible? I would maybe mention
that project() should be the preferred accessor for users.
> +/// - `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`.
Thus, the user only wants these two if he needs to access self-
referential fields?
> +///
> +/// 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,
>
Are you refering to my_struct.member(), or to
my_struct.with_member(|member| {… ) ?
> 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");
> +/// });
So if you need one field only you would do:
foo.as_ref().with_part(|part| {
pr_info("{}", part);
});
?
^ permalink raw reply [flat|nested] 3+ messages in thread
end of thread, other threads:[~2026-11-26 9:56 UTC | newest]
Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-24 22:16 [PATCH] rust: pin-init: document self-referential feature Gary Guo
2026-11-26 8:13 ` Alice Ryhl
2026-11-26 9:56 ` Philipp Stanner
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®