Rust for Linux List
 help / color / mirror / Atom feed
From: "Gary Guo" <gary@garyguo.net>
To: phasta@kernel.org, "Gary Guo" <gary@kernel.org>,
	"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: Re: [PATCH] rust: pin-init: document self-referential feature
Date: Tue, 01 Dec 2026 13:44:35 +0000	[thread overview]
Message-ID: <DN9FW81IZFC2.1018M56RVFGOL@garyguo.net> (raw)
In-Reply-To: <771a56496a50fc1e8bed77b45b3aa77feedca77d.camel@mailbox.org>

On Thu Nov 26, 2026 at 9:56 AM GMT, Philipp Stanner wrote:
> 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?

If you use `pin_data`, an `Unpin` implementation is controlled by `pin_data`. I
reckon this is also under-documented, but most users won't need to know anyway
(unless they manually implement `Unpin` and hit a duplicate implementation
errror). Typically, if all fields are `Unpin`, then the struct will be `Unpin`
despite use of `#[pin_data]`.

For self-referential struct, `pin_data` generates a never-satisfied
implementation and thus effectively never implement `Unpin` but also block user
from implementing it. This is true even if all fields are `Unpin`.

E.g.

    struct Foo {
        y: &'x u32,
        x: u32,
    }

all fields are `Unpin` but `Foo: !Unpin`.

I'd probably not expand it out because most users won't need to care.

>
>> +/// ## 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?

For some use cases perhaps, although `#[borrowed(mut)]` would make the field
disappear from all `&self` and `Pin<&mut Self>` so you can only access it via
the mutable reference that is created during initialization. If it fits your use
cases then it's a good replacement, but no generally true.

>
>> +/// ## 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" ?

The current wording is correct. Struct have generic parameters, and it can
either be lifetime parameter, type parameter or const parameter. Members don't
have 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?

No this feature is somewhat independent of self-referential borrow. You can have
a struct that just borrow from outside the struct only, but use the `exists`
feature:

    struct Foo<'a> where exists<'inv>: 'a {
        foo: Mutex<&'inv ()>,
    }

This is similar to

    struct Foo<'a> {
        foo: Mutex<&'a ()>,
    }

However the existential lifetime causes the struct to be covariant over `'a` and
not invariant. This becomes part of self-referential series because they're both
erased lifetimes and the implementation are remarkably similar (and shares
almost all the code).

>
>
>> +/// ## 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.

Depend on what you mean by preferred? If `project()` works then yes it is the
best. But many cases you do need to use `with_project()`/`with_project_ref()` or
the accessor methods so there's no single recommendation possible.

>
>> +/// - `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?

If you never access self-referential fields then you just need `project()` (or
directly access the field), which is why these methods didn't exist before the
pin-init self-ref series.

>
>
>> +///
>> +/// 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| {… ) ?

It's literally the next sentence?

>
>>  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);
> });

Ah I didn't include an example of invariant capture in the example above.
I should spell it out (and perhaps add comment in the doc code block too).

Best,
Gary

      reply	other threads:[~2026-12-01 13:44 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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
2026-12-01 13:44   ` Gary Guo [this message]

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=DN9FW81IZFC2.1018M56RVFGOL@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=gary@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=phasta@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