scoop:scoop.core:0.1.0
src/coroutine_execution.scoop
Selected production source · src/coroutine_execution.scoop
1
private const val DRIVE_NEW: Int = 03
private const val DRIVE_RUNNING: Int = 15
private const val DRIVE_IDLE: Int = 27
private const val DRIVE_QUEUED: Int = 39
private const val DRIVE_TAKING: Int = 411
private const val DRIVE_PUBLISHING: Int = 513
private const val DRIVE_DETACHED: Int = 615
private const val DRIVE_READY_INTERNAL: Int = 717
private const val DRIVE_READY_EXTERNAL: Int = 819
private const val DRIVE_FINISHING: Int = 921
private const val DRIVE_FINISHED: Int = 1023
private enum CoroutineDriveAction {24
Continue(CoroutineWork)25
Dispatch26
Stop27
Complete(ExecutorTask?)28
}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.32
internal class CoroutineExecution(task: ExecutorTask?): CoroutineExecutionDriver, CoroutineWork {33
private val state = AtomicInt(DRIVE_NEW)34
private var registration: ExecutorTask? = task35
private var pending: CoroutineWork? = None37
// Only the current drive queries its registration. Completion clears it38
// after that drive has left the frame and restored the resumer's context.39
public override fun task(): ExecutorTask? = registration41
public override fun start(work: CoroutineWork, dispatched: Boolean) {42
val initial =43
if (dispatched)44
DRIVE_DETACHED45
else46
DRIVE_RUNNING47
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 completion62
// 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
return68
}69
while (true) {70
val claimed =71
when (current) {72
DRIVE_RUNNING -> DRIVE_PUBLISHING73
DRIVE_IDLE -> DRIVE_DETACHED74
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
break80
current = observed81
}82
pending = Some(work)83
if (current == DRIVE_IDLE) {84
state.store(DRIVE_QUEUED, MemoryOrder.Release)85
schedule(true)86
return87
}88
when (89
state.compareAndExchange(90
DRIVE_PUBLISHING,91
DRIVE_READY_EXTERNAL,92
MemoryOrder.AcqRel,93
MemoryOrder.Acquire94
)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 publication103
// was in flight. Only this publisher may clear the slot now.104
pending = None105
}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.Acquire117
)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.Acquire129
)130
)131
throw IllegalStateException(Some("coroutine work is not queued"))132
val work = pending!!133
pending = None134
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
else144
task.dispatch(this)145
case None -> run()146
}147
}149
private fun drive(initial: CoroutineWork) {150
var work = initial151
while (true) {152
val next =153
try {154
work.run()155
afterDrive()156
} catch (error: Throwable) {157
completeRegistration(abortDrive())158
throw error159
}160
when (next) {161
case CoroutineDriveAction.Continue(val nextWork) -> work = nextWork162
case CoroutineDriveAction.Dispatch -> {163
schedule();164
return165
}166
case CoroutineDriveAction.Stop -> return167
case CoroutineDriveAction.Complete(val task) -> {168
completeRegistration(task);169
return170
}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_IDLE183
else184
DRIVE_DETACHED185
val observed =186
state.compareAndExchange(187
current,188
released,189
MemoryOrder.AcqRel,190
MemoryOrder.Acquire191
)192
if (observed == current)193
return CoroutineDriveAction.Stop194
current = observed195
}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.Dispatch200
}201
val work = pending!!202
pending = None203
state.store(DRIVE_RUNNING, MemoryOrder.Release)204
return CoroutineDriveAction.Continue(work)205
}206
DRIVE_FINISHING -> {207
val task = registration208
registration = None209
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 = None221
val task = registration222
registration = None223
return task224
}226
private fun completeRegistration(task: ExecutorTask?) {227
when (task) {228
case Some(val task) -> task.complete()229
case None -> {}230
}231
}232
}234
// This real caller owns the root registration handshake, including when every235
// user suspend call tail-forwards the primitive to its original completion.236
internal 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 the242
// original task's unused captures alive after starting its body.243
val body = task!!244
task = None245
val value =246
try {247
body.run()248
}249
catch (error: Throwable) {250
completion.resumeWithException(error)251
return252
}253
// Keep user completion outside the body catch: it must be notified once254
// even if the notification itself throws.255
completion.resume(value)256
}257
}259
internal 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 exception266
}267
}