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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! So, you have a nice `async fn` and you want to store a future it returns in
//! a struct. There's no need for boxing or dynamic dispatch: you statically
//! know the type. You just need to `#[name_it]`.
//!
//! ```rust
//! # use name_it::name_it;
//! # use futures::executor::block_on;
//! # async fn do_something_very_async() {}
//! #[name_it(Test)]
//! async fn add(x: i32, y: i32) -> i32 {
//!     do_something_very_async().await;
//!     x + y
//! }
//!
//! # fn main() {
//! let foo: Test = add(2, 3);
//! assert_eq!(block_on(foo), 5);
//! # }
//! ```
#![doc = include_str!("../readme-parts/main.md")]
#![no_std]
// lint me harder
#![forbid(non_ascii_idents)]
#![deny(
    future_incompatible,
    keyword_idents,
    elided_lifetimes_in_paths,
    meta_variable_misuse,
    noop_method_call,
    pointer_structural_match,
    unused_lifetimes,
    unused_qualifications,
    unsafe_op_in_unsafe_fn,
    clippy::undocumented_unsafe_blocks,
    clippy::wildcard_dependencies,
    clippy::debug_assert_with_mut_call,
    clippy::empty_line_after_outer_attr,
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::redundant_field_names,
    clippy::rest_pat_in_fully_bound_structs,
    clippy::unneeded_field_pattern,
    clippy::useless_let_if_seq,
    clippy::default_union_representation
)]
#![warn(clippy::pedantic)]
// not that hard:
#![allow(
    // ideally all the functions must be optimized to nothing, which requires always inlining
    clippy::inline_always,
    // we don't actually export functions, so it's not needed
    clippy::must_use_candidate,
)]

use core::{
    future::Future,
    marker::PhantomPinned,
    mem::{ManuallyDrop, MaybeUninit},
    pin::Pin,
    task::{Context, Poll},
};

/// A way to name the return type of an async function. See [crate docs](crate)
/// for more info.
pub use name_it_macros::name_it;

// Manual formatting looks better here
#[rustfmt::skip]
#[doc(hidden)]
pub mod markers;

// SAFETY: can only be implemented on functions returning `Self::Fut`
#[doc(hidden)]
pub unsafe trait FutParams {
    type Fut: Future<Output = Self::Output>;
    type Output;
}

#[doc(hidden)]
pub use elain as _elain;

#[doc(hidden)]
// This function is never called, it's only a placeholder
#[allow(clippy::panic)]
pub fn any<T>(_: &str) -> T {
    panic!()
}

