Scoop API

scoop:scoop.core:0.1.0

src/coroutine_execution.scoop

Selected production source · src/coroutine_execution.scoop

1private const val DRIVE_NEW: Int = 0
3private const val DRIVE_RUNNING: Int = 1
5private const val DRIVE_IDLE: Int = 2
7private const val DRIVE_QUEUED: Int = 3
9private const val DRIVE_TAKING: Int = 4
11private const val DRIVE_PUBLISHING: Int = 5
13private const val DRIVE_DETACHED: Int = 6
15private const val DRIVE_READY_INTERNAL: Int = 7
17private const val DRIVE_READY_EXTERNAL: Int = 8
19private const val DRIVE_FINISHING: Int = 9
21private const val DRIVE_FINISHED: Int = 10
23private enum CoroutineDriveAction {
24 Continue(CoroutineWork)
25 Dispatch
26 Stop
27 Complete(ExecutorTask?)
30// A drive owns all frame accesses, TaskContext changes and native catch cleanup.
31// Results may arrive concurrently, but another drive starts only after run exits.
32internal class CoroutineExecution(task: ExecutorTask?): CoroutineExecutionDriver, CoroutineWork {
33 private val state = AtomicInt(DRIVE_NEW)
34 private var registration: ExecutorTask? = task
35 private var pending: CoroutineWork? = None
37 // Only the current drive queries its registration. Completion clears it
38 // after that drive has left the frame and restored the resumer's context.
39 public override fun task(): ExecutorTask? = registration
41 public override fun start(work: CoroutineWork, dispatched: Boolean) {
42 val initial =
43 if (dispatched)
44 DRIVE_DETACHED
45 else
46 DRIVE_RUNNING
47 if (!state.compareAndSet(DRIVE_NEW, initial, MemoryOrder.AcqRel, MemoryOrder.Acquire))
48 throw IllegalStateException(Some("coroutine already started"))
49 if (dispatched) {
50 pending = Some(work)
51 state.store(DRIVE_QUEUED, MemoryOrder.Release)
52 schedule()
53 } else {
54 drive(work)
55 }
56 }
58 public override fun resume(work: CoroutineWork, external: Boolean) {
59 var current = state.load(MemoryOrder.Acquire)
60 if (!external) {
61 // The adapter compares execution identity, so this completion
62 // already owns the current drive and cannot race its exit.
63 if (current != DRIVE_RUNNING)
64 throw IllegalStateException(Some("coroutine is not waiting"))
65 pending = Some(work)
66 state.store(DRIVE_READY_INTERNAL, MemoryOrder.Release)
67 return
68 }
69 while (true) {
70 val claimed =
71 when (current) {
72 DRIVE_RUNNING -> DRIVE_PUBLISHING
73 DRIVE_IDLE -> DRIVE_DETACHED
74 else -> throw IllegalStateException(Some("coroutine is not waiting"))
75 }
76 val observed =
77 state.compareAndExchange(current, claimed, MemoryOrder.AcqRel, MemoryOrder.Acquire)
78 if (observed == current)
79 break
80 current = observed
81 }
82 pending = Some(work)
83 if (current == DRIVE_IDLE) {
84 state.store(DRIVE_QUEUED, MemoryOrder.Release)
85 schedule(true)
86 return
87 }
88 when (
89 state.compareAndExchange(
90 DRIVE_PUBLISHING,
91 DRIVE_READY_EXTERNAL,
92 MemoryOrder.AcqRel,
93 MemoryOrder.Acquire
94 )
95 ) {
96 DRIVE_PUBLISHING -> {}
97 DRIVE_DETACHED -> {
98 state.store(DRIVE_QUEUED, MemoryOrder.Release)
99 schedule(true)
100 }
101 DRIVE_FINISHED -> {
102 // The failed drive retired its registration while publication
103 // was in flight. Only this publisher may clear the slot now.
104 pending = None
105 }
106 else -> throw IllegalStateException(Some("coroutine lost its pending publication"))
107 }
108 }
110 internal fun finish() {
111 if (
112 !state.compareAndSet(
113 DRIVE_RUNNING,
114 DRIVE_FINISHING,
115 MemoryOrder.AcqRel,
116 MemoryOrder.Acquire
117 )
118 )
119 throw IllegalStateException(Some("coroutine has no unfinished drive"))
120 }
122 public override fun run() {
123 if (
124 !state.compareAndSet(
125 DRIVE_QUEUED,
126 DRIVE_TAKING,
127 MemoryOrder.AcqRel,
128 MemoryOrder.Acquire
129 )
130 )
131 throw IllegalStateException(Some("coroutine work is not queued"))
132 val work = pending!!
133 pending = None
134 state.store(DRIVE_RUNNING, MemoryOrder.Release)
135 drive(work)
136 }
138 private fun schedule(resuming: Boolean = false) {
139 // Capture before dispatch can run and retire this registration.
140 when (registration) {
141 case Some(val task) -> if (resuming)
142 task.dispatchResume(this)
143 else
144 task.dispatch(this)
145 case None -> run()
146 }
147 }
149 private fun drive(initial: CoroutineWork) {
150 var work = initial
151 while (true) {
152 val next =
153 try {
154 work.run()
155 afterDrive()
156 } catch (error: Throwable) {
157 completeRegistration(abortDrive())
158 throw error
159 }
160 when (next) {
161 case CoroutineDriveAction.Continue(val nextWork) -> work = nextWork
162 case CoroutineDriveAction.Dispatch -> {
163 schedule();
164 return
165 }
166 case CoroutineDriveAction.Stop -> return
167 case CoroutineDriveAction.Complete(val task) -> {
168 completeRegistration(task);
169 return
170 }
171 }
172 }
173 }
175 private fun afterDrive(): CoroutineDriveAction {
176 var current = state.load(MemoryOrder.Acquire)
177 while (true) {
178 when (current) {
179 DRIVE_RUNNING, DRIVE_PUBLISHING -> {
180 val released =
181 if (current == DRIVE_RUNNING)
182 DRIVE_IDLE
183 else
184 DRIVE_DETACHED
185 val observed =
186 state.compareAndExchange(
187 current,
188 released,
189 MemoryOrder.AcqRel,
190 MemoryOrder.Acquire
191 )
192 if (observed == current)
193 return CoroutineDriveAction.Stop
194 current = observed
195 }
196 DRIVE_READY_INTERNAL, DRIVE_READY_EXTERNAL -> {
197 if (current == DRIVE_READY_EXTERNAL && !coroutineAbsent(registration)) {
198 state.store(DRIVE_QUEUED, MemoryOrder.Release)
199 return CoroutineDriveAction.Dispatch
200 }
201 val work = pending!!
202 pending = None
203 state.store(DRIVE_RUNNING, MemoryOrder.Release)
204 return CoroutineDriveAction.Continue(work)
205 }
206 DRIVE_FINISHING -> {
207 val task = registration
208 registration = None
209 state.store(DRIVE_FINISHED, MemoryOrder.Release)
210 return CoroutineDriveAction.Complete(task)
211 }
212 else -> throw IllegalStateException(Some("coroutine lost its active drive"))
213 }
214 }
215 }
217 private fun abortDrive(): ExecutorTask? {
218 val previous = state.exchange(DRIVE_FINISHED, MemoryOrder.AcqRel)
219 if (previous != DRIVE_PUBLISHING && previous != DRIVE_DETACHED)
220 pending = None
221 val task = registration
222 registration = None
223 return task
224 }
226 private fun completeRegistration(task: ExecutorTask?) {
227 when (task) {
228 case Some(val task) -> task.complete()
229 case None -> {}
230 }
231 }
234// This real caller owns the root registration handshake, including when every
235// user suspend call tail-forwards the primitive to its original completion.
236internal class RootSuspendTask<T>(
237 private var task: SuspendTask<T>?,
238 private val completion: Continuation<T>
239): SuspendTask<Unit> {
240 public override suspend fun run() {
241 // The frame needs this object for completion, but must not keep the
242 // original task's unused captures alive after starting its body.
243 val body = task!!
244 task = None
245 val value =
246 try {
247 body.run()
248 }
249 catch (error: Throwable) {
250 completion.resumeWithException(error)
251 return
252 }
253 // Keep user completion outside the body catch: it must be notified once
254 // even if the notification itself throws.
255 completion.resume(value)
256 }
259internal class ExecutionCompletion(private val execution: CoroutineExecution): Continuation<Unit> {
260 public override fun resume(value: Unit) {
261 execution.finish()
262 }
263 public override fun resumeWithException(exception: Throwable) {
264 execution.finish()
265 throw exception
266 }