@@ -909,3 +909,245 @@ impl<P, U> CoerceUnsized<Pin<U>> for Pin<P> where P: CoerceUnsized<U> {}
909909
910910#[ stable( feature = "pin" , since = "1.33.0" ) ]
911911impl < P , U > DispatchFromDyn < Pin < U > > for Pin < P > where P : DispatchFromDyn < U > { }
912+
913+ /// Constructs a <code>[Pin]<[&mut] T></code>, by pinning[^1] a `value: T` _locally_[^2]
914+ /// (≠ [in the heap][`Box::pin`]).
915+ ///
916+ /// [^1]: If the (type `T` of the) given value does not implement [`Unpin`], then this
917+ /// effectively pins the `value` in memory, where it will be unable to be moved.
918+ /// Otherwise, <code>[Pin]<[&mut] T></code> behaves like <code>[&mut] T</code>, and operations such
919+ /// as [`mem::replace()`][crate::mem::replace] will allow extracting that value, and therefore,
920+ /// moving it.
921+ /// See [the `Unpin` section of the `pin` module][self#unpin] for more info.
922+ ///
923+ /// [^2]: This is usually dubbed "stack"-pinning. And whilst local values are almost always located
924+ /// in the stack (_e.g._, when within the body of a non-`async` function), the truth is that inside
925+ /// the body of an `async fn` or block —more generally, the body of a generator— any locals crossing
926+ /// an `.await` point —a `yield` point— end up being part of the state captured by the `Future` —by
927+ /// the `Generator`—, and thus will be stored wherever that one is.
928+ ///
929+ /// ## Examples
930+ ///
931+ /// ### Basic usage
932+ ///
933+ /// ```rust
934+ /// #![feature(pin_macro)]
935+ /// # use core::marker::PhantomPinned as Foo;
936+ /// use core::pin::{pin, Pin};
937+ ///
938+ /// fn stuff(foo: Pin<&mut Foo>) {
939+ /// // …
940+ /// # let _ = foo;
941+ /// }
942+ ///
943+ /// let pinned_foo = pin!(Foo { /* … */ });
944+ /// stuff(pinned_foo);
945+ /// // or, directly:
946+ /// stuff(pin!(Foo { /* … */ }));
947+ /// ```
948+ ///
949+ /// ### Manually polling a `Future` (wihout `Unpin` bounds)
950+ ///
951+ /// ```rust
952+ /// #![feature(pin_macro)]
953+ /// use std::{
954+ /// future::Future,
955+ /// pin::pin,
956+ /// task::{Context, Poll},
957+ /// thread,
958+ /// };
959+ /// # use std::{sync::Arc, task::Wake, thread::Thread};
960+ ///
961+ /// # /// A waker that wakes up the current thread when called.
962+ /// # struct ThreadWaker(Thread);
963+ /// #
964+ /// # impl Wake for ThreadWaker {
965+ /// # fn wake(self: Arc<Self>) {
966+ /// # self.0.unpark();
967+ /// # }
968+ /// # }
969+ /// #
970+ /// /// Runs a future to completion.
971+ /// fn block_on<Fut: Future>(fut: Fut) -> Fut::Output {
972+ /// let waker_that_unparks_thread = // …
973+ /// # Arc::new(ThreadWaker(thread::current())).into();
974+ /// let mut cx = Context::from_waker(&waker_that_unparks_thread);
975+ /// // Pin the future so it can be polled.
976+ /// let mut pinned_fut = pin!(fut);
977+ /// loop {
978+ /// match pinned_fut.as_mut().poll(&mut cx) {
979+ /// Poll::Pending => thread::park(),
980+ /// Poll::Ready(res) => return res,
981+ /// }
982+ /// }
983+ /// }
984+ /// #
985+ /// # assert_eq!(42, block_on(async { 42 }));
986+ /// ```
987+ ///
988+ /// ### With `Generator`s
989+ ///
990+ /// ```rust
991+ /// #![feature(generators, generator_trait, pin_macro)]
992+ /// use core::{
993+ /// ops::{Generator, GeneratorState},
994+ /// pin::pin,
995+ /// };
996+ ///
997+ /// fn generator_fn() -> impl Generator<Yield = usize, Return = ()> /* not Unpin */ {
998+ /// // Allow generator to be self-referential (not `Unpin`)
999+ /// // vvvvvv so that locals can cross yield points.
1000+ /// static || {
1001+ /// let foo = String::from("foo"); // --+
1002+ /// yield 0; // | <- crosses yield point!
1003+ /// println!("{}", &foo); // <----------+
1004+ /// yield foo.len();
1005+ /// }
1006+ /// }
1007+ ///
1008+ /// fn main() {
1009+ /// let mut generator = pin!(generator_fn());
1010+ /// match generator.as_mut().resume(()) {
1011+ /// GeneratorState::Yielded(0) => {},
1012+ /// _ => unreachable!(),
1013+ /// }
1014+ /// match generator.as_mut().resume(()) {
1015+ /// GeneratorState::Yielded(3) => {},
1016+ /// _ => unreachable!(),
1017+ /// }
1018+ /// match generator.resume(()) {
1019+ /// GeneratorState::Yielded(_) => unreachable!(),
1020+ /// GeneratorState::Complete(()) => {},
1021+ /// }
1022+ /// }
1023+ /// ```
1024+ ///
1025+ /// ## Remarks
1026+ ///
1027+ /// Precisely because a value is pinned to local storage, the resulting <code>[Pin]<[&mut] T></code>
1028+ /// reference ends up borrowing a local tied to that block: it can't escape it.
1029+ ///
1030+ /// The following, for instance, fails to compile:
1031+ ///
1032+ /// ```rust,compile_fail
1033+ /// #![feature(pin_macro)]
1034+ /// use core::pin::{pin, Pin};
1035+ /// # use core::{marker::PhantomPinned as Foo, mem::drop as stuff};
1036+ ///
1037+ /// let x: Pin<&mut Foo> = {
1038+ /// let x: Pin<&mut Foo> = pin!(Foo { /* … */ });
1039+ /// x
1040+ /// }; // <- Foo is dropped
1041+ /// stuff(x); // Error: use of dropped value
1042+ /// ```
1043+ ///
1044+ /// <details><summary>Error message</summary>
1045+ ///
1046+ /// ```rust
1047+ /// # const _IGNORE: &str = stringify! {
1048+ /// error[E0716]: temporary value dropped while borrowed
1049+ /// --> src/main.rs:9:28
1050+ /// |
1051+ /// 8 | let x: Pin<&mut Foo> = {
1052+ /// | - borrow later stored here
1053+ /// 9 | let x: Pin<&mut Foo> = pin!(Foo { /* … */ });
1054+ /// | ^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
1055+ /// 10 | x
1056+ /// 11 | }; // <- Foo is dropped
1057+ /// | - temporary value is freed at the end of this statement
1058+ /// |
1059+ /// = note: consider using a let binding to create a longer lived value
1060+ /// # };
1061+ /// ```
1062+ ///
1063+ /// </details>
1064+ ///
1065+ /// This makes [`pin!`] **unsuitable to pin values when intending to _return_ them**. Instead, the
1066+ /// value is expected to be passed around _unpinned_ until the point where it is to be consumed,
1067+ /// where it is then useful and even sensible to pin the value locally using [`pin!`].
1068+ ///
1069+ /// If you really need to return a pinned value, consider using [`Box::pin`] instead.
1070+ ///
1071+ /// On the other hand, pinning to the stack[<sup>2</sup>](#fn2) using [`pin!`] is likely to be
1072+ /// cheaper than pinning into a fresh heap allocation using [`Box::pin`]. Moreover, by virtue of not
1073+ /// even needing an allocator, [`pin!`] is the main non-`unsafe` `#![no_std]`-compatible [`Pin`]
1074+ /// constructor.
1075+ ///
1076+ /// [`Box::pin`]: ../../std/boxed/struct.Box.html#method.pin
1077+ #[ unstable( feature = "pin_macro" , issue = "93178" ) ]
1078+ pub macro pin ( $value: expr $( , ) ?) {
1079+ // This is `Pin::new_unchecked(&mut { $value })`, so, for starters, let's
1080+ // review such a hypothetical macro (that any user-code could define):
1081+ //
1082+ // ```rust
1083+ // macro_rules! pin {( $value:expr ) => (
1084+ // match &mut { $value } { at_value => unsafe { // Do not wrap `$value` in an `unsafe` block.
1085+ // $crate::pin::Pin::<&mut _>::new_unchecked(at_value)
1086+ // }}
1087+ // )}
1088+ // ```
1089+ //
1090+ // Safety:
1091+ // - `type P = &mut _`. There are thus no pathological `Deref{,Mut}` impls
1092+ // that would break `Pin`'s invariants.
1093+ // - `{ $value }` is braced, making it a _block expression_, thus **moving**
1094+ // the given `$value`, and making it _become an **anonymous** temporary_.
1095+ // By virtue of being anonynomous, it can no longer be accessed, thus
1096+ // preventing any attemps to `mem::replace` it or `mem::forget` it, _etc._
1097+ //
1098+ // This gives us a `pin!` definition that is sound, and which works, but only
1099+ // in certain scenarios:
1100+ // - If the `pin!(value)` expression is _directly_ fed to a function call:
1101+ // `let poll = pin!(fut).poll(cx);`
1102+ // - If the `pin!(value)` expression is part of a scrutinee:
1103+ // ```rust
1104+ // match pin!(fut) { pinned_fut => {
1105+ // pinned_fut.as_mut().poll(...);
1106+ // pinned_fut.as_mut().poll(...);
1107+ // }} // <- `fut` is dropped here.
1108+ // ```
1109+ // Alas, it doesn't work for the more straight-forward use-case: `let` bindings.
1110+ // ```rust
1111+ // let pinned_fut = pin!(fut); // <- temporary value is freed at the end of this statement
1112+ // pinned_fut.poll(...) // error[E0716]: temporary value dropped while borrowed
1113+ // // note: consider using a `let` binding to create a longer lived value
1114+ // ```
1115+ // - Issues such as this one are the ones motivating https://github.com/rust-lang/rfcs/pull/66
1116+ //
1117+ // This makes such a macro incredibly unergonomic in practice, and the reason most macros
1118+ // out there had to take the path of being a statement/binding macro (_e.g._, `pin!(future);`)
1119+ // instead of featuring the more intuitive ergonomics of an expression macro.
1120+ //
1121+ // Luckily, there is a way to avoid the problem. Indeed, the problem stems from the fact that a
1122+ // temporary is dropped at the end of its enclosing statement when it is part of the parameters
1123+ // given to function call, which has precisely been the case with our `Pin::new_unchecked()`!
1124+ // For instance,
1125+ // ```rust
1126+ // let p = Pin::new_unchecked(&mut <temporary>);
1127+ // ```
1128+ // becomes:
1129+ // ```rust
1130+ // let p = { let mut anon = <temporary>; &mut anon };
1131+ // ```
1132+ //
1133+ // However, when using a literal braced struct to construct the value, references to temporaries
1134+ // can then be taken. This makes Rust change the lifespan of such temporaries so that they are,
1135+ // instead, dropped _at the end of the enscoping block_.
1136+ // For instance,
1137+ // ```rust
1138+ // let p = Pin { pointer: &mut <temporary> };
1139+ // ```
1140+ // becomes:
1141+ // ```rust
1142+ // let mut anon = <temporary>;
1143+ // let p = Pin { pointer: &mut anon };
1144+ // ```
1145+ // which is *exactly* what we want.
1146+ //
1147+ // See https://doc.rust-lang.org/1.58.1/reference/destructors.html#temporary-lifetime-extension
1148+ // for more info.
1149+ //
1150+ // Finally, we don't hit problems _w.r.t._ the privacy of the `pointer` field, or the
1151+ // unqualified `Pin` name, thanks to `decl_macro`s being _fully_ hygienic (`def_site` hygiene).
1152+ Pin :: < & mut _ > { pointer : & mut { $value } }
1153+ }
0 commit comments