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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use_prelude!();

#[doc(hidden)]
/// The main "hack": the slot used by the `async fn` to yield items through it,
/// at each `await` / `yield_!` point.
pub
struct YieldSlot<'yield_slot, Item : 'yield_slot> (
    Pin<&'yield_slot CellOption<Item>>,
);

impl<'yield_slot, Item : 'yield_slot> YieldSlot<'yield_slot, Item> {
    #[inline]
    fn new (p: Pin<&'yield_slot CellOption<Item>>)
      -> Self
    {
        Self(p)
    }

    #[doc(hidden)]
    /// Fills the slot with a value, and returns an `.await`-able to be used as
    /// yield point.
    pub
    fn put (self: &'_ Self, value: Item)
      -> impl Future<Output = ()> + '_
    {
        let prev: Option<Item> = self.0.set(value);
        debug_assert!(prev.is_none(), "slot was empty");
        return WaitForClear { yield_slot: self };

        /// "Dummy" `.await`-able:
        ///
        ///  1. The first time it is polled, the slot has just been filled
        ///     (_c.f._, lines above); which triggers a `Pending` yield
        ///     interruption, so that the outer thing polling it
        ///     (GeneratorFn::resume), get to extract the value out of the yield
        ///     slot.
        ///
        ///  2. The second time it is polled, the slot is empty, so that the
        ///     generator can resume its execution to fill it again or complete
        ///     the iteration.
        struct WaitForClear<'yield_slot, Item : 'yield_slot> {
            yield_slot: &'yield_slot YieldSlot<'yield_slot, Item>,
        }

        impl<'yield_slot, Item> Future for WaitForClear<'yield_slot, Item> {
            type Output = ();

            fn poll (self: Pin<&'_ mut Self>, _: &'_ mut Context<'_>)
              -> Poll<()>
            {
                if /* while */ self.yield_slot.0.is_some() {
                    Poll::Pending
                } else {
                    Poll::Ready(())
                }
            }
        }
    }
}

/// An _instance_ of a `#[generator]`-tagged function.
///
/// These are created in a two-step fashion:
///
///  1. First, an [`empty()`][`GeneratorFn::empty`] generator is created,
///     which is to be [pinned][`Pin`].
///
///  2. Once it is [pinned][`Pin`], it can be [`.init()`][
///     `GeneratorFn::init`]-ialized with a `#[generator]`-tagged function.
///
/// As with any [`Generator`], for a [`GeneratorFn`] to be usable, it must have
/// been previously [`Pin`]ned:
///
///   - either in the _heap_, through [`Box::pin`];
///
///     ```rust
///     use ::next_gen::{prelude::*, GeneratorFn, GeneratorState};
///
///     #[generator(u32)]
///     fn countdown (mut remaining: u32)
///     {
///         while let Some(next) = remaining.checked_sub(1) {
///             yield_!(remaining);
///             remaining = next;
///         }
///     }
///
///     let generator = GeneratorFn::empty();
///     let mut generator = Box::pin(generator);
///     generator.as_mut().init(countdown, (3,));
///
///     let mut next = || generator.as_mut().resume();
///     assert_eq!(next(), GeneratorState::Yield(3));
///     assert_eq!(next(), GeneratorState::Yield(2));
///     assert_eq!(next(), GeneratorState::Yield(1));
///     assert_eq!(next(), GeneratorState::Return(()));
///     ```
///
///   - or in the _stack_, through [`stack_pinned!`][`stack_pinned`].
///
///     ```rust
///     use ::next_gen::{prelude::*, GeneratorFn, GeneratorState};
///
///     #[generator(u32)]
///     fn countdown (mut remaining: u32)
///     {
///         while let Some(next) = remaining.checked_sub(1) {
///             yield_!(remaining);
///             remaining = next;
///         }
///     }
///
///     let generator = GeneratorFn::empty();
///     stack_pinned!(mut generator);
///     generator.as_mut().init(countdown, (3,));
///     let mut next = || generator.as_mut().resume();
///     assert_eq!(next(), GeneratorState::Yield(3));
///     assert_eq!(next(), GeneratorState::Yield(2));
///     assert_eq!(next(), GeneratorState::Yield(1));
///     assert_eq!(next(), GeneratorState::Return(()));
///     ```
///
/// # `mk_gen!`
///
/// [`mk_gen!`][`mk_gen`] is a macro that reduces the boilerplate of the above
/// patterns, by performing the two step-initialization within a single macro
/// call.
///
/// # Stack _vs._ heap
///
/// Since stack-pinning prevents ever moving the generator around (duh), once
/// stack-pinned, a [`Generator`] cannot be, for instance, returned. For that,
/// [`Pin`]ning in the heap is necessary:
///
/// ```rust
/// use ::next_gen::prelude::*;
///
/// # let _ = countdown;
/// pub
/// fn countdown (count: u32)
///   -> impl Iterator<Item = u32> + 'static
/// {
///     #[generator(u32)]
///     fn countdown (mut remaining: u32)
///     {
///         while let Some(next) = remaining.checked_sub(1) {
///             yield_!(remaining);
///             remaining = next;
///         }
///     }
///
///     mk_gen!(let generator = box countdown(count));
///     generator.into_iter() // A pinned generator is iterable.
/// }
/// ```
///
/// However, pinning in the stack is vastly more performant (it is zero-cost in
/// release mode), and _suffices for local iteration_. It is thus **the blessed
/// form of [`Pin`]ning**, which should be favored over `box`-ing.
///
/// ```rust
/// use ::next_gen::prelude::*;
///
/// #[generator(u32)]
/// fn countdown (mut remaining: u32)
/// {
///     while let Some(next) = remaining.checked_sub(1) {
///         yield_!(remaining);
///         remaining = next;
///     }
/// }
///
/// mk_gen!(let generator = countdown(3));
/// assert_eq!(
///     generator.into_iter().collect::<Vec<_>>(),
///     [3, 2, 1],
/// );
/// ```
pub
struct GeneratorFn<Item, F : Future> {
    yield_slot: CellOption<Item>,

    future: Option<F>,
}

struct GeneratorPinnedFields<'pin, Item : 'pin, F : Future + 'pin> {
    yield_slot: Pin<&'pin CellOption<Item>>,
    future: Pin<&'pin mut F>,
}

impl<Item, F : Future> GeneratorFn<Item, F> {
    fn project (self: Pin<&'_ mut Self>) -> GeneratorPinnedFields<'_, Item, F>
    {
        unsafe {
            // # Safety
            //
            // This is the same as ::pin_project's .project() method:
            //
            //   - No `Drop`, no packing, and the two fields are considered
            //     transitively pinned.
            let this = self.get_unchecked_mut();
            GeneratorPinnedFields {
                yield_slot: Pin::new_unchecked(&this.yield_slot),
                future: Pin::new_unchecked(
                    this.future
                        .as_mut()
                        .expect("You must init a GeneratorFn before using it!")
                ),
            }
        }
    }

    /// Reserves memory for an empty generator.
    pub
    fn empty ()
      -> Self
    {
        Self {
            yield_slot: CellOption::None,
            future: None,
        }
    }

    /// Fill the memory reserved by [`GeneratorFn::empty`]`()` with an instance of
    /// the generator function / factory.
    pub
    fn init<'pin, 'yield_slot, Args> (
        self: Pin<&'pin mut Self>,
        factory: impl FnOnce(YieldSlot<'yield_slot, Item>, Args) -> F,
        args: Args,
    )
    where
        Item : 'yield_slot,
    {
        assert!(self.future.is_none(),
            "GeneratorFn cannot be initialized multiple times!",
        );
        unsafe {
            // # Safety
            //
            //   - This is a pinning projection except for the `future` field,
            //     to which it gets raw "unlimited" access. This is safe because
            //     the field cannot have been pinned yet (given the API).
            //
            //   - The pinning guarantee ensures the soundness of the lifetime
            //     extension.
            let this = self.get_unchecked_mut();
            let yield_slot =
                YieldSlot::new(Pin::new_unchecked(
                    ::core::mem::transmute::<
                        &'pin CellOption<Item>,
                        &'yield_slot CellOption<Item>,
                    >(
                        &this.yield_slot
                    )
                ))
            ;
            this.future = Some(factory(yield_slot, args));
        }
    }

    /// Associated method version of [`Generator::resume`].
    #[inline]
    pub
    fn resume (self: Pin<&'_ mut Self>)
      -> GeneratorState<Item, F::Output>
    {
        <Self as Generator>::resume(self)
    }
}

/// The trait implemented by [`GeneratorFn`]s.
///
/// Generators, also commonly referred to as coroutines, provide an ergonomic
/// definition for iterators and other primitives, allowing to write iterators
/// and iterator adapters in a much more _imperative_ way, which may sometimes
/// improve the readability of such iterators / iterator adapters.
///
/// # Example
///
/// ```rust
/// use ::next_gen::{prelude::*, GeneratorState};
///
/// fn main ()
/// {
///     #[generator(i32)]
///     fn generator_fn () -> &'static str
///     {
///         yield_!(1);
///         return "foo"
///     }
///
///     mk_gen!(let mut generator = generator_fn());
///
///     match generator.as_mut().resume() {
///         | GeneratorState::Yield(1) => {}
///         | _ => panic!("unexpected return from resume"),
///     }
///     match generator.as_mut().resume() {
///         | GeneratorState::Return("foo") => {}
///         | _ => panic!("unexpected yield from resume"),
///     }
/// }
/// ```
pub
trait Generator {
    /// The type of value this generator yields.
    ///
    /// This associated type corresponds to the `yield_!` expression and the
    /// values which are allowed to be returned each time a generator yields.
    /// For example an iterator-as-a-generator would likely have this type as
    /// `T`, the type being iterated over.
    type Yield;

    /// The type of value this generator returns.
    ///
    /// This corresponds to the type returned from a generator either with a
    /// `return` statement or implicitly as the last expression of a generator
    /// literal.
    type Return;


    /// Resumes the execution of this generator.
    ///
    /// This function will resume execution of the generator or start execution
    /// if it hasn't already. This call will return back into the generator's
    /// last suspension point, resuming execution from the latest `yield_!`.
    /// The generator will continue executing until it either yields or returns,
    /// at which point this function will return.
    ///
    /// # Return value
    ///
    /// The [`GeneratorState`] enum returned from this function indicates what
    /// state the generator is in upon returning.
    ///
    /// If the [`Yield`][`GeneratorState::Yield`] variant is returned then the
    /// generator has reached a suspension point and a value has been yielded
    /// out. Generators in this state are available for resumption at a later
    /// point.
    ///
    /// If [`Return`] is returned then the generator has completely finished
    /// with the value provided. It is invalid for the generator to be resumed
    /// again.
    ///
    /// # Panics
    ///
    /// This function may panic if it is called after the [`Return`] variant has
    /// been returned previously. While generator literals in the language are
    /// guaranteed to panic on resuming after [`Return`], this is not guaranteed
    /// for all implementations of the [`Generator`] trait.
    ///
    /// [`Return`]: `GeneratorState::Return`
    fn resume (self: Pin<&'_ mut Self>)
      -> GeneratorState<Self::Yield, Self::Return>
    ;
}

impl<Item, F : Future> Generator for GeneratorFn<Item, F> {
    type Yield = Item;

    type Return = F::Output;

    fn resume (self: Pin<&'_ mut Self>)
      -> GeneratorState<Item, F::Output>
    {
        let this = self.project(); // panics if uninit
        create_context!(cx);
        match this.future.poll(&mut cx) {
            | Poll::Pending => {
                let value =
                    this.yield_slot
                        .take()
                        .expect("Missing item in yield_slot!")
                ;
                GeneratorState::Yield(value)
            },

            | Poll::Ready(value) => {
                GeneratorState::Return(value)
            }
        }
    }
}

/// Value obtained when [polling][`Generator::resume`] a [`GeneratorFn`].
///
/// This corresponds to:
///
///   - either a [suspension point][`GeneratorState::Yield`],
///
///   - or a [termination point][`GeneratorState::Return`]
#[derive(
    Debug,
    Clone, Copy,
    PartialEq, Eq,
    PartialOrd, Ord,
    Hash
)]
pub
enum GeneratorState<Yield, Return = ()> {
    /// The [`Generator`] suspended with a value.
    ///
    /// This state indicates that a [`Generator`] has been suspended, and
    /// corresponds to a `yield_!` statement. The value provided in this variant
    /// corresponds to the expression passed to `yield_!` and allows generators
    /// to provide a value each time they `yield_!`.
    Yield(Yield),

    /// The [`Generator`] _completed_ with a [`Return`] value.
    ///
    /// This state indicates that a [`Generator`] has finished execution with
    /// the provided value. Once a generator has returned [`Return`], it is
    /// considered a programmer error to call [`.resume()`][`Generator::resume`]
    /// again.
    ///
    /// [`Return`]: Generator::Return
    Return(Return),
}

impl<'a, G : ?Sized + 'a> Generator for Pin<&'a mut G>
where
    G : Generator,
{
    type Yield = G::Yield;
    type Return = G::Return;

    #[inline]
    fn resume (mut self: Pin<&'_ mut Pin<&'a mut G>>)
      -> GeneratorState<Self::Yield, Self::Return>
    {
        G::resume(
            Pin::<&mut G>::as_mut(&mut *self)
        )
    }
}

impl<'a, G : ?Sized + 'a> Generator for &'a mut G
where
    G : Generator + Unpin,
{
    type Yield = G::Yield;
    type Return = G::Return;

    #[inline]
    fn resume (mut self: Pin<&'_ mut &'a mut G>)
      -> GeneratorState<Self::Yield, Self::Return>
    {
        G::resume(
            Pin::<&mut G>::new(&mut *self)
        )
    }
}