-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoroutine.go
More file actions
1187 lines (1060 loc) · 30.1 KB
/
coroutine.go
File metadata and controls
1187 lines (1060 loc) · 30.1 KB
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package async
import (
"iter"
"slices"
"sync"
)
type action int
const (
_ action = iota
doYield
doTransition
doTailTransition // Do transition and remove controller.
doEnd
doBreak
doContinue
doReturn
doRaise // Exit or panic.
)
const (
flagResumed = 1 << iota
flagEnqueued
flagCleanup
flagEnded
flagExiting
flagPanicking
flagCanceled
flagNonCancelable
flagNonRecyclable
)
type noCopy struct{}
func (*noCopy) Lock() {}
func (*noCopy) Unlock() {}
// A Coroutine is an execution of code, similar to a goroutine but cooperative
// and stackless.
//
// A coroutine is created with a function called [Task].
// A coroutine's job is to complete the task.
// When an [Executor] spawns a coroutine with a task, it runs the coroutine by
// calling the task function with the coroutine as the argument.
// The return value determines whether to end the coroutine or to yield it
// so that it could resume later.
//
// In order for a coroutine to resume, the coroutine must watch at least one
// [Event] (e.g. [Signal], [State], etc.), when calling the task function.
// A notification of such an event resumes the coroutine.
// When a coroutine is resumed, the executor runs the coroutine again.
//
// A coroutine can also make a transition to work on another task according to
// the return value of the task function.
// A coroutine can transition from one task to another until a task ends it.
type Coroutine struct {
_ noCopy
flag uint16
level uint16
childnum uint32
weight Weight
parent *Coroutine
executor *Executor
wg *sync.WaitGroup
ps panicstack
guard func() bool
task Task
deps map[Event]struct{}
cleanups []Cleanup
defers []Task
controllers []controller
}
type Weight int64
var coroutinePool = sync.Pool{
New: func() any { return new(Coroutine) },
}
func newCoroutine() *Coroutine {
return coroutinePool.Get().(*Coroutine)
}
func freeCoroutine(co *Coroutine) {
if co.flag&flagNonRecyclable != 0 {
return
}
co.flag |= flagNonRecyclable
co.parent = nil
co.executor = nil
wg := co.wg
co.wg = nil
clear(co.ps)
co.ps = co.ps[:0]
co.task = nil
coroutinePool.Put(co)
if wg != nil {
wg.Done()
}
}
func (co *Coroutine) init(l uint16, w Weight, e *Executor, t Task) *Coroutine {
co.flag = flagResumed
co.level = l
co.weight = w
co.executor = e
co.task = t
return co
}
func compare[Int intType](x, y Int) int {
if x < y {
return -1
}
if x > y {
return +1
}
return 0
}
func (co *Coroutine) less(other *Coroutine) bool {
if c := compare(co.weight, other.weight); c != 0 {
return c == +1
}
return co.level < other.level
}
// Resume resumes co.
func (co *Coroutine) Resume() {
co.executor.resumeCoroutine(co, true)
}
func (e *Executor) resumeCoroutine(co *Coroutine, lock bool) {
switch flag := co.flag; {
case flag&flagEnqueued != 0:
co.flag = flag | flagResumed
default:
co.flag = flag | flagResumed | flagEnqueued
if lock {
e.mu.Lock()
}
e.pq.Push(co)
if lock {
e.mu.Unlock()
}
}
}
func (e *Executor) runCoroutine(co *Coroutine) {
flag := co.flag
flag &^= flagEnqueued
co.flag = flag
switch {
case flag&flagEnded != 0:
freeCoroutine(co)
case flag&flagResumed != 0:
e.mu.Unlock()
co.run()
e.mu.Lock()
}
}
func (co *Coroutine) run() (suspended bool) {
var res Result
ps := &co.ps
guard := co.guard
for {
if guard != nil {
var ok bool
co.flag &^= flagResumed
if !ps.Try(func() { ok = guard() }) {
co.flag |= flagPanicking
co.task = (*Coroutine).raise
ok = true
}
if !ok {
return true
}
guard = nil
co.guard = nil
}
co.flag &^= flagResumed
co.flag |= flagCleanup
co.clearDeps()
co.clearCleanups()
if co.childnum != 0 {
return true
}
co.flag &^= flagResumed | flagCleanup
if !ps.Try(func() { res = co.task(co) }) {
res = co.panic()
}
if res.action == doYield && co.flag&(flagCanceled|flagNonCancelable) == flagCanceled {
res = co.cancel()
}
if res.action != doYield && res.action != doTransition {
co.flag &^= flagResumed
co.flag |= flagCleanup
co.clearDeps()
co.clearCleanups()
if co.childnum != 0 {
co.task = actionToTask(res.action)
return true
}
co.flag &^= flagResumed | flagCleanup
if co.Panicking() {
res = co.raise()
}
controllers := co.controllers
for len(controllers) != 0 {
i := len(controllers) - 1
c := &controllers[i]
if !ps.Try(func() { res = c.negotiate(co, res) }) {
res = c.negotiate(co, co.panic())
}
if res.action != doTransition {
if !ps.Try(c.cleanup) {
res = co.panic()
}
controllers[i] = controller{}
controllers = controllers[:i]
co.controllers = controllers
}
if res.action == doTransition || res.action == doTailTransition {
break
}
}
if res.action != doTransition && res.action != doTailTransition {
rootController := &controller{kind: funcController}
if !ps.Try(func() { res = rootController.negotiate(co, res) }) {
res = rootController.negotiate(co, co.panic())
}
}
if res.action == doTailTransition {
res.action = doTransition
}
}
if res.task != nil {
co.task = res.task
}
if res.guard != nil {
guard = res.guard
co.guard = guard
continue // For calling guard immediately.
}
if res.controller.kind != 0 {
addController := true
if res.controller.kind == funcController && !res.controller.wasExiting && !res.controller.wasPanicking {
lastController := &controller{kind: funcController}
if n := len(co.controllers); n != 0 {
lastController = &co.controllers[n-1]
}
if lastController.kind == funcController && lastController.numDefer == res.controller.numDefer {
// Tail-call optimization:
// If the last controller is also a funcController, do not add another one.
// (doTailTransition also pays tribute to this optimization.)
addController = false
}
}
if addController {
co.controllers = append(co.controllers, res.controller)
if capSizeLimit := 1000000; cap(co.controllers) > capSizeLimit {
co.flag |= flagNonRecyclable
co.task = func(co *Coroutine) Result {
panic("async: too many controllers or recursions")
}
}
}
}
if res.action != doTransition {
break
}
}
if res.action == doYield {
return true
}
co.flag |= flagEnded
parent := co.parent
if parent != nil {
if i := slices.Index(parent.cleanups, Cleanup((*childCoroutineCleanup)(co))); i != -1 {
parent.cleanups = slices.Delete(parent.cleanups, i, i+1)
}
parent.childnum--
if parent.childnum == 0 && parent.flag&flagCleanup != 0 {
parent.Resume()
}
}
if co.Panicking() {
if parent != nil {
parent.flag |= flagPanicking
parent.guard = nil
parent.task = (*Coroutine).raise
parent.ps = append(parent.ps, co.ps...)
parent.Resume()
} else {
co.executor.ps = append(co.executor.ps, co.ps...)
}
}
if len(co.deps) != 0 {
panic("async: internal error: deps did not clear")
}
if len(co.cleanups) != 0 {
panic("async: internal error: cleanups did not clear")
}
if len(co.defers) != 0 {
panic("async: internal error: defers did not clear")
}
if len(co.controllers) != 0 {
panic("async: internal error: controllers did not clear")
}
if co.childnum != 0 {
panic("async: internal error: child coroutines did not clear")
}
if co.flag&flagEnqueued == 0 {
freeCoroutine(co)
}
return false
}
func (co *Coroutine) clearDeps() {
deps := co.deps
for d := range deps {
delete(deps, d)
d.removeListener(co)
}
}
func (co *Coroutine) clearCleanups() {
ok := true
cleanups := co.cleanups
for len(co.cleanups) != 0 {
cleanups := co.cleanups
co.cleanups = nil
for _, c := range slices.Backward(cleanups) {
ok = co.ps.Try(c.Cleanup) && ok
}
}
clear(cleanups)
co.cleanups = cleanups[:0]
if !ok {
co.flag |= flagPanicking
co.task = (*Coroutine).raise
}
}
type childCoroutineCleanup Coroutine
func (child *childCoroutineCleanup) Cleanup() {
co := (*Coroutine)(child)
co.flag |= flagCanceled
if !co.NonCancelable() {
co.flag |= flagExiting
co.guard = nil
co.task = (*Coroutine).raise
co.run()
}
}
// Weight returns the weight of co.
func (co *Coroutine) Weight() Weight {
return co.weight
}
// Parent returns the parent coroutine of co.
//
// Note that a coroutine must not escape to a non-child coroutine or another
// goroutine because, a coroutine may be put into pool for later reuse when
// it completes.
func (co *Coroutine) Parent() *Coroutine {
return co.parent
}
// Executor returns the executor that spawned co.
func (co *Coroutine) Executor() *Executor {
return co.executor
}
// Resumed reports whether co has been resumed.
func (co *Coroutine) Resumed() bool {
return co.flag&flagResumed != 0
}
// Exiting reports whether co is exiting.
//
// When exiting, entering a [Func], in a deferred task, would temporarily
// reset Exiting to false until that [Func] ends or exits again.
func (co *Coroutine) Exiting() bool {
return co.flag&flagExiting != 0
}
// Panicking reports whether co is panicking.
//
// When panicking, entering a [Func], in a deferred task, would temporarily
// reset Panicking to false until that [Func] ends or panics again.
func (co *Coroutine) Panicking() bool {
return co.flag&flagPanicking != 0
}
// Canceled reports whether co has been canceled.
func (co *Coroutine) Canceled() bool {
return co.flag&flagCanceled != 0
}
// NonCancelable reports whether co is currently running a [NonCancelable] task.
func (co *Coroutine) NonCancelable() bool {
return co.flag&flagNonCancelable != 0
}
// Watch watches some events so that, when any of them notifies, co resumes.
func (co *Coroutine) Watch(ev ...Event) {
switch flag := co.flag; {
case flag&flagCleanup != 0:
panic("async: watch during cleanup")
case flag&(flagCanceled|flagNonCancelable) == flagCanceled:
return
}
var deps map[Event]struct{}
for _, d := range ev {
if deps == nil {
deps = co.deps
if deps == nil {
deps = make(map[Event]struct{})
co.deps = deps
}
}
deps[d] = struct{}{}
d.addListener(co)
}
}
// Cleanup represents any type that carries a Cleanup method.
// A Cleanup can be added to a coroutine in a [Task] function for making
// an effect some time later when the coroutine resumes or finishes a [Task].
type Cleanup interface {
Cleanup()
}
// A CleanupFunc is a func() that implements the [Cleanup] interface.
type CleanupFunc func()
// Cleanup implements the [Cleanup] interface.
func (f CleanupFunc) Cleanup() { f() }
// Cleanup adds something to clean up when co resumes or finishes a [Task].
func (co *Coroutine) Cleanup(c Cleanup) {
if c == nil {
return
}
co.cleanups = append(co.cleanups, c)
}
// CleanupFunc adds a function call when co resumes or finishes a [Task].
func (co *Coroutine) CleanupFunc(f func()) {
if f == nil {
return
}
co.cleanups = append(co.cleanups, CleanupFunc(f))
}
// Defer adds a [Task] for execution when returning from a [Func].
// Deferred tasks are executed in last-in-first-out (LIFO) order.
func (co *Coroutine) Defer(t Task) {
if t == nil {
return
}
co.defers = append(co.defers, t)
}
// Recover returns the latest value in the panic stack and stops co from
// panicking.
// If co isn't panicking, Recover returns nil.
//
// One might be tempted to use the built-in panic function and this method to
// mimic the power of try-catch statement in some other programming languages,
// but there's a cost.
// In order to be able to continue running, when there's a panic, a coroutine
// immediately recovers it and puts it into the panic stack, along with a stack
// trace returned by [runtime/debug.Stack], which might take thousands of bytes.
//
// Instead of using the built-in panic function to trigger a panic, one could
// consider use [Coroutine.Panic] to mimic one, which leaves no stack trace
// behind.
func (co *Coroutine) Recover() (v any) {
switch flag := co.flag; {
case flag&flagCleanup != 0:
panic("async: recover during cleanup")
case flag&flagPanicking == 0:
return nil
}
p := &co.ps[len(co.ps)-1]
p.recovered = true
co.flag &^= flagPanicking
return p.value
}
// RecoverFunc is like [Coroutine.Recover] but only recovers the recent panic
// that satisfies a condition.
func (co *Coroutine) RecoverFunc(f func(v any) bool) (v any) {
switch flag := co.flag; {
case flag&flagCleanup != 0:
panic("async: recover during cleanup")
case flag&flagPanicking == 0:
return nil
}
p := &co.ps[len(co.ps)-1]
if f(p.value) {
p.recovered = true
co.flag &^= flagPanicking
v = p.value
}
return v
}
// Spawn creates a child coroutine with the same weight as co to work on t.
//
// Spawn runs t immediately. If t panics immediately, Spawn panics, too.
//
// Child coroutines, if not yet ended, are canceled when the parent one resumes
// or finishes a [Task].
// When a coroutine is canceled, it runs to completion with all yield points
// treated like exit points.
//
// However, within a [NonCancelable] context, a canceled coroutine is allowed
// to yield, which correspondingly causes its parent coroutine to yield, too.
// In such case, the parent coroutine stays suspended until all its child
// coroutines complete.
func (co *Coroutine) Spawn(t Task) {
level := co.level + 1
if level == 0 {
panic("async: too many levels")
}
if co.childnum+1 == 0 {
panic("async: too many child coroutines")
}
child := newCoroutine().init(level, co.weight, co.executor, t)
child.parent = co
co.childnum++
switch suspended := child.run(); {
case suspended:
co.cleanups = append(co.cleanups, (*childCoroutineCleanup)(child))
case co.Panicking():
// child panics.
panic(dummy{}) // Stop current task.
}
}
// Result is the type of the return value of a [Task] function.
// A Result determines what next for a coroutine to do after running a task.
//
// A Result can be created by calling one of the following methods:
// - [Coroutine.Await]: for creating a [PendingResult] that can be transformed
// into a [Result] with one of its methods, which will then cause
// the running coroutine to yield;
// - [Coroutine.Yield]: for yielding a coroutine with additional events to
// watch and, when resumed, reiterating the running task;
// - [Coroutine.Transition]: for making a transition to work on another task;
// - [Coroutine.End]: for ending the running task of a coroutine;
// - [Coroutine.Break]: for breaking a [Loop] (or [LoopN]);
// - [Coroutine.Continue]: for continuing a [Loop] (or [LoopN]);
// - [Coroutine.Return]: for returning from a [Func];
// - [Coroutine.Exit]: for exiting a coroutine;
// - [Coroutine.Panic]: for simulating a panic.
//
// These methods may have side effects. One should never store a Result in
// a variable and overwrite it with another, before returning it. Instead,
// one should just return a Result right after it is created.
type Result struct {
action action
guard func() bool // used by doYield only
task Task // used by doYield, doTransition and doTailTransition
controller controller // used by doTransition only
}
// PendingResult is the return type of the [Coroutine.Await] method.
// A PendingResult is an intermediate value that must be transformed into
// a [Result] with one of its methods before returning from a [Task].
type PendingResult struct {
res Result
}
// Reiterate returns a [Result] that will cause the running coroutine to yield
// and, when resumed, reiterate the running task.
func (pr PendingResult) Reiterate() Result {
return pr.res
}
// Then returns a [Result] that will cause the running coroutine to yield and,
// when resumed, make a transition to work on another [Task].
func (pr PendingResult) Then(t Task) Result {
pr.res.task = must(t)
return pr.res
}
// End returns a [Result] that will cause the running coroutine to yield and,
// when resumed, end the running task.
func (pr PendingResult) End() Result {
return pr.Then(End())
}
// Break returns a [Result] that will cause the running coroutine to yield and,
// when resumed, break a [Loop] (or [LoopN]).
func (pr PendingResult) Break() Result {
return pr.Then(Break())
}
// Continue returns a [Result] that will cause the running coroutine to yield
// and, when resumed, continue a [Loop] (or [LoopN]).
func (pr PendingResult) Continue() Result {
return pr.Then(Continue())
}
// Return returns a [Result] that will cause the running coroutine to yield and,
// when resumed, return from a [Func].
func (pr PendingResult) Return() Result {
return pr.Then(Return())
}
// Exit returns a [Result] that will cause the running coroutine to yield and,
// when resumed, cause the running coroutine to exit.
func (pr PendingResult) Exit() Result {
return pr.Then(Exit())
}
// Panic returns a [Result] that will cause the running coroutine to yield and,
// when resumed, cause the running coroutine to behave like there's a panic.
// Unlike the built-in panic function, Panic leaves no stack trace behind.
// Please use with caution.
func (pr PendingResult) Panic(v any) Result {
return pr.Then(Panic(v))
}
// Until transforms pr into one with a condition.
// Affected coroutines remain suspended until the condition is met.
func (pr PendingResult) Until(f func() bool) PendingResult {
pr.res.guard = f
return pr
}
// Await returns a [PendingResult] that can be transformed into a [Result]
// with one of its methods, which will then cause co to yield.
// Await also accepts additional events to watch.
func (co *Coroutine) Await(ev ...Event) PendingResult {
if len(ev) != 0 {
co.Watch(ev...)
}
return PendingResult{res: Result{action: doYield}}
}
// Yield returns a [Result] that will cause co to yield and, when co is resumed,
// reiterate the running task.
// Yield also accepts additional events to watch.
func (co *Coroutine) Yield(ev ...Event) Result {
return co.Await(ev...).Reiterate()
}
// Transition returns a [Result] that will cause co to make a transition to
// work on t.
func (co *Coroutine) Transition(t Task) Result {
return Result{action: doTransition, task: must(t)}
}
// End returns a [Result] that will cause co to end its current running task.
func (co *Coroutine) End() Result {
return Result{action: doEnd}
}
// Break returns a [Result] that will cause co to break a [Loop] (or [LoopN]).
func (co *Coroutine) Break() Result {
return Result{action: doBreak}
}
// Continue returns a [Result] that will cause co to continue a [Loop]
// (or [LoopN]).
func (co *Coroutine) Continue() Result {
return Result{action: doContinue}
}
// Return returns a [Result] that will cause co to return from a [Func].
func (co *Coroutine) Return() Result {
return Result{action: doReturn}
}
// Exit returns a [Result] that will cause co to exit.
// All deferred tasks will be run before co exits.
func (co *Coroutine) Exit() Result {
co.flag |= flagExiting
return Result{action: doRaise}
}
func (co *Coroutine) cancel() Result {
co.flag |= flagExiting | flagCanceled
return Result{action: doRaise}
}
func (co *Coroutine) panic() Result {
co.flag |= flagPanicking
return Result{action: doRaise}
}
func (co *Coroutine) raise() Result {
return Result{action: doRaise}
}
// Panic returns a [Result] that will cause co to behave like there's a panic.
// Unlike the built-in panic function, Panic leaves no stack trace behind.
// Please use with caution.
func (co *Coroutine) Panic(v any) Result {
if v == nil {
panic("async: Panic called with nil argument")
}
co.ps.push(v, nil)
co.flag |= flagPanicking
return Result{action: doRaise}
}
type controllerKind int8
const (
_ controllerKind = iota
funcController
thenController
blockController
loopController
seqController
ncController
)
type controller struct {
kind controllerKind
wasExiting bool // used by funcController only
wasPanicking bool // used by funcController only
numPanic int // used by funcController only
numDefer int // used by funcController only
task Task // used by thenController and loopController
tasks []Task // used by blockController only
next func() (Task, bool) // used by seqController only
stop func() // used by seqController only
}
func (c *controller) negotiate(co *Coroutine, res Result) Result {
switch c.kind {
case funcController:
switch res.action {
case doEnd, doReturn, doRaise:
if !co.Panicking() && len(co.ps) > c.numPanic {
// Discard recovered panic values.
clear(co.ps[c.numPanic:])
co.ps = co.ps[:c.numPanic]
}
if len(co.defers) > c.numDefer {
i := len(co.defers) - 1
t := co.defers[i]
co.defers[i] = nil
co.defers = co.defers[:i]
return co.Transition(t)
}
raise := co.flag&(flagExiting|flagPanicking) != 0
if c.wasExiting {
co.flag |= flagExiting
}
if c.wasPanicking {
co.flag |= flagPanicking
}
if raise {
return co.raise()
}
return co.End()
case doBreak:
panic("async: unhandled break action")
case doContinue:
panic("async: unhandled continue action")
default:
panic("async: internal error: unknown action")
}
case thenController:
if res.action != doEnd {
return res
}
return Result{action: doTailTransition, task: c.task}
case blockController:
if res.action != doEnd || len(c.tasks) == 0 {
return res
}
t := c.tasks[0]
c.tasks = c.tasks[1:]
action := doTransition
if len(c.tasks) == 0 {
action = doTailTransition
}
return Result{action: action, task: must(t)}
case loopController:
switch res.action {
case doEnd:
return co.Transition(c.task)
case doBreak:
return co.End()
case doContinue:
return co.Transition(c.task)
default:
return res
}
case seqController:
if res.action == doEnd {
if t, ok := c.next(); ok {
return co.Transition(t)
}
}
return res
case ncController:
co.flag &^= flagNonCancelable
return res
default:
panic("async: internal error: unknown controller")
}
}
func (c *controller) cleanup() {
switch c.kind {
case seqController:
c.stop()
}
}
// A Task is a piece of work that a coroutine is given to do when it is spawned.
// The return value of a task, a [Result], determines what next for a coroutine
// to do.
//
// The argument co must not escape to a non-child coroutine or another goroutine
// because, co may be put into pool for later reuse when co completes.
type Task func(co *Coroutine) Result
// Then returns a [Task] that first works on t, then next after t ends.
//
// To chain multiple tasks, use [Block] function.
func (t Task) Then(next Task) Task {
return func(co *Coroutine) Result {
return Result{
action: doTransition,
task: must(t),
controller: controller{kind: thenController, task: must(next)},
}
}
}
// Do returns a [Task] that calls f, and then ends.
func Do(f func()) Task {
return func(co *Coroutine) Result {
f()
return co.End()
}
}
// End returns a [Task] that ends without doing anything.
func End() Task {
return (*Coroutine).End
}
// Await returns a [Task] that awaits some events until any of them notifies,
// and then ends.
// If ev is empty, Await returns a [Task] that never ends.
func Await(ev ...Event) Task {
if len(ev) == 0 {
// Return a pure function instead.
return func(co *Coroutine) Result {
return co.Await().End()
}
}
return func(co *Coroutine) Result {
return co.Await(ev...).End()
}
}
// Block returns a [Task] that runs each of the given tasks in sequence.
// When one task ends, Block runs another.
func Block(s ...Task) Task {
switch len(s) {
case 0:
return End()
case 1:
return s[0]
case 2:
return s[0].Then(s[1])
}
return func(co *Coroutine) Result {
return Result{
action: doTransition,
task: must(s[0]),
controller: controller{kind: blockController, tasks: s[1:]},
}
}
}
// Break returns a [Task] that breaks a [Loop] (or [LoopN]).
func Break() Task {
return (*Coroutine).Break
}
// Continue returns a [Task] that continues a [Loop] (or [LoopN]).
func Continue() Task {
return (*Coroutine).Continue
}
// Loop returns a [Task] that forms a loop, which would run t repeatedly.
// Both [Coroutine.Break] and [Break] can break this loop early.
// Both [Coroutine.Continue] and [Continue] can continue this loop early.
func Loop(t Task) Task {
return func(co *Coroutine) Result {
return Result{
action: doTransition,
task: must(t),
controller: controller{kind: loopController, task: t},
}
}
}
// LoopN returns a [Task] that forms a loop, which would run t repeatedly
// for n times.
// Both [Coroutine.Break] and [Break] can break this loop early.
// Both [Coroutine.Continue] and [Continue] can continue this loop early.
func LoopN[Int intType](n Int, t Task) Task {
return func(co *Coroutine) Result {
i := Int(0)
f := func(co *Coroutine) Result {
if i < n {
i++
return co.Transition(t)
}
return co.Break()
}
return Result{
action: doTransition,
task: f,
controller: controller{kind: loopController, task: f},
}
}
}
type intType interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
// Defer returns a [Task] that adds t for execution when returning from
// a [Func].
// Deferred tasks are executed in last-in-first-out (LIFO) order.
func Defer(t Task) Task {
return func(co *Coroutine) Result {
co.Defer(t)
return co.End()
}
}
// Return returns a [Task] that returns from a surrounding [Func].
func Return() Task {
return (*Coroutine).Return
}
// Exit returns a [Task] that causes the coroutine that runs it to exit.
// All deferred tasks are run before the coroutine exits.
func Exit() Task {
return (*Coroutine).Exit
}
// Panic returns a [Task] that causes the coroutine that runs it to behave