rust: pin-init: remove `try_` versions of the initializer macros

The `try_[pin_]init!` versions of the initializer macros are
superfluous. Instead of forcing the user to always write an error in
`try_[pin_]init!` and not allowing one in `[pin_]init!`, combine them
into `[pin_]init!` that defaults the error to
`core::convert::Infallible`, but also allows to specify a custom one.

Projects using pin-init still can provide their own defaulting
initializers using the `try_` prefix by using the `#[default_error]`
attribute added in a future patch.

[ Adjust the definition of the kernel's version of the `try_`
  initializer macros - Benno]

Reviewed-by: Gary Guo <gary@garyguo.net>
Tested-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: Benno Lossin <lossin@kernel.org>
This commit is contained in:
Benno Lossin 2026-01-16 11:54:16 +01:00
parent 0f61b1860c
commit 61d62ab08f
5 changed files with 35 additions and 122 deletions

View File

@ -222,14 +222,14 @@ macro_rules! try_init {
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}) => { }) => {
::pin_init::try_init!($(&$this in)? $t $(::<$($generics),*>)? { ::pin_init::init!($(&$this in)? $t $(::<$($generics),*>)? {
$($fields)* $($fields)*
}? $crate::error::Error) }? $crate::error::Error)
}; };
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}? $err:ty) => { }? $err:ty) => {
::pin_init::try_init!($(&$this in)? $t $(::<$($generics),*>)? { ::pin_init::init!($(&$this in)? $t $(::<$($generics),*>)? {
$($fields)* $($fields)*
}? $err) }? $err)
}; };
@ -282,14 +282,14 @@ macro_rules! try_pin_init {
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}) => { }) => {
::pin_init::try_pin_init!($(&$this in)? $t $(::<$($generics),*>)? { ::pin_init::pin_init!($(&$this in)? $t $(::<$($generics),*>)? {
$($fields)* $($fields)*
}? $crate::error::Error) }? $crate::error::Error)
}; };
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}? $err:ty) => { }? $err:ty) => {
::pin_init::try_pin_init!($(&$this in)? $t $(::<$($generics),*>)? { ::pin_init::pin_init!($(&$this in)? $t $(::<$($generics),*>)? {
$($fields)* $($fields)*
}? $err) }? $err)
}; };

View File

