1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#![stable(feature = "futures_api", since = "1.36.0")]

//! 异步值。

use crate::{
    ops::{Generator, GeneratorState},
    pin::Pin,
    ptr::NonNull,
    task::{Context, Poll},
};

mod future;
mod into_future;
mod pending;
mod poll_fn;
mod ready;

#[stable(feature = "futures_api", since = "1.36.0")]
pub use self::future::Future;

#[unstable(feature = "into_future", issue = "67644")]
pub use into_future::IntoFuture;

#[stable(feature = "future_readiness_fns", since = "1.48.0")]
pub use pending::{pending, Pending};
#[stable(feature = "future_readiness_fns", since = "1.48.0")]
pub use ready::{ready, Ready};

#[unstable(feature = "future_poll_fn", issue = "72302")]
pub use poll_fn::{poll_fn, PollFn};

/// 之所以需要这种类型,是因为:
///
/// a) Generators 不能实现 `for<'a, 'b> Generator<&'a mut Context<'b>>`,所以我们需要传递一个裸体路径 (见 <https://github.com/rust-lang/rust/issues/68923>)。
///
/// b) 裸指针和 `NonNull` 不是 `Send` 或 `Sync`,因此每个 future non-Send/Sync 也是如此,我们不想要那样。
///
/// 它还简化了 `.await` 的 HIR 降低。
///
#[doc(hidden)]
#[unstable(feature = "gen_future", issue = "50547")]
#[derive(Debug, Copy, Clone)]
pub struct ResumeTy(NonNull<Context<'static>>);

#[unstable(feature = "gen_future", issue = "50547")]
unsafe impl Send for ResumeTy {}

#[unstable(feature = "gen_future", issue = "50547")]
unsafe impl Sync for ResumeTy {}

/// 将生成器包装在 future 中。
///
/// 此函数在下面返回 `GenFuture`,但将其隐藏在 `impl Trait` 中以提供更好的错误消息 (`impl Future` 而不是 `GenFuture<[closure.....]>`)。
///
// 这是 `const`,以避免在我们从 `const async fn` 恢复后出现额外的错误
#[lang = "from_generator"]
#[doc(hidden)]
#[unstable(feature = "gen_future", issue = "50547")]
#[rustc_const_unstable(feature = "gen_future", issue = "50547")]
#[inline]
pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
where
    T: Generator<ResumeTy, Yield = ()>,
{
    #[rustc_diagnostic_item = "gen_future"]
    struct GenFuture<T: Generator<ResumeTy, Yield = ()>>(T);

    // 我们依靠这样的事实,即 async/await futures 是不动的,以便在基础生成器中创建自指代借用。
    //
    impl<T: Generator<ResumeTy, Yield = ()>> !Unpin for GenFuture<T> {}

    impl<T: Generator<ResumeTy, Yield = ()>> Future for GenFuture<T> {
        type Output = T::Return;
        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            // SAFETY: 安全,因为我们是 `!Unpin + !Drop`,这只是一个字段推断。
            let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };

            // 恢复生成器,将 `&mut Context` 变成 `NonNull` 裸指针。
            // `.await` lowering 会安全地将其转换为 `&mut Context`。
            match gen.resume(ResumeTy(NonNull::from(cx).cast::<Context<'static>>())) {
                GeneratorState::Yielded(()) => Poll::Pending,
                GeneratorState::Complete(x) => Poll::Ready(x),
            }
        }
    }

    GenFuture(gen)
}

#[lang = "get_context"]
#[doc(hidden)]
#[unstable(feature = "gen_future", issue = "50547")]
#[inline]
pub unsafe fn get_context<'a, 'b>(cx: ResumeTy) -> &'a mut Context<'b> {
    // SAFETY: 调用者必须保证 `cx.0` 是满足可变引用所有要求的有效指针。
    //
    unsafe { &mut *cx.0.as_ptr().cast() }
}