Scoop API

scoop:scoop.core:0.1.0

src/coroutine_scope.scoop

Selected production source · src/coroutine_scope.scoop

1/**
2 * A structured child job carrying one eventual result or failure.
3 */
4public class Deferred<T> internal constructor(parent: Job?, propagatesFailure: Boolean = true): Job(
5 parent,
6 propagatesFailure
7) {
8 private var result: MaybeUninit<T> = MaybeUninit<T>.uninit()
10 internal fun succeed(value: T) {
11 result = MaybeUninit<T>.initialized(value)
12 finishBody(None)
13 }
15 internal fun getCompleted(): T {
16 when (finalFailure()) {
17 case Some(val error) -> throw error
18 case None -> @Unsafe
19 {
20 return result.assumeInit()
21 }
22 }
23 }
25 /**
26 * Waits for completion and returns the result, or rethrows its failure.
27 */
28 public suspend fun await(): T {
29 join()
30 return getCompleted()
31 }
34private enum CoroutineScopeState {
35 Open(ExecutorTask?)
36 Closed
39/** Launches child computations associated with one parent job and a default executor. */
40public class CoroutineScope internal constructor(
41 /**
42 * The parent used for children launched through this scope.
43 */
44 public val job: Job,
45 private val executor: CoroutineExecutor?
46) {
47 private val lock: CoroutineLock = CoroutineLock()
48 private var state: CoroutineScopeState = CoroutineScopeState.Open(None)
50 internal fun enter() {
51 val registration = currentExecutorTask()
52 lock.withLock { state = CoroutineScopeState.Open(registration) }
53 }
55 internal fun close() {
56 lock.withLock { state = CoroutineScopeState.Closed }
57 }
59 private fun parentRegistration(): ExecutorTask? =
60 lock.withLock {
61 when (state) {
62 case CoroutineScopeState.Open(val parent) -> parent
63 case CoroutineScopeState.Closed -> throw IllegalStateException(
64 Some("coroutine scope is closed")
65 )
66 }
67 }
69 /**
70 * Starts a child returning Unit and returns its job for cancellation or joining.
71 */
72 public fun launch(block: suspend CoroutineScope.() -> Unit): Job = async(block)
74 /** Starts a child on the selected executor while retaining this scope's job parent. */
75 public fun launch(executor: CoroutineExecutor, block: suspend CoroutineScope.() -> Unit): Job =
76 async(executor, block)
78 /**
79 * Starts a child that produces a result and returns a deferred handle.
80 */
81 public fun <T> async(block: suspend CoroutineScope.() -> T): Deferred<T> =
82 startStructuredTask(
83 Some(job),
84 executor,
85 parentRegistration(),
86 !coroutineAbsent(executor),
87 true,
88 block
89 )
91 /** Starts a child returning a result on the selected executor. */
92 public fun <T> async(
93 executor: CoroutineExecutor,
94 block: suspend CoroutineScope.() -> T
95 ): Deferred<T> =
96 startStructuredTask(Some(job), Some(executor), parentRegistration(), true, true, block)
99/**
100 * Returns the job installed for the currently running coroutine, or None outside a job context.
101 */
102public fun currentJobOrNone(): Job? = contextOrNone<Job>()
104/**
105 * Checks cancellation of the current job. With no current job, this operation does nothing.
106 */
107public fun ensureActive() {
108 when (currentJobOrNone()) {
109 case Some(val job) -> job.ensureActive()
110 case None -> {}
111 }
114private fun <T> startStructuredTask(
115 parent: Job?,
116 executor: CoroutineExecutor?,
117 preferredRegistration: ExecutorTask?,
118 dispatched: Boolean,
119 propagatesFailure: Boolean,
120 block: suspend CoroutineScope.() -> T
121): Deferred<T> {
122 val task = Deferred<T>(parent, propagatesFailure)
123 when (parent) {
124 case Some(val owner) -> owner.attach(task)
125 case None -> {}
126 }
127 val job: Job = task
128 val scope = CoroutineScope(job, executor)
129 val execution =
130 try {
131 prepareCoroutineExecution(executor, preferredRegistration)
132 } catch (error: Throwable) {
133 scope.close()
134 task.finishBody(Some(error))
135 throw error
136 }
137 context(job) {
138 startCoroutineTask(
139 execution,
140 dispatched,
141 FunctionSuspendTask<T>({ runScopeBody(scope, block) }),
142 StructuredCompletion<T>(task)
143 )
144 }
145 return task
148private suspend fun <T> runScopeBody(
149 scope: CoroutineScope,
150 block: suspend CoroutineScope.() -> T
151): T {
152 scope.enter()
153 try {
154 scope.job.ensureActive()
155 return block(scope)
156 } finally {
157 scope.close()
158 }
161private class StructuredCompletion<T>(val task: Deferred<T>): Continuation<T> {
162 public override fun resume(value: T) {
163 task.succeed(value)
164 }
165 public override fun resumeWithException(exception: Throwable) {
166 task.finishBody(Some(exception))
167 }
170/**
171 * Runs a block in a child scope and waits for its children before returning the block's result.
172 */
173public suspend fun <T> coroutineScope(block: suspend CoroutineScope.() -> T): T =
174 runCoroutineScope(currentJobOrNone(), block)
176/**
177 * Runs a structured scope detached from parent cancellation. The scope still owns a job whose own
178 * cancellation and child completion rules apply.
179 */
180public suspend fun <T> nonCancellableScope(block: suspend CoroutineScope.() -> T): T =
181 runCoroutineScope(None, block)
183/** Runs a structured child scope on the selected executor and waits for all of its children. */
184public suspend fun <T> withExecutor(
185 executor: CoroutineExecutor,
186 block: suspend CoroutineScope.() -> T
187): T {
188 val task =
189 startStructuredTask(
190 currentJobOrNone(),
191 Some(executor),
192 currentExecutorTask(),
193 true,
194 false,
195 block
196 )
197 task.joinUncancelled()
198 return task.getCompleted()
201private suspend fun <T> runCoroutineScope(parent: Job?, block: suspend CoroutineScope.() -> T): T {
202 val task = Deferred<T>(parent, false)
203 parent?.attach(task)
204 val job: Job = task
205 val scope = CoroutineScope(job, currentCoroutineExecutorOrNone())
206 context(job) {
207 val result =
208 try {
209 Some(runScopeBody(scope, block))
210 }
211 catch (error: Throwable) {
212 task.finishBody(Some(error))
213 None
214 }
215 // A failed completion notification must not complete the body a second time.
216 when (result) {
217 case Some(val value) -> task.succeed(value)
218 case None -> {}
219 }
220 }
221 task.joinUncancelled()
222 return task.getCompleted()