Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
44e77f1
internal: pin_data: infer self-referential struct
nbdd0121 Apr 30, 2026
d3e89e0
internal: pin_data: rewrite fields that borrow others
nbdd0121 May 1, 2026
ab3dce4
internal: pin_data: pin borrowed fields with wrapper
nbdd0121 Sep 22, 2026
897485f
internal: pin_data: teach drop check about generics that cannot dangle
nbdd0121 Sep 22, 2026
feae46e
internal: pin_data: self-referential drop order checks
nbdd0121 May 1, 2026
17e5fc8
internal: pin_data: check covariance of self-referential fields
nbdd0121 May 2, 2026
237b17a
internal: pin_data: implement initialization of borrowed structs
nbdd0121 Apr 25, 2026
9ee8803
internal: pin_data: project self-referential fields
nbdd0121 Sep 25, 2026
ca0985e
internal: pin_data: add `with_project` method
nbdd0121 May 2, 2026
b66eb3a
internal: pin_data: enable self-referential support
nbdd0121 Sep 29, 2026
2238c9d
internal: pin_data: allow lifetime to be shortened per field drop order
nbdd0121 Oct 1, 2026
7b76ee2
internal: pin_data: parse explicit `#[borrowed]` annotation
nbdd0121 Sep 24, 2026
ebf2b0a
internal: pin_data: support mutable borrows
nbdd0121 May 6, 2026
d23c5bc
internal: pin_data: parse explicit `#[uses]` annotation
nbdd0121 Sep 24, 2026
582ac96
internal: pin_data: make field lifetime invariance imply type invariance
nbdd0121 Sep 9, 2026
cc92c50
internal: pin_data: complete invariant borrow support
nbdd0121 May 2, 2026
63cd2f7
internal: pin_data: perform AST lifetime replacement if possible
nbdd0121 May 2, 2026
3a36d0e
internal: pin_data: support shared projection
nbdd0121 Sep 8, 2026
315a807
internal: pin_data: support existential lifetimes
nbdd0121 Sep 9, 2026
bb0c889
tests: add self reference test suites
nbdd0121 Sep 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Tuple structs are now supported. For `[pin_]init!` , if pinning (`<-` syntax) is required, only
the struct syntax can be used, e.g. `init!(Foo { 0: value, 1 <- initializer })`.
- Safely creating references from sibling fields is now supported.
- `[pin_]init_scope` functions to run arbitrary code inside of an initializer.
- `&'static mut MaybeUninit<T>` now implements `InPlaceWrite`. This enables users to use external
allocation mechanisms such as `static_cell`.
Expand Down
60 changes: 60 additions & 0 deletions examples/selfref.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT

#![allow(clippy::disallowed_names)]

use pin_init::*;

#[pin_data]
struct SelfRef {
#[uses('_: invariant)]
not_cov: Box<dyn Fn(&'str str) -> bool + 'str>,

part: &'str str,
str: String,

mut_part: &'mut_str mut str,
#[borrowed(mut)]
mut_str: String,
}

fn use_self_ref() {
stack_pin_init!(let foo = pin_init!(SelfRef {
str: "hello world".to_owned(),
part: &str[..5],
mut_str: "hello world".to_owned(),
mut_part: &mut mut_str[..5],
not_cov: Box::new(move |s| s == str),
}));

// Access via projection.
println!("{}", foo.as_mut().project().part);

// Access via accessor.
println!("{}", foo.part());

// Access via `with_project`, gives mutable reference.
foo.as_mut().with_project(|proj| {
*proj.part = &proj.str[5..];
});

println!("{}", foo.part());

// Access fields that mutable borrow others are similar to those of shared borrow.
println!("{}", foo.as_mut().project().mut_part);
println!("{}", foo.mut_part());
foo.as_mut().with_project(|proj| {
proj.mut_part.make_ascii_uppercase();
});

// Access non-covariant type using `with_` accessor.
foo.with_not_cov(|not_cov| {
not_cov("");
});

// Access non-covariant type using `with_project`.
foo.as_mut().with_project(|proj| (proj.not_cov)(proj.str));
}

fn main() {
use_self_ref();
}
2 changes: 1 addition & 1 deletion internal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ proc-macro = true
[dependencies]
quote = "1.0.40"
proc-macro2 = "1.0.101"
syn = { version = "2.0.106", features = ["full", "parsing", "visit-mut"] }
syn = { version = "2.0.106", features = ["full", "parsing", "visit", "visit-mut"] }

[build-dependencies]
rustc_version = "0.4"
Expand Down
42 changes: 35 additions & 7 deletions internal/src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,10 @@ fn expand(
},
};
// `mixed_site` ensures that the data is not accessible to the user-controlled code.
let init_fields = init_fields(&fields, pinned);
let init_fields = make_field_init(&fields, pinned, false);
let drop_check = make_field_init(&fields, pinned, true);
let field_check = make_field_check(&fields, init_kind, &path);

