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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Coroutines/generators via code transformation, without `async`.
//!
//! Annotate a function with [`macro@coroutine`] and it is rewritten into
//! a state machine implementing the [`Coroutine`] trait. Suspension
//! points are written as `yield_!(expr)`; the body is analyzed as a
//! control-flow graph and rewritten at compile time — no `async`, no
//! allocation, no unsafe code.
//!
//! ```
//! use diapause::{Coroutine, CoroutineState};
//!
//! #[diapause::coroutine(yield = u32, resume = u32)]
//! fn running_total(start: u32) -> u32 {
//! let a = yield_!(start);
//! let b = yield_!(start + a);
//! start + a + b
//! }
//!
//! let mut c = running_total(100);
//! assert_eq!(c.start(), CoroutineState::Yielded(100));
//! assert_eq!(c.resume(1), CoroutineState::Yielded(101));
//! assert_eq!(c.resume(2), CoroutineState::Complete(103));
//! ```
//!
//! Calling the annotated function returns the initial state without
//! running any code; [`Coroutine::start`] runs the body up to the first
//! `yield_!`, and each [`Coroutine::resume`] continues from the previous
//! suspension point, passing its argument as the value of the
//! `let x = yield_!(..)` binding.
//!
//! The [playground](https://todesking.github.io/diapause/) runs the
//! transform in the browser, showing the expanded code and control-flow
//! graph for any annotated function.
//!
//! # Supported bodies
//!
//! `yield_!` works inside `if` / `match` / `loop` / `while` /
//! `while let` / `for` at any nesting depth, mixed with `break`,
//! `continue`, early `return`, and the `?` operator on `Result` and
//! `Option`. [`yield_all!`] delegates to another coroutine, forwarding
//! its yields and resume values ([`yield_all_resume!`] does the same
//! for one that is already started, and the `box` modifier stores the
//! delegate boxed, enabling recursion). Because the state enum stores only
//! concrete types, serde derives work with their ordinary semantics and
//! a suspended coroutine can be serialized, deserialized elsewhere, and
//! resumed — nested delegation states included.
//!
//! The macro never sees rustc's type information and works purely
//! syntactically, which imposes rules on the body: `yield_!` is
//! statement-position only, variables held across a suspension point
//! need syntactically determinable types, and only direct borrows may
//! cross a yield. See [`macro@coroutine`] for the full constraint list
//! with workarounds.
//!
//! # Comparison with async-based generators
//!
//! Crates like `genawaiter` implement generators by driving an `async`
//! block. diapause instead generates the state machine itself, which
//! means no `Pin` (states are always `Unpin`), resume arguments that
//! are plain function arguments rather than shared-cell tricks, an
//! inspectable state enum that supports `#[derive(Clone)]` snapshots
//! and serde persistence — at the price of the syntactic rules above.
extern crate alloc;
pub use coroutine;
/// Support items for the code `#[coroutine]` generates; not public API.
/// Runs the README's code examples as doctests.
;
/// The result of a [`Coroutine::start`] / [`Coroutine::resume`] call.
/// The result of a [`Coroutine::status`] query.
///
/// Reports which of `start`/`resume` may currently be called without
/// panicking, without having to call either and risk the panic.
/// A resumable computation.
///
/// Implemented by the state enums that [`macro@coroutine`] generates.
/// `R` is the resume argument type (the attribute's `resume = ..`,
/// defaulting to `()`).
///
/// Unlike nightly's `std::ops::Coroutine`, `resume` takes `&mut self`
/// without `Pin`: borrows are never stored in the state, so the
/// generated state machines are always `Unpin`.
///
/// The conditions under which `start`/`resume` panic are documented on
/// each method (and reported by [`status`](Self::status) beforehand);
/// the panic messages themselves are not part of the stable API.
/// Forwarding impl so that generic drivers can take a coroutine by
/// mutable reference, and a coroutine can be partially iterated without
/// being consumed (`for x in Iter::new(&mut c)`).
/// Forwarding impl so a boxed coroutine can be driven directly, e.g.
/// one stored boxed to break a recursive type. Requires the `alloc`
/// feature (enabled by default).
/// Fingerprint validation of a persisted coroutine state.
///
/// Implemented by the state enums that [`macro@coroutine`] generates
/// when the attribute is given the `fingerprint` flag, so that generic
/// persistence layers can validate states without naming each concrete
/// state type.
/// A persisted coroutine state does not match the source of the
/// coroutine it is checked against.
///
/// Returned by [`Fingerprinted::check_fingerprint`], which
/// [`macro@coroutine`] implements when the attribute is given the
/// `fingerprint` flag. Call it right after deserializing to detect the
/// mismatch gracefully; `start`/`resume` panic on the same condition.
/// Desugaring target for `?` inside a `#[diapause::coroutine]` function.
///
/// The coroutine transformation rewrites `expr?` into a `branch` call so
/// that `?` works on stable without `std::ops::Try`. Supported operand
/// types are `Result` and `Option`, exactly as with `?` in a plain
/// function. This trait shows up in rustc error messages when `?` is
/// used on an unsupported type, but it is an internal implementation
/// detail: it is sealed and cannot be implemented for other types.
/// Companion of [`Try`]: rebuilds the coroutine's return value from
/// the residual carried out by an early-exiting `?`.
///
/// Like `Try`, this is an internal implementation detail that only
/// exists in error messages; it is sealed and cannot be implemented
/// for other types.
// The `From` bound mirrors `?`'s error conversion in plain functions.
/// A wrapper that implements `Iterator` for a coroutine.
///
/// Converts a coroutine with `resume = ()` into an `Iterator` that yields
/// the coroutine's yielded values. The coroutine's completion value is
/// discarded.
///
/// A coroutine whose `resume` type is `()` also implements
/// [`IntoIterator`] directly (the `#[coroutine]` macro generates it), so
/// the state can be passed straight to a `for` loop without wrapping it in
/// `Iter::new`. `Iter::new` remains as the general entry point, e.g. when
/// naming the iterator type or converting a value already held as `C`;
/// `Iter::new(&mut c)` borrows the coroutine instead of consuming it
/// (via the `Coroutine for &mut C` forwarding impl), so
/// `for x in Iter::new(&mut c)` iterates partially and leaves the rest
/// resumable.
///
/// This wrapper does not implement `Deref`/`DerefMut`; access the wrapped
/// coroutine explicitly through [`get_ref`](Self::get_ref),
/// [`get_mut`](Self::get_mut), or [`into_inner`](Self::into_inner). The
/// iterator holds no shadow state: `next` decides what to do by asking the
/// coroutine's [`status`](Coroutine::status), so driving the coroutine
/// directly through `get_mut` stays consistent with continued iteration.
///
/// # Example: Direct iteration
///
/// ```
/// use diapause::Coroutine;
///
/// #[diapause::coroutine(yield = u32, resume = ())]
/// fn count_up() {
/// let nums: [u32; 3] = [0, 1, 2];
/// for i in nums {
/// yield_!(i);
/// }
/// }
///
/// let mut iter = diapause::Iter::new(count_up());
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// # Example: Using a for loop
///
/// A `resume = ()` coroutine implements `IntoIterator`, so it can be
/// passed directly to `for`:
///
/// ```
/// #[diapause::coroutine(yield = u32, resume = ())]
/// fn count_to_three() {
/// let nums: [u32; 3] = [1, 2, 3];
/// for n in nums {
/// yield_!(n);
/// }
/// }
///
/// let mut sum = 0;
/// for n in count_to_three() {
/// sum += n;
/// }
/// assert_eq!(sum, 6);
/// ```
/// Marks a suspension point inside a `#[diapause::coroutine]` function.
///
/// `yield_!(expr)` suspends the coroutine, yielding `expr` to the caller.
/// `let r = yield_!(expr);` additionally binds the value passed to the
/// next `resume` call. `yield_!()` yields `()`.
///
/// It is a macro rather than the `yield` keyword because stable rustfmt
/// and IDEs handle reserved-keyword expressions poorly.
///
/// This macro is consumed by the `#[coroutine]` transformation and never
/// expands on its own; it exists so that `yield_!` resolves for IDEs and
/// documentation. Using it outside a `#[diapause::coroutine]` function is
/// a compile error.
/// Delegates to another coroutine inside a `#[diapause::coroutine]`
/// function (the analogue of Python's `yield from`).
///
/// `yield_all!(sub)` runs the coroutine held by the variable `sub` to
/// completion: every value it yields is yielded to the caller, every
/// resume value is forwarded back into it, and the whole expression
/// evaluates to its completion value. The inner coroutine's yield and
/// resume types must match the outer ones, and it must not have been
/// started yet (`start` panics otherwise) — delegate to an
/// already-started coroutine with [`yield_all_resume!`].
///
/// The operand is either a variable whose type is syntactically known
/// (bind the coroutine with a type annotation first) or a direct call
/// of a coroutine function — `yield_all!(sub(x))`, whose delegate type
/// is derived from the callee path as `sub::State`, carrying a
/// turbofish over as its arguments (`sub::<u32>(x)` gives
/// `sub::State<u32>`). Two shapes are not derivable and need the
/// variable form: a generic coroutine called without a turbofish, and
/// one taking a reference (its state is generic over a lifetime the
/// outer state cannot elide). Any other expression is a compile error.
/// Supported positions are a
/// statement (`yield_all!(sub);`, completion value discarded), a whole
/// `let` initializer (`let x = yield_all!(sub);` — the binding's type
/// is derived from the operand, an explicit annotation wins), and a
/// trailing expression: the function body's, or that of a block,
/// `if`/`else` branch, or match arm that is itself in one of these
/// positions, recursively
/// (`let v: u32 = match x { A => yield_all!(sub), _ => 0 };`). In each
/// position the delegation may be followed by `?`
/// (`let v: T = yield_all!(sub)?;`), unwrapping the completion value
/// and exiting early on Err.
///
/// The inner coroutine's state enum is stored by value inside the outer
/// one, so `Clone` and serde derives compose: a coroutine suspended
/// inside a delegation serializes with the nested state included.
///
/// # Boxed delegation
///
/// `yield_all!(box sub)` stores the delegate boxed instead, which is
/// what makes *recursive* delegation representable — by-value storage
/// of a state inside itself would be infinitely sized. Boxing is lazy:
/// the delegate is started unboxed and boxed only if it actually
/// suspends, so a delegate that completes on entry never allocates.
/// Requires the `alloc` feature (enabled by default); the contract and
/// supported positions are otherwise identical to the unboxed form.
///
/// ```
/// use diapause::{Coroutine, CoroutineState};
///
/// #[diapause::coroutine(yield = u32)]
/// fn countdown(n: u32) {
/// yield_!(n);
/// if n > 0 {
/// yield_all!(box countdown(n - 1));
/// }
/// }
///
/// # fn main() {
/// let mut c = countdown(1);
/// assert_eq!(c.start(), CoroutineState::Yielded(1));
/// assert_eq!(c.resume(()), CoroutineState::Yielded(0));
/// assert_eq!(c.resume(()), CoroutineState::Complete(()));
/// # }
/// ```
///
/// Like [`yield_!`], this macro is consumed by the `#[coroutine]`
/// transformation and never expands on its own; using it outside a
/// `#[diapause::coroutine]` function is a compile error.
/// Delegates to an already-started coroutine inside a
/// `#[diapause::coroutine]` function.
///
/// `yield_all_resume!(sub, rv)` resumes the suspended coroutine held by
/// the variable `sub` with the resume value `rv`, then runs it to
/// completion exactly like [`yield_all!`]: every value it yields is
/// yielded to the caller, every resume value is forwarded back into it,
/// and the whole expression evaluates to its completion value. Where
/// `yield_all!` enters via [`Coroutine::start`] and requires a coroutine
/// that has not been started, `yield_all_resume!` enters via
/// [`Coroutine::resume`] and requires one that is suspended at a
/// `yield_!` (`resume` panics otherwise).
///
/// ```
/// use diapause::{Coroutine, CoroutineState};
///
/// #[diapause::coroutine(yield = u32, resume = u32)]
/// fn running_total(start: u32) -> u32 {
/// let a = yield_!(start);
/// let b = yield_!(start + a);
/// start + a + b
/// }
///
/// #[diapause::coroutine(yield = u32, resume = u32)]
/// fn outer(sub: running_total::State, rv: u32) -> u32 {
/// yield_all_resume!(sub, rv)
/// }
///
/// # fn main() {
/// let mut sub = running_total(100);
/// // The first yield is consumed here, before delegation begins.
/// assert_eq!(sub.start(), CoroutineState::Yielded(100));
/// let mut c = outer(sub, 1);
/// assert_eq!(c.start(), CoroutineState::Yielded(101));
/// assert_eq!(c.resume(2), CoroutineState::Complete(103));
/// # }
/// ```
///
/// The first operand must be a variable whose type is syntactically
/// known — [`yield_all!`]'s call form has no meaning here, since a
/// freshly called coroutine is never started. The resume value may be
/// any expression
/// not containing `yield_!`; it is consumed by the first `resume` call
/// before any suspension and is never stored in the state. The
/// supported positions are the same: a statement
/// (`yield_all_resume!(sub, rv);`, completion value discarded), a whole
/// `let` initializer, and a trailing expression (of the function body,
/// or of a block, `if`/`else` branch, or match arm in one of these
/// positions), each optionally followed by `?`. The `box` modifier
/// (`yield_all_resume!(box sub, rv)`) stores the delegate boxed with
/// the same lazy-boxing behavior as [`yield_all!`]'s (see *Boxed
/// delegation* there; requires the `alloc` feature).
///
/// Like [`yield_!`], this macro is consumed by the `#[coroutine]`
/// transformation and never expands on its own; using it outside a
/// `#[diapause::coroutine]` function is a compile error.