self_cell/
lib.rs

1//! # Overview
2//!
3//! `self_cell` provides one macro-rules macro: [`self_cell`]. With this macro
4//! you can create self-referential structs that are safe-to-use in stable Rust,
5//! without leaking the struct internal lifetime.
6//!
7//! In a nutshell, the API looks *roughly* like this:
8//!
9//! ```ignore
10//! // User code:
11//!
12//! self_cell!(
13//!     struct NewStructName {
14//!         owner: Owner,
15//!
16//!         #[covariant]
17//!         dependent: Dependent,
18//!     }
19//!
20//!     impl {Debug}
21//! );
22//!
23//! // Generated by macro:
24//!
25//! struct NewStructName(...);
26//!
27//! impl NewStructName {
28//!     fn new(
29//!         owner: Owner,
30//!         dependent_builder: impl for<'a> ::core::ops::FnOnce(&'a Owner) -> Dependent<'a>
31//!     ) -> NewStructName { ... }
32//!     fn borrow_owner<'a>(&'a self) -> &'a Owner { ... }
33//!     fn borrow_dependent<'a>(&'a self) -> &'a Dependent<'a> { ... }
34//!     [...]
35//!     // See the macro level documentation for a list of all generated functions,
36//!     // and other possible options, e.g. async builder support, section "Generated API".
37//!     
38//! }
39//!
40//! impl Debug for NewStructName { ... }
41//! ```
42//!
43//! Self-referential structs are currently not supported with safe vanilla Rust.
44//! The only reasonable safe alternative is to have the user juggle 2 separate
45//! data structures which is a mess. The library solution ouroboros is expensive
46//! to compile due to its use of procedural macros.
47//!
48//! This alternative is `no_std`, uses no proc-macros, some self contained
49//! unsafe and works on stable Rust, and is miri tested. With a total of less
50//! than 300 lines of implementation code, which consists mostly of type and
51//! trait implementations, this crate aims to be a good minimal solution to the
52//! problem of self-referential structs.
53//!
54//! It has undergone [community code
55//! review](https://users.rust-lang.org/t/experimental-safe-to-use-proc-macro-free-self-referential-structs-in-stable-rust/52775)
56//! from experienced Rust users.
57//!
58//! ### Fast compile times
59//!
60//! ```txt
61//! $ rm -rf target && cargo +nightly build -Z timings
62//!
63//! Compiling self_cell v0.7.0
64//! Completed self_cell v0.7.0 in 0.2s
65//! ```
66//!
67//! Because it does **not** use proc-macros, and has 0 dependencies
68//! compile-times are fast.
69//!
70//! Measurements done on a slow laptop.
71//!
72//! ### A motivating use case
73//!
74//! ```rust
75//! use self_cell::self_cell;
76//!
77//! #[derive(Debug, Eq, PartialEq)]
78//! struct Ast<'a>(pub Vec<&'a str>);
79//!
80//! self_cell!(
81//!     struct AstCell {
82//!         owner: String,
83//!
84//!         #[covariant]
85//!         dependent: Ast,
86//!     }
87//!
88//!     impl {Debug, Eq, PartialEq}
89//! );
90//!
91//! fn build_ast_cell(code: &str) -> AstCell {
92//!     // Create owning String on stack.
93//!     let pre_processed_code = code.trim().to_string();
94//!
95//!     // Move String into AstCell, then build Ast inplace.
96//!     AstCell::new(
97//!        pre_processed_code,
98//!        |code| Ast(code.split(' ').filter(|word| word.len() > 1).collect())
99//!     )
100//! }
101//!
102//! fn main() {
103//!     let ast_cell = build_ast_cell("fox = cat + dog");
104//!
105//!     println!("ast_cell -> {:?}", &ast_cell);
106//!     println!("ast_cell.borrow_owner() -> {:?}", ast_cell.borrow_owner());
107//!     println!("ast_cell.borrow_dependent().0[1] -> {:?}", ast_cell.borrow_dependent().0[1]);
108//! }
109//! ```
110//!
111//! ```txt
112//! $ cargo run
113//!
114//! ast_cell -> AstCell { owner: "fox = cat + dog", dependent: Ast(["fox", "cat", "dog"]) }
115//! ast_cell.borrow_owner() -> "fox = cat + dog"
116//! ast_cell.borrow_dependent().0[1] -> "cat"
117//! ```
118//!
119//! There is no way in safe Rust to have an API like `build_ast_cell`, as soon
120//! as `Ast` depends on stack variables like `pre_processed_code` you can't
121//! return the value out of the function anymore. You could move the
122//! pre-processing into the caller but that gets ugly quickly because you can't
123//! encapsulate things anymore. Note this is a somewhat niche use case,
124//! self-referential structs should only be used when there is no good
125//! alternative.
126//!
127//! Under the hood, it heap allocates a struct which it initializes first by
128//! moving the owner value to it and then using the reference to this now
129//! Pin/Immovable owner to construct the dependent inplace next to it. This
130//! makes it safe to move the generated SelfCell but you have to pay for the
131//! heap allocation.
132//!
133//! See the documentation for [`self_cell`] to dive further into the details.
134//!
135//! Or take a look at the advanced examples:
136//! - [Example how to handle dependent construction that can fail](https://github.com/Voultapher/self_cell/tree/main/examples/fallible_dependent_construction)
137//!
138//! - [How to build a lazy AST with self_cell](https://github.com/Voultapher/self_cell/tree/main/examples/lazy_ast)
139//!
140//! - [How to handle dependents that take a mutable reference](https://github.com/Voultapher/self_cell/tree/main/examples/mut_ref_to_owner_in_builder) see also [`MutBorrow`]
141//!
142//! - [How to use an owner type with lifetime](https://github.com/Voultapher/self_cell/tree/main/examples/owner_with_lifetime)
143//!
144//! - [How to build the dependent with an async function](https://github.com/Voultapher/self_cell/tree/main/examples/async_builder)
145//!
146//! ### Min required rustc version
147//!
148//! By default the minimum required rustc version is 1.51.
149//!
150//! There is an optional feature you can enable called "old_rust" that enables
151//! support down to rustc version 1.36. However this requires polyfilling std
152//! library functionality for older rustc with technically UB versions. Testing
153//! does not show older rustc versions (ab)using this. Use at your own risk.
154//!
155//! The minimum versions are a best effor and may change with any new major
156//! release.
157
158#![no_std]
159
160#[doc(hidden)]
161pub extern crate alloc;
162
163#[doc(hidden)]
164pub mod unsafe_self_cell;
165
166/// This macro declares a new struct of `$StructName` and implements traits
167/// based on `$AutomaticDerive`.
168///
169/// ### Example:
170///
171/// ```rust
172/// use self_cell::self_cell;
173///
174/// #[derive(Debug, Eq, PartialEq)]
175/// struct Ast<'a>(Vec<&'a str>);
176///
177/// self_cell!(
178///     #[doc(hidden)]
179///     struct PackedAstCell {
180///         owner: String,
181///
182///         #[covariant]
183///         dependent: Ast,
184///     }
185///
186///     impl {Debug, PartialEq, Eq, Hash}
187/// );
188/// ```
189///
190/// See the crate overview to get a get an overview and a motivating example.
191///
192/// ### Generated API:
193///
194/// The macro implements these constructors:
195///
196/// ```ignore
197/// fn new(
198///     owner: $Owner,
199///     dependent_builder: impl for<'a> ::core::ops::FnOnce(&'a $Owner) -> $Dependent<'a>
200/// ) -> Self
201/// ```
202///
203/// ```ignore
204/// fn try_new<Err>(
205///     owner: $Owner,
206///     dependent_builder: impl for<'a> ::core::ops::FnOnce(&'a $Owner) -> Result<$Dependent<'a>, Err>
207/// ) -> Result<Self, Err>
208/// ```
209///
210/// ```ignore
211/// fn try_new_or_recover<Err>(
212///     owner: $Owner,
213///     dependent_builder: impl for<'a> ::core::ops::FnOnce(&'a $Owner) -> Result<$Dependent<'a>, Err>
214/// ) -> Result<Self, ($Owner, Err)>
215/// ```
216///
217/// The macro implements these methods:
218///
219/// ```ignore
220/// fn borrow_owner<'a>(&'a self) -> &'a $Owner
221/// ```
222///
223/// ```ignore
224/// // Only available if dependent is covariant.
225/// fn borrow_dependent<'a>(&'a self) -> &'a $Dependent<'a>
226/// ```
227///
228/// ```ignore
229/// fn with_dependent<'outer_fn, Ret>(
230///     &'outer_fn self,
231///     func: impl for<'a> ::core::ops::FnOnce(&'a $Owner, &'outer_fn $Dependent<'a>
232/// ) -> Ret) -> Ret
233/// ```
234///
235/// ```ignore
236/// fn with_dependent_mut<'outer_fn, Ret>(
237///     &'outer_fn mut self,
238///     func: impl for<'a> ::core::ops::FnOnce(&'a $Owner, &'outer_fn mut $Dependent<'a>) -> Ret
239/// ) -> Ret
240/// ```
241///
242/// ```ignore
243/// fn into_owner(self) -> $Owner
244/// ```
245///
246///
247/// ### Parameters:
248///
249/// - `$Vis:vis struct $StructName:ident` Name of the struct that will be
250///   declared, this needs to be unique for the relevant scope. Example: `struct
251///   AstCell` or `pub struct AstCell`. `$Vis` can be used to mark the struct
252///   and all functions implemented by the macro as public.
253///
254///   `$(#[$StructMeta:meta])*` allows you specify further meta items for this
255///   struct, eg. `#[doc(hidden)] struct AstCell`.
256///
257/// - `$Owner:ty` Type of owner. This has to have a `'static` lifetime. Example:
258///   `String`.
259///
260/// - `$Dependent:ident` Name of the dependent type without specified lifetime.
261///   This can't be a nested type name. As workaround either create a type alias
262///   `type Dep<'a> = Option<Vec<&'a str>>;` or create a new-type `struct
263///   Dep<'a>(Option<Vec<&'a str>>);`. Example: `Ast`.
264///
265///   `$Covariance:ident` Marker declaring if `$Dependent` is
266///   [covariant](https://doc.rust-lang.org/nightly/nomicon/subtyping.html).
267///   Possible Values:
268///
269///   * **covariant**: This generates the direct reference accessor function
270///     `borrow_dependent`. This is only safe to do if this compiles `fn
271///     _assert_covariance<'x: 'y, 'y>(x: &'y $Dependent<'x>) -> &'y $Dependent<'y>
272///     {x}`. Otherwise you could choose a lifetime that is too short for types
273///     with interior mutability like `Cell`, which can lead to UB in safe code.
274///     Which would violate the promise of this library that it is safe-to-use.
275///     If you accidentally mark a type that is not covariant as covariant, you
276///     will get a compile time error.
277///
278///   * **not_covariant**: This generates no additional code but you can use the
279///     `with_dependent` function. See [How to build a lazy AST with
280///     self_cell](https://github.com/Voultapher/self_cell/tree/main/examples/lazy_ast)
281///     for a usage example.
282///
283///   In both cases you can use the `with_dependent_mut` function to mutate the
284///   dependent value. This is safe to do because notionally you are replacing
285///   pointers to a value not the other way around.
286///
287///   `#[$Covariance:ident, async_builder]` Optional marker that tells the macro to
288///   generate `async` construction functions. `new`, `try_new` and `try_new_or_recover`
289///   will all be `async` functions taking `async` closures as `dependent_builder`
290///   functions.
291///
292/// - `impl {$($AutomaticDerive:ident),*},` Optional comma separated list of
293///   optional automatic trait implementations. Possible Values:
294///
295///   * **Debug**: Prints the debug representation of owner and dependent.
296///     Example: `AstCell { owner: "fox = cat + dog", dependent: Ast(["fox",
297///     "cat", "dog"]) }`
298///
299///   * **PartialEq**: Logic `*self.borrow_owner() == *other.borrow_owner()`,
300///     this assumes that `Dependent<'a>::From<&'a Owner>` is deterministic, so
301///     that only comparing owner is enough.
302///
303///   * **Eq**: Will implement the trait marker `Eq` for `$StructName`. Beware
304///     if you select this `Eq` will be implemented regardless if `$Owner`
305///     implements `Eq`, that's an unfortunate technical limitation.
306///
307///   * **Hash**: Logic `self.borrow_owner().hash(state);`, this assumes that
308///     `Dependent<'a>::From<&'a Owner>` is deterministic, so that only hashing
309///     owner is enough.
310///
311///   All `AutomaticDerive` are optional and you can implement you own version
312///   of these traits. The declared struct is part of your module and you are
313///   free to implement any trait in any way you want. Access to the unsafe
314///   internals is only possible via unsafe functions, so you can't accidentally
315///   use them in safe code.
316///
317///   There is limited nested cell support. Eg, having an owner with non static
318///   references. Eg `struct ChildCell<'a> { owner: &'a String, ...`. You can
319///   use any lifetime name you want, except `_q` and only a single lifetime is
320///   supported, and can only be used in the owner. Due to macro_rules
321///   limitations, no `AutomaticDerive` are supported if an owner lifetime is
322///   provided.
323///
324#[macro_export]
325macro_rules! self_cell {
326(
327    $(#[$StructMeta:meta])*
328    $Vis:vis struct $StructName:ident $(<$OwnerLifetime:lifetime>)? {
329        owner: $Owner:ty,
330
331
332        #[$Covariance:ident $(, $AsyncBuilder:ident)?]
333        dependent: $Dependent:ident,
334    }
335
336    $(impl {$($AutomaticDerive:ident),*})?
337) => {
338    #[repr(transparent)]
339    $(#[$StructMeta])*
340    $Vis struct $StructName $(<$OwnerLifetime>)? {
341        unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell<
342            $StructName$(<$OwnerLifetime>)?,
343            $Owner,
344            $Dependent<'static>
345        >,
346
347        $(owner_marker: $crate::_covariant_owner_marker!($Covariance, $OwnerLifetime) ,)?
348    }
349
350    impl <$($OwnerLifetime)?> $StructName <$($OwnerLifetime)?> {
351        $crate::_self_cell_new!($Vis, $Owner $(=> $OwnerLifetime)?, $Dependent $(, $AsyncBuilder)?);
352
353        $crate::_self_cell_try_new!($Vis, $Owner $(=> $OwnerLifetime)?, $Dependent $(, $AsyncBuilder)?);
354
355        $crate::_self_cell_try_new_or_recover!($Vis, $Owner $(=> $OwnerLifetime)?, $Dependent $(, $AsyncBuilder)?);
356
357        /// Borrows owner.
358        $Vis fn borrow_owner<'_q>(&'_q self) -> &'_q $Owner {
359            unsafe { self.unsafe_self_cell.borrow_owner::<$Dependent<'_q>>() }
360        }
361
362        /// Calls given closure `func` with a shared reference to dependent.
363        $Vis fn with_dependent<'outer_fn, Ret>(
364            &'outer_fn self,
365            func: impl for<'_q> ::core::ops::FnOnce(&'_q $Owner, &'outer_fn $Dependent<'_q>
366        ) -> Ret) -> Ret {
367            unsafe {
368                func(
369                    self.unsafe_self_cell.borrow_owner::<$Dependent>(),
370                    self.unsafe_self_cell.borrow_dependent()
371                )
372            }
373        }
374
375        /// Calls given closure `func` with an unique reference to dependent.
376        $Vis fn with_dependent_mut<'outer_fn, Ret>(
377            &'outer_fn mut self,
378            func: impl for<'_q> ::core::ops::FnOnce(&'_q $Owner, &'outer_fn mut $Dependent<'_q>) -> Ret
379        ) -> Ret {
380            let (owner, dependent) = unsafe {
381                    self.unsafe_self_cell.borrow_mut()
382            };
383
384            func(owner, dependent)
385        }
386
387        $crate::_covariant_access!($Covariance, $Vis, $Dependent);
388
389        /// Consumes `self` and returns the the owner.
390        $Vis fn into_owner(self) -> $Owner {
391            // This is only safe to do with repr(transparent).
392            let unsafe_self_cell = unsafe { ::core::mem::transmute::<
393                Self,
394                $crate::unsafe_self_cell::UnsafeSelfCell<
395                    $StructName$(<$OwnerLifetime>)?,
396                    $Owner,
397                    $Dependent<'static>
398                >
399            >(self) };
400
401            let owner = unsafe { unsafe_self_cell.into_owner::<$Dependent>() };
402
403            owner
404        }
405    }
406
407    impl $(<$OwnerLifetime>)? Drop for $StructName $(<$OwnerLifetime>)? {
408        fn drop(&mut self) {
409            unsafe {
410                self.unsafe_self_cell.drop_joined::<$Dependent>();
411            }
412        }
413    }
414
415    // The user has to choose which traits can and should be automatically
416    // implemented for the cell.
417    $($(
418        $crate::_impl_automatic_derive!($AutomaticDerive, $StructName);
419    )*)*
420};
421}
422
423#[doc(hidden)]
424#[macro_export]
425macro_rules! _covariant_access {
426    (covariant, $Vis:vis, $Dependent:ident) => {
427        /// Borrows dependent.
428        $Vis fn borrow_dependent<'_q>(&'_q self) -> &'_q $Dependent<'_q> {
429            fn _assert_covariance<'x: 'y, 'y>(x: &'y $Dependent<'x>) -> &'y $Dependent<'y> {
430                //  This function only compiles for covariant types.
431                x // Change the macro invocation to not_covariant.
432            }
433
434            unsafe { self.unsafe_self_cell.borrow_dependent() }
435        }
436    };
437    (not_covariant, $Vis:vis, $Dependent:ident) => {
438        // For types that are not covariant it's unsafe to allow
439        // returning direct references.
440        // For example a lifetime that is too short could be chosen:
441        // See https://github.com/Voultapher/self_cell/issues/5
442    };
443    ($x:ident, $Vis:vis, $Dependent:ident) => {
444        compile_error!("This macro only accepts `covariant` or `not_covariant`");
445    };
446}
447
448#[doc(hidden)]
449#[macro_export]
450macro_rules! _covariant_owner_marker {
451    (covariant, $OwnerLifetime:lifetime) => {
452        // Ensure that contravariant owners don't imply covariance
453        // over the dependent. See issue https://github.com/Voultapher/self_cell/issues/18
454        ::core::marker::PhantomData<&$OwnerLifetime ()>
455    };
456    (not_covariant, $OwnerLifetime:lifetime) => {
457        // See the discussion in https://github.com/Voultapher/self_cell/pull/29
458        //
459        // If the dependent is non_covariant, mark the owner as invariant over its
460        // lifetime. Otherwise unsound use is possible.
461        ::core::marker::PhantomData<fn(&$OwnerLifetime ()) -> &$OwnerLifetime ()>
462    };
463    ($x:ident, $OwnerLifetime:lifetime) => {
464        compile_error!("This macro only accepts `covariant` or `not_covariant`");
465    };
466}
467
468#[doc(hidden)]
469#[macro_export]
470macro_rules! _covariant_owner_marker_ctor {
471    ($OwnerLifetime:lifetime) => {
472        // Helper to optionally expand into PhantomData for construction.
473        ::core::marker::PhantomData
474    };
475}
476
477#[doc(hidden)]
478#[macro_export]
479macro_rules! _self_cell_new {
480    ($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident) => {
481        /// Constructs a new self-referential struct.
482        ///
483        /// The provided `owner` will be moved into a heap allocated box. Followed by construction
484        /// of the dependent value, by calling `dependent_builder` with a shared reference to the
485        /// owner that remains valid for the lifetime of the constructed struct.
486        $Vis fn new(
487            owner: $Owner,
488            dependent_builder: impl for<'_q> ::core::ops::FnOnce(&'_q $Owner) -> $Dependent<'_q>
489        ) -> Self {
490            type JoinedCell<'_q $(, $OwnerLifetime)?> =
491                    $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>;
492
493            // unsafe placed here to make sure the body macro can't be abused.
494            unsafe {
495                $crate::_self_cell_new_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder)
496            }
497        }
498    };
499    ($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident, async_builder) => {
500        /// Constructs a new self-referential struct.
501        ///
502        /// The provided `owner` will be moved into a heap allocated box. Followed by construction
503        /// of the dependent value, by calling the async closure `dependent_builder` with a shared
504        /// reference to the owner that remains valid for the lifetime of the constructed struct.
505        $Vis async fn new(
506            owner: $Owner,
507            dependent_builder: impl for<'_q> ::core::ops::AsyncFnOnce(&'_q $Owner) -> $Dependent<'_q>
508        ) -> Self {
509            type JoinedCell<'_q $(, $OwnerLifetime)?> =
510                    $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>;
511
512            // unsafe placed here to make sure the body macro can't be abused.
513            unsafe {
514                $crate::_self_cell_new_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder, async_builder)
515            }
516        }
517    };
518    ($Vis:vis, $Owner:ty, $Dependent:ident, $x:ident) => {
519        compile_error!("This macro only accepts `async_builder`");
520    };
521}
522
523#[doc(hidden)]
524#[macro_export]
525macro_rules! _self_cell_new_body {
526    ($JoinedCell:ty, $owner:expr $(=> $OwnerLifetime:lifetime)?, $dependent_builder:expr $(, $AsyncBuilder:ident)?) => {{
527        // All this has to happen here, because there is not good way
528        // of passing the appropriate logic into UnsafeSelfCell::new
529        // short of assuming Dependent<'static> is the same as
530        // Dependent<'_q>, which I'm not confident is safe.
531
532        // For this API to be safe there has to be no safe way to
533        // capture additional references in `dependent_builder` and then
534        // return them as part of Dependent. Eg. it should be impossible
535        // to express: '_q should outlive 'x here `fn
536        // bad<'_q>(outside_ref: &'_q String) -> impl for<'x> ::core::ops::FnOnce(&'x
537        // Owner) -> Dependent<'x>`.
538
539        let layout = $crate::alloc::alloc::Layout::new::<$JoinedCell>();
540        assert!(layout.size() != 0);
541
542        let joined_void_ptr = ::core::ptr::NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap();
543
544        let mut joined_ptr = joined_void_ptr.cast::<$JoinedCell>();
545
546        let (owner_ptr, dependent_ptr) = <$JoinedCell>::_field_pointers(joined_ptr.as_ptr());
547
548        // Move owner into newly allocated space.
549        owner_ptr.write($owner);
550
551        // Drop guard that cleans up should building the dependent panic.
552        let drop_guard =
553            $crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr);
554
555        // Initialize dependent with owner reference in final place.
556        dependent_ptr.write($crate::_await_opt!($dependent_builder(&*owner_ptr) $(, $AsyncBuilder)?));
557        ::core::mem::forget(drop_guard);
558
559        Self {
560            unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new(
561                joined_void_ptr,
562            ),
563            $(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)?
564        }
565    }}
566}
567
568#[doc(hidden)]
569#[macro_export]
570macro_rules! _self_cell_try_new {
571    ($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident) => {
572        /// Constructs a new self-referential struct or returns an error.
573        ///
574        /// Consumes owner on error.
575        $Vis fn try_new<Err>(
576            owner: $Owner,
577            dependent_builder:
578                impl for<'_q> ::core::ops::FnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err>
579        ) -> ::core::result::Result<Self, Err> {
580            type JoinedCell<'_q $(, $OwnerLifetime)?> =
581                    $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>;
582
583            // unsafe placed here to make sure the body macro can't be abused.
584            unsafe {
585                $crate::_self_cell_try_new_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder)
586            }
587        }
588    };
589    ($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident, async_builder) => {
590        /// Constructs a new self-referential struct or returns an error.
591        ///
592        /// Consumes owner on error.
593        $Vis async fn try_new<Err>(
594            owner: $Owner,
595            dependent_builder:
596                impl for<'_q> ::core::ops::AsyncFnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err>
597        ) -> ::core::result::Result<Self, Err> {
598            type JoinedCell<'_q $(, $OwnerLifetime)?> =
599                    $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>;
600
601            // unsafe placed here to make sure the body macro can't be abused.
602            unsafe {
603                $crate::_self_cell_try_new_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder, async_builder)
604            }
605        }
606    };
607    ($Vis:vis, $Owner:ty, $Dependent:ident, $x:ident) => {
608        compile_error!("This macro only accepts `async_builder`");
609    };
610}
611
612#[doc(hidden)]
613#[macro_export]
614macro_rules! _self_cell_try_new_body {
615    ($JoinedCell:ty, $owner:expr $(=> $OwnerLifetime:lifetime)?, $dependent_builder:expr $(, $AsyncBuilder:ident)?) => {{
616        // See fn new for more explanation.
617
618        let layout = $crate::alloc::alloc::Layout::new::<$JoinedCell>();
619        assert!(layout.size() != 0);
620
621        let joined_void_ptr = ::core::ptr::NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap();
622
623        let mut joined_ptr = joined_void_ptr.cast::<$JoinedCell>();
624
625        let (owner_ptr, dependent_ptr) = <$JoinedCell>::_field_pointers(joined_ptr.as_ptr());
626
627        // Move owner into newly allocated space.
628        owner_ptr.write($owner);
629
630        // Drop guard that cleans up should building the dependent panic.
631        let mut drop_guard =
632            $crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr);
633
634        match $crate::_await_opt!($dependent_builder(&*owner_ptr) $(, $AsyncBuilder)?) {
635            ::core::result::Result::Ok(dependent) => {
636                dependent_ptr.write(dependent);
637                ::core::mem::forget(drop_guard);
638
639                ::core::result::Result::Ok(Self {
640                    unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new(
641                        joined_void_ptr,
642                    ),
643                    $(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)?
644                })
645            }
646            ::core::result::Result::Err(err) => ::core::result::Result::Err(err)
647        }
648    }}
649}
650
651#[doc(hidden)]
652#[macro_export]
653macro_rules! _self_cell_try_new_or_recover {
654    ($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident) => {
655        /// Constructs a new self-referential struct or returns an error.
656        ///
657        /// Returns owner and error as tuple on error.
658        $Vis fn try_new_or_recover<Err>(
659            owner: $Owner,
660            dependent_builder:
661                impl for<'_q> ::core::ops::FnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err>
662    ) -> ::core::result::Result<Self, ($Owner, Err)> {
663            type JoinedCell<'_q $(, $OwnerLifetime)?> =
664                    $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>;
665
666            // unsafe placed here to make sure the body macro can't be abused.
667            unsafe {
668                $crate::_self_cell_try_new_or_recover_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder)
669            }
670        }
671    };
672    ($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident, async_builder) => {
673        /// Constructs a new self-referential struct or returns an error.
674        ///
675        /// Returns owner and error as tuple on error.
676        $Vis async fn try_new_or_recover<Err>(
677            owner: $Owner,
678            dependent_builder:
679                impl for<'_q> ::core::ops::AsyncFnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err>
680        ) -> ::core::result::Result<Self, ($Owner, Err)> {
681            type JoinedCell<'_q $(, $OwnerLifetime)?> =
682                    $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>;
683
684            // unsafe placed here to make sure the body macro can't be abused.
685            unsafe {
686                $crate::_self_cell_try_new_or_recover_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder, async_builder)
687            }
688        }
689    };
690    ($Vis:vis, $Owner:ty, $Dependent:ident, $x:ident) => {
691        compile_error!("This macro only accepts `async_builder`");
692    };
693}
694
695#[doc(hidden)]
696#[macro_export]
697macro_rules! _self_cell_try_new_or_recover_body {
698    ($JoinedCell:ty, $owner:expr $(=> $OwnerLifetime:lifetime)?, $dependent_builder:expr $(, $AsyncBuilder:ident)?) => {{
699        let layout = $crate::alloc::alloc::Layout::new::<$JoinedCell>();
700        assert!(layout.size() != 0);
701
702        let joined_void_ptr = ::core::ptr::NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap();
703
704        let mut joined_ptr = joined_void_ptr.cast::<$JoinedCell>();
705
706        let (owner_ptr, dependent_ptr) = <$JoinedCell>::_field_pointers(joined_ptr.as_ptr());
707
708        // Move owner into newly allocated space.
709        owner_ptr.write($owner);
710
711        // Drop guard that cleans up should building the dependent panic.
712        let mut drop_guard =
713            $crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr);
714
715        match $crate::_await_opt!($dependent_builder(&*owner_ptr) $(, $AsyncBuilder)?) {
716            ::core::result::Result::Ok(dependent) => {
717                dependent_ptr.write(dependent);
718                ::core::mem::forget(drop_guard);
719
720                ::core::result::Result::Ok(Self {
721                    unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new(
722                        joined_void_ptr,
723                    ),
724                    $(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)?
725                })
726            }
727            ::core::result::Result::Err(err) => {
728                // In contrast to into_owner ptr::read, here no dependent
729                // ever existed in this function and so we are sure its
730                // drop impl can't access owner after the read.
731                // And err can't return a reference to owner.
732                let owner_on_err = ::core::ptr::read(owner_ptr);
733
734                // Allowing drop_guard to finish would let it double free owner.
735                // So we dealloc the JoinedCell here manually.
736                ::core::mem::forget(drop_guard);
737                $crate::alloc::alloc::dealloc(joined_void_ptr.as_ptr(), layout);
738
739                ::core::result::Result::Err((owner_on_err, err))
740            }
741        }
742    }}
743}
744
745#[doc(hidden)]
746#[macro_export]
747macro_rules! _await_opt {
748    ($val:expr) => {
749        $val
750    };
751    ($future:expr, async_builder) => {
752        $future.await
753    };
754    ($v:expr, $x:ident) => {
755        compile_error!("This macro only accepts `async_builder`");
756    };
757}
758
759#[doc(hidden)]
760#[macro_export]
761macro_rules! _impl_automatic_derive {
762    (Debug, $StructName:ident) => {
763        impl ::core::fmt::Debug for $StructName {
764            fn fmt(
765                &self,
766                fmt: &mut ::core::fmt::Formatter,
767            ) -> ::core::result::Result<(), ::core::fmt::Error> {
768                self.with_dependent(|owner, dependent| {
769                    fmt.debug_struct(stringify!($StructName))
770                        .field("owner", owner)
771                        .field("dependent", dependent)
772                        .finish()
773                })
774            }
775        }
776    };
777    (PartialEq, $StructName:ident) => {
778        impl ::core::cmp::PartialEq for $StructName {
779            fn eq(&self, other: &Self) -> bool {
780                *self.borrow_owner() == *other.borrow_owner()
781            }
782        }
783    };
784    (Eq, $StructName:ident) => {
785        // TODO this should only be allowed if owner is Eq.
786        impl ::core::cmp::Eq for $StructName {}
787    };
788    (Hash, $StructName:ident) => {
789        impl ::core::hash::Hash for $StructName {
790            fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
791                self.borrow_owner().hash(state);
792            }
793        }
794    };
795    ($x:ident, $StructName:ident) => {
796        compile_error!(concat!(
797            "No automatic trait impl for trait: ",
798            stringify!($x)
799        ));
800    };
801}
802
803pub use unsafe_self_cell::MutBorrow;