@ -135,7 +135,7 @@ struct DriverData {
impl DriverData { impl DriverData {
fn new() -> impl PinInit<Self, Error> { fn new() -> impl PinInit<Self, Error> {
try_pin_init!(Self { pin_init!(Self {
status <- CMutex::new(0), status <- CMutex::new(0),
buffer: Box::init(pin_init::init_zeroed())?, buffer: Box::init(pin_init::init_zeroed())?,
}? Error) }? Error)

View File

@ -6,7 +6,6 @@
use core::{ use core::{
cell::Cell, cell::Cell,
convert::Infallible,
marker::PhantomPinned, marker::PhantomPinned,
pin::Pin, pin::Pin,
ptr::{self, NonNull}, ptr::{self, NonNull},
@ -31,31 +30,31 @@ pub struct ListHead {
impl ListHead { impl ListHead {
#[inline] #[inline]
pub fn new() -> impl PinInit<Self, Infallible> { pub fn new() -> impl PinInit<Self> {
try_pin_init!(&this in Self { pin_init!(&this in Self {
next: unsafe { Link::new_unchecked(this) }, next: unsafe { Link::new_unchecked(this) },
prev: unsafe { Link::new_unchecked(this) }, prev: unsafe { Link::new_unchecked(this) },
pin: PhantomPinned, pin: PhantomPinned,
}? Infallible) })
} }
#[inline] #[inline]
#[allow(dead_code)] #[allow(dead_code)]
pub fn insert_next(list: &ListHead) -> impl PinInit<Self, Infallible> + '_ { pub fn insert_next(list: &ListHead) -> impl PinInit<Self> + '_ {
try_pin_init!(&this in Self { pin_init!(&this in Self {
prev: list.next.prev().replace(unsafe { Link::new_unchecked(this)}), prev: list.next.prev().replace(unsafe { Link::new_unchecked(this)}),
next: list.next.replace(unsafe { Link::new_unchecked(this)}), next: list.next.replace(unsafe { Link::new_unchecked(this)}),
pin: PhantomPinned, pin: PhantomPinned,
}? Infallible) })
} }
#[inline] #[inline]
pub fn insert_prev(list: &ListHead) -> impl PinInit<Self, Infallible> + '_ { pub fn insert_prev(list: &ListHead) -> impl PinInit<Self> + '_ {
try_pin_init!(&this in Self { pin_init!(&this in Self {
next: list.prev.next().replace(unsafe { Link::new_unchecked(this)}), next: list.prev.next().replace(unsafe { Link::new_unchecked(this)}),
prev: list.prev.replace(unsafe { Link::new_unchecked(this)}), prev: list.prev.replace(unsafe { Link::new_unchecked(this)}),
pin: PhantomPinned, pin: PhantomPinned,
}? Infallible) })
} }
#[inline] #[inline]

View File

@ -98,11 +98,11 @@ mod pthread_mtx {
// SAFETY: mutex has been initialized // SAFETY: mutex has been initialized
unsafe { pin_init_from_closure(init) } unsafe { pin_init_from_closure(init) }
} }
try_pin_init!(Self { pin_init!(Self {
data: UnsafeCell::new(data), data: UnsafeCell::new(data),
raw <- init_raw(), raw <- init_raw(),
pin: PhantomPinned, pin: PhantomPinned,
}? Error) }? Error)
} }
#[allow(dead_code)] #[allow(dead_code)]

View File

@ -146,7 +146,7 @@
//! //!
//! impl DriverData { //! impl DriverData {
//! fn new() -> impl PinInit<Self, Error> { //! fn new() -> impl PinInit<Self, Error> {
//! try_pin_init!(Self { //! pin_init!(Self {
//! status <- CMutex::new(0), //! status <- CMutex::new(0),
//! buffer: Box::init(pin_init::init_zeroed())?, //! buffer: Box::init(pin_init::init_zeroed())?,
//! }? Error) //! }? Error)
@ -528,7 +528,7 @@ macro_rules! stack_pin_init {
/// x: u32, /// x: u32,
/// } /// }
/// ///
/// stack_try_pin_init!(let foo: Foo = try_pin_init!(Foo { /// stack_try_pin_init!(let foo: Foo = pin_init!(Foo {
/// a <- CMutex::new(42), /// a <- CMutex::new(42),
/// b: Box::try_new(Bar { /// b: Box::try_new(Bar {
/// x: 64, /// x: 64,
@ -555,7 +555,7 @@ macro_rules! stack_pin_init {
/// x: u32, /// x: u32,
/// } /// }
/// ///
/// stack_try_pin_init!(let foo: Foo =? try_pin_init!(Foo { /// stack_try_pin_init!(let foo: Foo =? pin_init!(Foo {
/// a <- CMutex::new(42), /// a <- CMutex::new(42),
/// b: Box::try_new(Bar { /// b: Box::try_new(Bar {
/// x: 64, /// x: 64,
@ -584,10 +584,10 @@ macro_rules! stack_try_pin_init {
}; };
} }
/// Construct an in-place, pinned initializer for `struct`s. /// Construct an in-place, fallible pinned initializer for `struct`s.
/// ///
/// This macro defaults the error to [`Infallible`]. If you need a different error, then use /// The error type defaults to [`Infallible`]; if you need a different one, write `? Error` at the
/// [`try_pin_init!`]. /// end, after the struct initializer.
/// ///
/// The syntax is almost identical to that of a normal `struct` initializer: /// The syntax is almost identical to that of a normal `struct` initializer:
/// ///
@ -783,54 +783,10 @@ macro_rules! pin_init {
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}) => { }) => {
$crate::try_pin_init!($(&$this in)? $t $(::<$($generics),*>)? { $crate::pin_init!($(&$this in)? $t $(::<$($generics),*>)? {
$($fields)* $($fields)*
}? ::core::convert::Infallible) }? ::core::convert::Infallible)
}; };
}
/// Construct an in-place, fallible pinned initializer for `struct`s.
///
/// If the initialization can complete without error (or [`Infallible`]), then use [`pin_init!`].
///
/// You can use the `?` operator or use `return Err(err)` inside the initializer to stop
/// initialization and return the error.
///
/// IMPORTANT: if you have `unsafe` code inside of the initializer you have to ensure that when
/// initialization fails, the memory can be safely deallocated without any further modifications.
///
/// The syntax is identical to [`pin_init!`] with the following exception: you must append `? $type`
/// after the `struct` initializer to specify the error type you want to use.
///
/// # Examples
///
/// ```rust
/// # #![feature(allocator_api)]
/// # #[path = "../examples/error.rs"] mod error; use error::Error;
/// use pin_init::{pin_data, try_pin_init, PinInit, InPlaceInit, init_zeroed};
///
/// #[pin_data]
/// struct BigBuf {
/// big: Box<[u8; 1024 * 1024 * 1024]>,
/// small: [u8; 1024 * 1024],
/// ptr: *mut u8,
/// }
///
/// impl BigBuf {
/// fn new() -> impl PinInit<Self, Error> {
/// try_pin_init!(Self {
/// big: Box::init(init_zeroed())?,
/// small: [0; 1024 * 1024],
/// ptr: core::ptr::null_mut(),
/// }? Error)
/// }
/// }
/// # let _ = Box::pin_init(BigBuf::new());
/// ```
// For a detailed example of how this macro works, see the module documentation of the hidden
// module `macros` inside of `macros.rs`.
#[macro_export]
macro_rules! try_pin_init {
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}? $err:ty) => { }? $err:ty) => {
@ -847,10 +803,10 @@ macro_rules! try_pin_init {
} }
} }
/// Construct an in-place initializer for `struct`s. /// Construct an in-place, fallible initializer for `struct`s.
/// ///
/// This macro defaults the error to [`Infallible`]. If you need a different error, then use /// This macro defaults the error to [`Infallible`]; if you need a different one, write `? Error`
/// [`try_init!`]. /// at the end, after the struct initializer.
/// ///
/// The syntax is identical to [`pin_init!`] and its safety caveats also apply: /// The syntax is identical to [`pin_init!`] and its safety caveats also apply:
/// - `unsafe` code must guarantee either full initialization or return an error and allow /// - `unsafe` code must guarantee either full initialization or return an error and allow
@ -890,52 +846,10 @@ macro_rules! init {
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}) => { }) => {
$crate::try_init!($(&$this in)? $t $(::<$($generics),*>)? { $crate::init!($(&$this in)? $t $(::<$($generics),*>)? {
$($fields)* $($fields)*
}? ::core::convert::Infallible) }? ::core::convert::Infallible)
} };
}
/// Construct an in-place fallible initializer for `struct`s.
///
/// If the initialization can complete without error (or [`Infallible`]), then use
/// [`init!`].
///
/// The syntax is identical to [`try_pin_init!`]. You need to specify a custom error
/// via `? $type` after the `struct` initializer.
/// The safety caveats from [`try_pin_init!`] also apply:
/// - `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.
///
/// # Examples
///
/// ```rust
/// # #![feature(allocator_api)]
/// # use core::alloc::AllocError;
/// # use pin_init::InPlaceInit;
/// use pin_init::{try_init, Init, init_zeroed};
///
/// struct BigBuf {
/// big: Box<[u8; 1024 * 1024 * 1024]>,
/// small: [u8; 1024 * 1024],
/// }
///
/// impl BigBuf {
/// fn new() -> impl Init<Self, AllocError> {
/// try_init!(Self {
/// big: Box::init(init_zeroed())?,
/// small: [0; 1024 * 1024],
/// }? AllocError)
/// }
/// }
/// # let _ = Box::init(BigBuf::new());
/// ```
// For a detailed example of how this macro works, see the module documentation of the hidden
// module `macros` inside of `macros.rs`.
#[macro_export]
macro_rules! try_init {
($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
$($fields:tt)* $($fields:tt)*
}? $err:ty) => { }? $err:ty) => {
@ -1410,14 +1324,14 @@ where
/// fn init_foo() -> impl PinInit<Foo, Error> { /// fn init_foo() -> impl PinInit<Foo, Error> {
/// pin_init_scope(|| { /// pin_init_scope(|| {
/// let bar = lookup_bar()?; /// let bar = lookup_bar()?;
/// Ok(try_pin_init!(Foo { a: bar.a.into(), b: bar.b }? Error)) /// Ok(pin_init!(Foo { a: bar.a.into(), b: bar.b }? Error))
/// }) /// })
/// } /// }
/// ``` /// ```
/// ///
/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the /// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
/// initializer itself will fail with that error. If it returned `Ok`, then it will run the /// initializer itself will fail with that error. If it returned `Ok`, then it will run the
/// initializer returned by the [`try_pin_init!`] invocation. /// initializer returned by the [`pin_init!`] invocation.
pub fn pin_init_scope<T, E, F, I>(make_init: F) -> impl PinInit<T, E> pub fn pin_init_scope<T, E, F, I>(make_init: F) -> impl PinInit<T, E>
where where
F: FnOnce() -> Result<I, E>, F: FnOnce() -> Result<I, E>,
@ -1453,14 +1367,14 @@ where
/// fn init_foo() -> impl Init<Foo, Error> { /// fn init_foo() -> impl Init<Foo, Error> {
/// init_scope(|| { /// init_scope(|| {
/// let bar = lookup_bar()?; /// let bar = lookup_bar()?;
/// Ok(try_init!(Foo { a: bar.a.into(), b: bar.b }? Error)) /// Ok(init!(Foo { a: bar.a.into(), b: bar.b }? Error))
/// }) /// })
/// } /// }
/// ``` /// ```
/// ///
/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the /// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
/// initializer itself will fail with that error. If it returned `Ok`, then it will run the /// initializer itself will fail with that error. If it returned `Ok`, then it will run the
/// initializer returned by the [`try_init!`] invocation. /// initializer returned by the [`init!`] invocation.
pub fn init_scope<T, E, F, I>(make_init: F) -> impl Init<T, E> pub fn init_scope<T, E, F, I>(make_init: F) -> impl Init<T, E>
where where
F: FnOnce() -> Result<I, E>, F: FnOnce() -> Result<I, E>,