mirror of
https://github.com/rust-lang/rust.git
synced 2024-10-31 06:22:00 +00:00
Add a stack-pin!
-ning macro to the pin
module.
Add a type annotation to improve error messages with type mismatches Add a link to the temporary-lifetime-extension section of the reference
This commit is contained in:
parent
b321742c6c
commit
ee9cd7bb6a
@ -909,3 +909,245 @@ impl<P, U> CoerceUnsized<Pin<U>> for Pin<P> where P: CoerceUnsized<U> {}
|
||||
|
||||
#[stable(feature = "pin", since = "1.33.0")]
|
||||
impl<P, U> DispatchFromDyn<Pin<U>> for Pin<P> where P: DispatchFromDyn<U> {}
|
||||
|
||||
/// Constructs a <code>[Pin]<[&mut] T></code>, by pinning[^1] a `value: T` _locally_[^2]
|
||||
/// (≠ [in the heap][`Box::pin`]).
|
||||
///
|
||||
/// [^1]: If the (type `T` of the) given value does not implement [`Unpin`], then this
|
||||
/// effectively pins the `value` in memory, where it will be unable to be moved.
|
||||
/// Otherwise, <code>[Pin]<[&mut] T></code> behaves like <code>[&mut] T</code>, and operations such
|
||||
/// as [`mem::replace()`][crate::mem::replace] will allow extracting that value, and therefore,
|
||||
/// moving it.
|
||||
/// See [the `Unpin` section of the `pin` module][self#unpin] for more info.
|
||||
///
|
||||
/// [^2]: This is usually dubbed "stack"-pinning. And whilst local values are almost always located
|
||||
/// in the stack (_e.g._, when within the body of a non-`async` function), the truth is that inside
|
||||
/// the body of an `async fn` or block —more generally, the body of a generator— any locals crossing
|
||||
/// an `.await` point —a `yield` point— end up being part of the state captured by the `Future` —by
|
||||
/// the `Generator`—, and thus will be stored wherever that one is.
|
||||
///
|
||||
/// ## Examples
|
||||
///
|
||||
/// ### Basic usage
|
||||
///
|
||||
/// ```rust
|
||||
/// #![feature(pin_macro)]
|
||||
/// # use core::marker::PhantomPinned as Foo;
|
||||
/// use core::pin::{pin, Pin};
|
||||
///
|
||||
/// fn stuff(foo: Pin<&mut Foo>) {
|
||||
/// // …
|
||||
/// # let _ = foo;
|
||||
/// }
|
||||
///
|
||||
/// let pinned_foo = pin!(Foo { /* … */ });
|
||||
/// stuff(pinned_foo);
|
||||
/// // or, directly:
|
||||
/// stuff(pin!(Foo { /* … */ }));
|
||||
/// ```
|
||||
///
|
||||
/// ### Manually polling a `Future` (wihout `Unpin` bounds)
|
||||
///
|
||||
/// ```rust
|
||||
/// #![feature(pin_macro)]
|
||||
/// use std::{
|
||||
/// future::Future,
|
||||
/// pin::pin,
|
||||
/// task::{Context, Poll},
|
||||
/// thread,
|
||||
/// };
|
||||
/// # use std::{sync::Arc, task::Wake, thread::Thread};
|
||||
///
|
||||
/// # /// A waker that wakes up the current thread when called.
|
||||
/// # struct ThreadWaker(Thread);
|
||||
/// #
|
||||
/// # impl Wake for ThreadWaker {
|
||||
/// # fn wake(self: Arc<Self>) {
|
||||
/// # self.0.unpark();
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// /// Runs a future to completion.
|
||||
/// fn block_on<Fut: Future>(fut: Fut) -> Fut::Output {
|
||||
/// let waker_that_unparks_thread = // …
|
||||
/// # Arc::new(ThreadWaker(thread::current())).into();
|
||||
/// let mut cx = Context::from_waker(&waker_that_unparks_thread);
|
||||
/// // Pin the future so it can be polled.
|
||||
/// let mut pinned_fut = pin!(fut);
|
||||
/// loop {
|
||||
/// match pinned_fut.as_mut().poll(&mut cx) {
|
||||
/// Poll::Pending => thread::park(),
|
||||
/// Poll::Ready(res) => return res,
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// #
|
||||
/// # assert_eq!(42, block_on(async { 42 }));
|
||||
/// ```
|
||||
///
|
||||
/// ### With `Generator`s
|
||||
///
|
||||
/// ```rust
|
||||
/// #![feature(generators, generator_trait, pin_macro)]
|
||||
/// use core::{
|
||||
/// ops::{Generator, GeneratorState},
|
||||
/// pin::pin,
|
||||
/// };
|
||||
///
|
||||
/// fn generator_fn() -> impl Generator<Yield = usize, Return = ()> /* not Unpin */ {
|
||||
/// // Allow generator to be self-referential (not `Unpin`)
|
||||
/// // vvvvvv so that locals can cross yield points.
|
||||
/// static || {
|
||||
/// let foo = String::from("foo"); // --+
|
||||
/// yield 0; // | <- crosses yield point!
|
||||
/// println!("{}", &foo); // <----------+
|
||||
/// yield foo.len();
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let mut generator = pin!(generator_fn());
|
||||
/// match generator.as_mut().resume(()) {
|
||||
/// GeneratorState::Yielded(0) => {},
|
||||
/// _ => unreachable!(),
|
||||
/// }
|
||||
/// match generator.as_mut().resume(()) {
|
||||
/// GeneratorState::Yielded(3) => {},
|
||||
/// _ => unreachable!(),
|
||||
/// }
|
||||
/// match generator.resume(()) {
|
||||
/// GeneratorState::Yielded(_) => unreachable!(),
|
||||
/// GeneratorState::Complete(()) => {},
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Remarks
|
||||
///
|
||||
/// Precisely because a value is pinned to local storage, the resulting <code>[Pin]<[&mut] T></code>
|
||||
/// reference ends up borrowing a local tied to that block: it can't escape it.
|
||||
///
|
||||
/// The following, for instance, fails to compile:
|
||||
///
|
||||
/// ```rust,compile_fail
|
||||
/// #![feature(pin_macro)]
|
||||
/// use core::pin::{pin, Pin};
|
||||
/// # use core::{marker::PhantomPinned as Foo, mem::drop as stuff};
|
||||
///
|
||||
/// let x: Pin<&mut Foo> = {
|
||||
/// let x: Pin<&mut Foo> = pin!(Foo { /* … */ });
|
||||
/// x
|
||||
/// }; // <- Foo is dropped
|
||||
/// stuff(x); // Error: use of dropped value
|
||||
/// ```
|
||||
///
|
||||
/// <details><summary>Error message</summary>
|
||||
///
|
||||
/// ```rust
|
||||
/// # const _IGNORE: &str = stringify! {
|
||||
/// error[E0716]: temporary value dropped while borrowed
|
||||
/// --> src/main.rs:9:28
|
||||
/// |
|
||||
/// 8 | let x: Pin<&mut Foo> = {
|
||||
/// | - borrow later stored here
|
||||
/// 9 | let x: Pin<&mut Foo> = pin!(Foo { /* … */ });
|
||||
/// | ^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
|
||||
/// 10 | x
|
||||
/// 11 | }; // <- Foo is dropped
|
||||
/// | - temporary value is freed at the end of this statement
|
||||
/// |
|
||||
/// = note: consider using a let binding to create a longer lived value
|
||||
/// # };
|
||||
/// ```
|
||||
///
|
||||
/// </details>
|
||||
///
|
||||
/// This makes [`pin!`] **unsuitable to pin values when intending to _return_ them**. Instead, the
|
||||
/// value is expected to be passed around _unpinned_ until the point where it is to be consumed,
|
||||
/// where it is then useful and even sensible to pin the value locally using [`pin!`].
|
||||
///
|
||||
/// If you really need to return a pinned value, consider using [`Box::pin`] instead.
|
||||
///
|
||||
/// On the other hand, pinning to the stack[<sup>2</sup>](#fn2) using [`pin!`] is likely to be
|
||||
/// cheaper than pinning into a fresh heap allocation using [`Box::pin`]. Moreover, by virtue of not
|
||||
/// even needing an allocator, [`pin!`] is the main non-`unsafe` `#![no_std]`-compatible [`Pin`]
|
||||
/// constructor.
|
||||
///
|
||||
/// [`Box::pin`]: ../../std/boxed/struct.Box.html#method.pin
|
||||
#[unstable(feature = "pin_macro", issue = "93178")]
|
||||
pub macro pin($value:expr $(,)?) {
|
||||
// This is `Pin::new_unchecked(&mut { $value })`, so, for starters, let's
|
||||
// review such a hypothetical macro (that any user-code could define):
|
||||
//
|
||||
// ```rust
|
||||
// macro_rules! pin {( $value:expr ) => (
|
||||
// match &mut { $value } { at_value => unsafe { // Do not wrap `$value` in an `unsafe` block.
|
||||
// $crate::pin::Pin::<&mut _>::new_unchecked(at_value)
|
||||
// }}
|
||||
// )}
|
||||
// ```
|
||||
//
|
||||
// Safety:
|
||||
// - `type P = &mut _`. There are thus no pathological `Deref{,Mut}` impls
|
||||
// that would break `Pin`'s invariants.
|
||||
// - `{ $value }` is braced, making it a _block expression_, thus **moving**
|
||||
// the given `$value`, and making it _become an **anonymous** temporary_.
|
||||
// By virtue of being anonynomous, it can no longer be accessed, thus
|
||||
// preventing any attemps to `mem::replace` it or `mem::forget` it, _etc._
|
||||
//
|
||||
// This gives us a `pin!` definition that is sound, and which works, but only
|
||||
// in certain scenarios:
|
||||
// - If the `pin!(value)` expression is _directly_ fed to a function call:
|
||||
// `let poll = pin!(fut).poll(cx);`
|
||||
// - If the `pin!(value)` expression is part of a scrutinee:
|
||||
// ```rust
|
||||
// match pin!(fut) { pinned_fut => {
|
||||
// pinned_fut.as_mut().poll(...);
|
||||
// pinned_fut.as_mut().poll(...);
|
||||
// }} // <- `fut` is dropped here.
|
||||
// ```
|
||||
// Alas, it doesn't work for the more straight-forward use-case: `let` bindings.
|
||||
// ```rust
|
||||
// let pinned_fut = pin!(fut); // <- temporary value is freed at the end of this statement
|
||||
// pinned_fut.poll(...) // error[E0716]: temporary value dropped while borrowed
|
||||
// // note: consider using a `let` binding to create a longer lived value
|
||||
// ```
|
||||
// - Issues such as this one are the ones motivating https://github.com/rust-lang/rfcs/pull/66
|
||||
//
|
||||
// This makes such a macro incredibly unergonomic in practice, and the reason most macros
|
||||
// out there had to take the path of being a statement/binding macro (_e.g._, `pin!(future);`)
|
||||
// instead of featuring the more intuitive ergonomics of an expression macro.
|
||||
//
|
||||
// Luckily, there is a way to avoid the problem. Indeed, the problem stems from the fact that a
|
||||
// temporary is dropped at the end of its enclosing statement when it is part of the parameters
|
||||
// given to function call, which has precisely been the case with our `Pin::new_unchecked()`!
|
||||
// For instance,
|
||||
// ```rust
|
||||
// let p = Pin::new_unchecked(&mut <temporary>);
|
||||
// ```
|
||||
// becomes:
|
||||
// ```rust
|
||||
// let p = { let mut anon = <temporary>; &mut anon };
|
||||
// ```
|
||||
//
|
||||
// However, when using a literal braced struct to construct the value, references to temporaries
|
||||
// can then be taken. This makes Rust change the lifespan of such temporaries so that they are,
|
||||
// instead, dropped _at the end of the enscoping block_.
|
||||
// For instance,
|
||||
// ```rust
|
||||
// let p = Pin { pointer: &mut <temporary> };
|
||||
// ```
|
||||
// becomes:
|
||||
// ```rust
|
||||
// let mut anon = <temporary>;
|
||||
// let p = Pin { pointer: &mut anon };
|
||||
// ```
|
||||
// which is *exactly* what we want.
|
||||
//
|
||||
// See https://doc.rust-lang.org/1.58.1/reference/destructors.html#temporary-lifetime-extension
|
||||
// for more info.
|
||||
//
|
||||
// Finally, we don't hit problems _w.r.t._ the privacy of the `pointer` field, or the
|
||||
// unqualified `Pin` name, thanks to `decl_macro`s being _fully_ hygienic (`def_site` hygiene).
|
||||
Pin::<&mut _> { pointer: &mut { $value } }
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user