#[doc(hidden)]
#[macro_export]
macro_rules! _produce_any {
    ($f:ident $($xs:pat),*$(,)?) => {
        $f(
            $($crate::any(stringify!($xs))),*
        )
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! _name_it_inner {
    ($v:vis type $name:ident = $func:ident($($underscores:tt)*) -> $ret:ty$(;)?) => {
        #[repr(C)]
        $v struct $name<'fut>
        where
            $crate::_elain::Align<{$crate::align_of_fut(&($func as fn($($underscores)*) -> _))}>: $crate::_elain::Alignment,
        {
            bytes: [::core::mem::MaybeUninit<u8>; $crate::size_of_fut(&($func as fn($($underscores)*) -> _))],
            _alignment: $crate::_elain::Align<{$crate::align_of_fut(&($func as fn($($underscores)*) -> _))}>,
            // FIXME: invariant is probably too strict
            _lifetime: ::core::marker::PhantomData<&'fut mut &'fut mut ()>,
            _markers: $crate::markers!($crate::_produce_any!($func $($underscores)*)),
        }

        impl<'fut> $name<'fut> {
            #[doc(hidden)]
            $v unsafe fn new(bytes: [::core::mem::MaybeUninit<u8>; $crate::size_of_fut(&($func as fn($($underscores)*) -> _))]) -> Self {
                Self {
                    bytes,
                    _alignment: $crate::_elain::Align::NEW,
                    _lifetime: ::core::marker::PhantomData,
                    _markers: $crate::markers::Markers::new(),
                }
            }
        }

        impl<'fut> ::core::future::Future for $name<'fut> {
            type Output = $ret;

            fn poll(self: ::core::pin::Pin<&mut Self>, cx: &mut ::core::task::Context<'_>) -> ::core::task::Poll<$ret> {
                // SAFETY:
                // 1. `::poll()` is safe since we're not lying about the type
                // 2. `transmute()` is safe since the representation is the same
                unsafe {
                    $crate::poll(
                        ::core::mem::transmute::<
                            _, ::core::pin::Pin<&mut [::core::mem::MaybeUninit<u8>; $crate::size_of_fut(&($func as fn($($underscores)*) -> _))]>
                        >(self),
                        cx, $func as fn($($underscores)*) -> _
                    )
                }
            }
        }

        impl<'fut> ::core::ops::Drop for $name<'fut> {
            fn drop(&mut self) {
                // SAFETY: this is the only `::dispose()` call and we're not lying about the type
                unsafe {
                    $crate::dispose(&mut self.bytes, ($func as fn($($underscores)*) -> _));
                }
            }
        }
    };
}

/// Wrapper type for named futures.
///
/// Type of your future will be something like
/// ```rust,ignore
/// type YourName<'fut> = Named</* implementation detail */>;
/// ```
#[repr(transparent)]
pub struct Named<T> {
    // Oh, we read this field, just not as you expected, poor rustc
    #[allow(dead_code)]
    inner: T,
    _pinned: PhantomPinned,
}

impl<T> Named<T> {
    #[doc(hidden)]
    pub fn new(inner: T) -> Self {
        Self {
            inner,
            _pinned: PhantomPinned,
        }
    }
}

impl<T> Future for Named<T>
where
    T: Future,
{
    type Output = T::Output;

    #[inline]
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // SAFETY: the representation is the same
        unsafe { core::mem::transmute::<_, Pin<&mut T>>(self) }.poll(cx)
    }
}

#[repr(C)]
union Transmute<From, To> {
    from: ManuallyDrop<From>,
    to: ManuallyDrop<To>,
}

#[inline]
#[doc(hidden)]
pub unsafe fn transmute_generic<From, To>(val: From) -> To {
    ManuallyDrop::into_inner(
        // SAFETY: caller-guaranteed
        unsafe {
            Transmute::<From, To> {
                from: ManuallyDrop::new(val),
            }
            .to
        },
    )
}

#[inline]
#[doc(hidden)]
pub unsafe fn poll<F: FutParams, const N: usize>(
    this: Pin<&mut [MaybeUninit<u8>; N]>,
    cx: &mut Context<'_>,
    _: F,
) -> Poll<F::Output> {
    // SAFETY: `transmute_generic()` is safe because caller promised us that's the
    // type inside
    let fut = unsafe { transmute_generic::<Pin<&mut _>, Pin<&mut F::Fut>>(this) };
    fut.poll(cx)
}

#[inline]
#[doc(hidden)]
pub unsafe fn dispose<F: FutParams, const N: usize>(this: &mut [MaybeUninit<u8>; N], _: F) {
    // SAFETY: caller promised us that's the type inside
    let fut = unsafe { transmute_generic::<&mut _, &mut MaybeUninit<F::Fut>>(this) };
    // SAFETY: we're only calling this one time, in our `Drop`, and never use this
    // after
    unsafe { fut.assume_init_drop() };
}

#[doc(hidden)]
pub const fn size_of_fut<F: FutParams>(_: &F) -> usize {
    core::mem::size_of::<F::Fut>()
}

#[doc(hidden)]
pub const fn align_of_fut<F: FutParams>(_: &F) -> usize {
    core::mem::align_of::<F::Fut>()
}

macro_rules! impl_fut_params {
    ($($t:ident $($ts:ident)*)?) => {
        // SAFETY: we're implementing this for a function returning `Fut`
        unsafe impl<$($t, $($ts,)*)? R, Fut> FutParams for fn($($t, $($ts,)*)?) -> Fut
        where
            Fut: Future<Output = R>
        {
            type Fut = Fut;
            type Output = R;
        }

        $(impl_fut_params!($($ts)*);)?
    };
}

impl_fut_params!(
    T00 T01 T02 T03 T04 T05 T06 T07 T08 T09 T10 T11 T12 T13 T14 T15
    T16 T17 T18 T19 T20 T21 T22 T23 T24 T25 T26 T27 T28 T29 T30 T31
);