| 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 effort and may change with any new major |
| 156 |
//! release. |
| 157 |
|
| 158 |
#![no_std] |
| 159 |
|
| 160 |
#[doc(hidden)] |
| 161 |
pub extern crate alloc; |
| 162 |
|
| 163 |
#[doc(hidden)] |
| 164 |
pub 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 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 your 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] |
| 325 |
macro_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 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] |
| 425 |
macro_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] |
| 450 |
macro_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] |
| 470 |
macro_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] |
| 479 |
macro_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] |
| 525 |
macro_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 joined_ptr = joined_void_ptr.cast::<$JoinedCell>(); |
| 545 |
|
| 546 |
let (owner_ptr, dependent_ptr) = <$JoinedCell>::_field_pointers(joined_ptr.as_ptr()); |
| 547 |
|
| 548 |
// SAFETY: We are the only ones controlling the write timing of `dependent_ptr_send` |
| 549 |
// and it is sequential. |
| 550 |
let dependent_ptr_send = |
| 551 |
$crate::unsafe_self_cell::SendMutPtr::new(dependent_ptr); |
| 552 |
let joined_void_ptr_send = |
| 553 |
$crate::unsafe_self_cell::SendMutPtr::new(joined_void_ptr.as_ptr()); |
| 554 |
|
| 555 |
// Move owner into newly allocated space. |
| 556 |
owner_ptr.write($owner); |
| 557 |
|
| 558 |
// Drop guard that cleans up should building the dependent panic. |
| 559 |
let drop_guard = |
| 560 |
$crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
| 561 |
|
| 562 |
// Initialize dependent with owner reference in final place. |
| 563 |
dependent_ptr_send.write($crate::_await_opt!($dependent_builder(&*owner_ptr) $(, $AsyncBuilder)?)); |
| 564 |
|
| 565 |
::core::mem::forget(drop_guard); |
| 566 |
|
| 567 |
Self { |
| 568 |
unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
| 569 |
// SAFETY: `joined_void_ptr_send` becomes part of `UnsafeSelfCell`, which doesn't do |
| 570 |
// any direct writes to the pointer, so it can't race them, even though the user |
| 571 |
// get's control over the value. |
| 572 |
joined_void_ptr_send.into_non_null().unwrap(), |
| 573 |
), |
| 574 |
$(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
| 575 |
} |
| 576 |
}} |
| 577 |
} |
| 578 |
|
| 579 |
#[doc(hidden)] |
| 580 |
#[macro_export] |
| 581 |
macro_rules! _self_cell_try_new { |
| 582 |
($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident) => { |
| 583 |
/// Constructs a new self-referential struct or returns an error. |
| 584 |
/// |
| 585 |
/// Consumes owner on error. |
| 586 |
$Vis fn try_new<Err>( |
| 587 |
owner: $Owner, |
| 588 |
dependent_builder: |
| 589 |
impl for<'_q> ::core::ops::FnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err> |
| 590 |
) -> ::core::result::Result<Self, Err> { |
| 591 |
type JoinedCell<'_q $(, $OwnerLifetime)?> = |
| 592 |
$crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
| 593 |
|
| 594 |
// unsafe placed here to make sure the body macro can't be abused. |
| 595 |
unsafe { |
| 596 |
$crate::_self_cell_try_new_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder) |
| 597 |
} |
| 598 |
} |
| 599 |
}; |
| 600 |
($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident, async_builder) => { |
| 601 |
/// Constructs a new self-referential struct or returns an error. |
| 602 |
/// |
| 603 |
/// Consumes owner on error. |
| 604 |
$Vis async fn try_new<Err>( |
| 605 |
owner: $Owner, |
| 606 |
dependent_builder: |
| 607 |
impl for<'_q> ::core::ops::AsyncFnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err> |
| 608 |
) -> ::core::result::Result<Self, Err> { |
| 609 |
type JoinedCell<'_q $(, $OwnerLifetime)?> = |
| 610 |
$crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
| 611 |
|
| 612 |
// unsafe placed here to make sure the body macro can't be abused. |
| 613 |
unsafe { |
| 614 |
$crate::_self_cell_try_new_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder, async_builder) |
| 615 |
} |
| 616 |
} |
| 617 |
}; |
| 618 |
($Vis:vis, $Owner:ty, $Dependent:ident, $x:ident) => { |
| 619 |
compile_error!("This macro only accepts `async_builder`"); |
| 620 |
}; |
| 621 |
} |
| 622 |
|
| 623 |
#[doc(hidden)] |
| 624 |
#[macro_export] |
| 625 |
macro_rules! _self_cell_try_new_body { |
| 626 |
($JoinedCell:ty, $owner:expr $(=> $OwnerLifetime:lifetime)?, $dependent_builder:expr $(, $AsyncBuilder:ident)?) => {{ |
| 627 |
// See fn new for more explanation. |
| 628 |
|
| 629 |
let layout = $crate::alloc::alloc::Layout::new::<$JoinedCell>(); |
| 630 |
assert!(layout.size() != 0); |
| 631 |
|
| 632 |
let joined_void_ptr = ::core::ptr::NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
| 633 |
|
| 634 |
let joined_ptr = joined_void_ptr.cast::<$JoinedCell>(); |
| 635 |
|
| 636 |
let (owner_ptr, dependent_ptr) = <$JoinedCell>::_field_pointers(joined_ptr.as_ptr()); |
| 637 |
|
| 638 |
// SAFETY: We are the only ones controlling the write timing of `dependent_ptr_send` |
| 639 |
// and it is sequential. |
| 640 |
let dependent_ptr_send = |
| 641 |
$crate::unsafe_self_cell::SendMutPtr::new(dependent_ptr); |
| 642 |
let joined_void_ptr_send = |
| 643 |
$crate::unsafe_self_cell::SendMutPtr::new(joined_void_ptr.as_ptr()); |
| 644 |
|
| 645 |
// Move owner into newly allocated space. |
| 646 |
owner_ptr.write($owner); |
| 647 |
|
| 648 |
// Drop guard that cleans up should building the dependent panic. |
| 649 |
let mut drop_guard = |
| 650 |
$crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
| 651 |
|
| 652 |
match $crate::_await_opt!($dependent_builder(&*owner_ptr) $(, $AsyncBuilder)?) { |
| 653 |
::core::result::Result::Ok(dependent) => { |
| 654 |
dependent_ptr_send.write(dependent); |
| 655 |
|
| 656 |
::core::mem::forget(drop_guard); |
| 657 |
|
| 658 |
::core::result::Result::Ok(Self { |
| 659 |
unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
| 660 |
joined_void_ptr_send.into_non_null().unwrap(), |
| 661 |
), |
| 662 |
$(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
| 663 |
}) |
| 664 |
} |
| 665 |
::core::result::Result::Err(err) => ::core::result::Result::Err(err) |
| 666 |
} |
| 667 |
}} |
| 668 |
} |
| 669 |
|
| 670 |
#[doc(hidden)] |
| 671 |
#[macro_export] |
| 672 |
macro_rules! _self_cell_try_new_or_recover { |
| 673 |
($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident) => { |
| 674 |
/// Constructs a new self-referential struct or returns an error. |
| 675 |
/// |
| 676 |
/// Returns owner and error as tuple on error. |
| 677 |
$Vis fn try_new_or_recover<Err>( |
| 678 |
owner: $Owner, |
| 679 |
dependent_builder: |
| 680 |
impl for<'_q> ::core::ops::FnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err> |
| 681 |
) -> ::core::result::Result<Self, ($Owner, Err)> { |
| 682 |
type JoinedCell<'_q $(, $OwnerLifetime)?> = |
| 683 |
$crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
| 684 |
|
| 685 |
// unsafe placed here to make sure the body macro can't be abused. |
| 686 |
unsafe { |
| 687 |
$crate::_self_cell_try_new_or_recover_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder) |
| 688 |
} |
| 689 |
} |
| 690 |
}; |
| 691 |
($Vis:vis, $Owner:ty $(=> $OwnerLifetime:lifetime)?, $Dependent:ident, async_builder) => { |
| 692 |
/// Constructs a new self-referential struct or returns an error. |
| 693 |
/// |
| 694 |
/// Returns owner and error as tuple on error. |
| 695 |
$Vis async fn try_new_or_recover<Err>( |
| 696 |
owner: $Owner, |
| 697 |
dependent_builder: |
| 698 |
impl for<'_q> ::core::ops::AsyncFnOnce(&'_q $Owner) -> ::core::result::Result<$Dependent<'_q>, Err> |
| 699 |
) -> ::core::result::Result<Self, ($Owner, Err)> { |
| 700 |
type JoinedCell<'_q $(, $OwnerLifetime)?> = |
| 701 |
$crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
| 702 |
|
| 703 |
// unsafe placed here to make sure the body macro can't be abused. |
| 704 |
unsafe { |
| 705 |
$crate::_self_cell_try_new_or_recover_body!(JoinedCell, owner $(=> $OwnerLifetime)?, dependent_builder, async_builder) |
| 706 |
} |
| 707 |
} |
| 708 |
}; |
| 709 |
($Vis:vis, $Owner:ty, $Dependent:ident, $x:ident) => { |
| 710 |
compile_error!("This macro only accepts `async_builder`"); |
| 711 |
}; |
| 712 |
} |
| 713 |
|
| 714 |
#[doc(hidden)] |
| 715 |
#[macro_export] |
| 716 |
macro_rules! _self_cell_try_new_or_recover_body { |
| 717 |
($JoinedCell:ty, $owner:expr $(=> $OwnerLifetime:lifetime)?, $dependent_builder:expr $(, $AsyncBuilder:ident)?) => {{ |
| 718 |
let layout = $crate::alloc::alloc::Layout::new::<$JoinedCell>(); |
| 719 |
assert!(layout.size() != 0); |
| 720 |
|
| 721 |
let joined_void_ptr = ::core::ptr::NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
| 722 |
|
| 723 |
let joined_ptr = joined_void_ptr.cast::<$JoinedCell>(); |
| 724 |
|
| 725 |
let (owner_ptr, dependent_ptr) = <$JoinedCell>::_field_pointers(joined_ptr.as_ptr()); |
| 726 |
|
| 727 |
// SAFETY: We are the only ones controlling the write timing of `dependent_ptr_send` |
| 728 |
// and it is sequential. |
| 729 |
let owner_ptr_send = |
| 730 |
$crate::unsafe_self_cell::SendMutPtr::new(owner_ptr); |
| 731 |
let dependent_ptr_send = |
| 732 |
$crate::unsafe_self_cell::SendMutPtr::new(dependent_ptr); |
| 733 |
let joined_void_ptr_send = |
| 734 |
$crate::unsafe_self_cell::SendMutPtr::new(joined_void_ptr.as_ptr()); |
| 735 |
|
| 736 |
// Move owner into newly allocated space. |
| 737 |
owner_ptr.write($owner); |
| 738 |
|
| 739 |
// Drop guard that cleans up should building the dependent panic. |
| 740 |
let mut drop_guard = |
| 741 |
$crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
| 742 |
|
| 743 |
match $crate::_await_opt!($dependent_builder(&*owner_ptr) $(, $AsyncBuilder)?) { |
| 744 |
::core::result::Result::Ok(dependent) => { |
| 745 |
dependent_ptr_send.write(dependent); |
| 746 |
|
| 747 |
::core::mem::forget(drop_guard); |
| 748 |
|
| 749 |
::core::result::Result::Ok(Self { |
| 750 |
unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
| 751 |
joined_void_ptr_send.into_non_null().unwrap(), |
| 752 |
), |
| 753 |
$(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
| 754 |
}) |
| 755 |
} |
| 756 |
::core::result::Result::Err(err) => { |
| 757 |
// In contrast to into_owner ptr::read, here no dependent |
| 758 |
// ever existed in this function and so we are sure its |
| 759 |
// drop impl can't access owner after the read. |
| 760 |
// And err can't return a reference to owner. |
| 761 |
let owner_on_err = owner_ptr_send.read(); |
| 762 |
|
| 763 |
// Allowing drop_guard to finish would let it double free owner. |
| 764 |
// So we dealloc the JoinedCell here manually. |
| 765 |
::core::mem::forget(drop_guard); |
| 766 |
|
| 767 |
// SAFETY: This is a kind of write to the pointer, which is Send because we are the |
| 768 |
// only ones with access to it. |
| 769 |
joined_void_ptr_send.dealloc(layout); |
| 770 |
|
| 771 |
::core::result::Result::Err((owner_on_err, err)) |
| 772 |
} |
| 773 |
} |
| 774 |
}} |
| 775 |
} |
| 776 |
|
| 777 |
#[doc(hidden)] |
| 778 |
#[macro_export] |
| 779 |
macro_rules! _await_opt { |
| 780 |
($val:expr) => { |
| 781 |
$val |
| 782 |
}; |
| 783 |
($future:expr, async_builder) => { |
| 784 |
$future.await |
| 785 |
}; |
| 786 |
($v:expr, $x:ident) => { |
| 787 |
compile_error!("This macro only accepts `async_builder`"); |
| 788 |
}; |
| 789 |
} |
| 790 |
|
| 791 |
#[doc(hidden)] |
| 792 |
#[macro_export] |
| 793 |
macro_rules! _impl_automatic_derive { |
| 794 |
(Debug, $StructName:ident) => { |
| 795 |
impl ::core::fmt::Debug for $StructName { |
| 796 |
fn fmt( |
| 797 |
&self, |
| 798 |
fmt: &mut ::core::fmt::Formatter, |
| 799 |
) -> ::core::result::Result<(), ::core::fmt::Error> { |
| 800 |
self.with_dependent(|owner, dependent| { |
| 801 |
fmt.debug_struct(stringify!($StructName)) |
| 802 |
.field("owner", owner) |
| 803 |
.field("dependent", dependent) |
| 804 |
.finish() |
| 805 |
}) |
| 806 |
} |
| 807 |
} |
| 808 |
}; |
| 809 |
(PartialEq, $StructName:ident) => { |
| 810 |
impl ::core::cmp::PartialEq for $StructName { |
| 811 |
fn eq(&self, other: &Self) -> bool { |
| 812 |
*self.borrow_owner() == *other.borrow_owner() |
| 813 |
} |
| 814 |
} |
| 815 |
}; |
| 816 |
(Eq, $StructName:ident) => { |
| 817 |
// TODO this should only be allowed if owner is Eq. |
| 818 |
impl ::core::cmp::Eq for $StructName {} |
| 819 |
}; |
| 820 |
(Hash, $StructName:ident) => { |
| 821 |
impl ::core::hash::Hash for $StructName { |
| 822 |
fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) { |
| 823 |
self.borrow_owner().hash(state); |
| 824 |
} |
| 825 |
} |
| 826 |
}; |
| 827 |
($x:ident, $StructName:ident) => { |
| 828 |
compile_error!(concat!( |
| 829 |
"No automatic trait impl for trait: ", |
| 830 |
stringify!($x) |
| 831 |
)); |
| 832 |
}; |
| 833 |
} |
| 834 |
|
| 835 |
pub use unsafe_self_cell::MutBorrow; |