Ok(quote_spanned! { Span::mixed_site() => {
// Get the data about fields from the supplied type.
let data = {
Expand All @@ -303,17 +305,29 @@ fn expand(

// Ensure that `data` really is of type `data` and help with type inference:
let init = data.__make_closure::<_, #error>(
move |slot| {
move |slot, data_lt| {
#zeroable_check
#this
#init_fields
// Generate init twice, which is mostly identical except for lifetimes.
if true {
// In this path, we use the field lifetime from HRTB to prevent environment
// lifetime from entering the fields, and to ensure that the dependency of
// fields is consistent with the field drop of the struct.
#init_fields
} else {
// In this path, we use local lifetime, to make sure that if initialization
// fails, the destructor execution will not cause lifetime issues. This is
// separate as implied bounds between field lifetimes can be inconsistent with
// that of the drop.
#drop_check
}
#field_check
// SAFETY: we are the `init!` macro that is allowed to call this.
Ok(unsafe { ::pin_init::__internal::InitOk::new() })
}
);
let init = move |slot| -> ::core::result::Result<(), #error> {
init(slot).map(|__InitOk| ())
init(slot, data.__with_lt()).map(|__InitOk| ())
};
// SAFETY: TODO
unsafe { ::pin_init::#init_from_closure::<_, #error>(init) }
Expand Down Expand Up @@ -360,7 +374,11 @@ fn get_init_kind(rest: Option<(Token![..], Expr)>, dcx: &mut DiagCtxt) -> InitKi
}

/// Generate the code that initializes the fields of the struct using the initializers in `field`.
fn init_fields(fields: &Punctuated<InitializerField, Token![,]>, pinned: bool) -> TokenStream {
fn make_field_init(
fields: &Punctuated<InitializerField, Token![,]>,
pinned: bool,
dropck: bool,
) -> TokenStream {
let mut forget_guards = vec![];
let mut res = TokenStream::new();
for InitializerField { attrs, kind } in fields {
Expand Down Expand Up @@ -388,13 +406,18 @@ fn init_fields(fields: &Punctuated<InitializerField, Token![,]>, pinned: bool) -
let span = Span::mixed_site().located_at(ident.span());

let slot = if pinned {
let data = if !dropck {
quote_spanned!(span => data_lt)
} else {
quote_spanned!(span => data.__with_lt())
};
quote_spanned! { span =>
// SAFETY:
// - `slot` is valid and properly aligned.
// - `make_field_check` checks that `&raw mut (*slot).#member` is properly aligned.
// - `make_field_check` prevents `#member` from being used twice, therefore
// `(*slot).#member` is exclusively accessed and has not been initialized.
(unsafe { data.#ident(slot) })
(unsafe { #data.#ident(slot) })
}
} else {
quote_spanned! { span =>
Expand Down Expand Up @@ -455,14 +478,19 @@ fn init_fields(fields: &Punctuated<InitializerField, Token![,]>, pinned: bool) -

// A tuple field has no name that could be bound here (the `_0` identifiers are considered
// implementation detail and not user-facing).
let let_binding_method = if !dropck {
format_ident!("let_binding", span = span)
} else {
format_ident!("let_binding_in_dropck", span = span)
};
let binding = match member {
Member::Named(ident) => quote_spanned! { span =>
#(#cfgs)*
// Allow `non_snake_case` since the same warning is going to be reported for the
// struct field.
#[allow(unused_variables, non_snake_case)]
// Include `mut` so that `Pin<&mut T>` bindings can be reborrowed via `.as_mut()`.
let mut #ident = #guard.let_binding();
let mut #ident = #guard.#let_binding_method();
},
Member::Unnamed(_) => quote!(),
};
Expand Down
Loading
Loading