-
Notifications
You must be signed in to change notification settings - Fork 451
/
Copy pathRaise.kt
400 lines (370 loc) · 12.8 KB
/
Raise.kt
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
@file:OptIn(ExperimentalTypeInference::class)
package arrow.core.continuations
import arrow.core.Either
import arrow.core.EmptyValue
import arrow.core.NonEmptyList
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
import arrow.core.emptyCombine
import arrow.core.identity
import arrow.core.nel
import arrow.typeclasses.Semigroup
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.experimental.ExperimentalTypeInference
import kotlin.jvm.JvmName
@DslMarker
public annotation class EffectDSL
/**
* The [Raise] DSL allows you to work with _logical failures_ of type [R].
* A _logical failure_ does not necessarily mean that the computation has failed,
* but that it has stopped or _short-circuited_.
*
* The [Raise] DSL allows you to [raise] _logical failure_ of type [R], and you can [recover] from them.
*
* ```kotlin
* fun Raise<String>.failure(): Int = raise("failed")
*
* fun Raise<Nothing>.recovered(): String =
* recover({ program() }) { failure: String ->
* "Recovered from $failure"
* }
* ```
*
* Above we defined a function `failure` that raises a logical failure of type [String] with value `"failed"`.
* And in the function `recovered` we recover from the failure by providing a fallback value,
* and resolving the error type [String] to [Nothing]. Meaning we can track that we recovered from the error in the type.
*
* Since we defined programs in terms of [Raise] they _seamlessly work with any of the builders_ available in Arrow,
* or any you might build for your custom types.
*
* ```kotlin
* fun main() {
* val either: Either<String, Int> =
* either { failure() } // returns Left("failed")
*
* val effect: Effect<String, Int> =
* effect { failure() }
*
* val ior: Ior<String, Int> =
* ior { failure() }
*
* println(either)
* }
* ```
*
* ```text
* Either.Right(Recovered from failed)
* ```
*/
public interface Raise<in R> {
/** Raise a _logical failure_ of type [R] */
public fun raise(r: R): Nothing
/**
* Accumulate the errors from running both [action1] and [action2]
* using the given [semigroup].
*/
public fun <A, B, C> zipOrAccumulate(
semigroup: Semigroup<@UnsafeVariance R>,
action1: Raise<R>.() -> A,
action2: Raise<R>.() -> B,
block: Raise<R>.(A, B) -> C
): C {
val result1 = recover(action1) { e1 ->
// try to execute the second
recover(action2) { e2 -> raise(semigroup.append(e1, e2)) }
// if the second succeeds, just raise the first one
raise(e1)
}
return block(result1, action2())
}
/**
* Accumulate the errors from running [action1], [action2], and [action3]
* using the given [semigroup].
*/
public fun <A, B, C, D> zipOrAccumulate(
semigroup: Semigroup<@UnsafeVariance R>,
action1: Raise<R>.() -> A,
action2: Raise<R>.() -> B,
action3: Raise<R>.() -> C,
block: Raise<R>.(A, B, C) -> D
): D = zipOrAccumulate(
semigroup,
{ zipOrAccumulate(semigroup, action1, action2) { x, y -> x to y } },
action3
) { xy, z -> block(xy.first, xy.second, z) }
/**
* Accumulate the errors from running [action1], [action2], [action3], and [action4]
* using the given [semigroup].
*/
public fun <A, B, C, D, E> zipOrAccumulate(
semigroup: Semigroup<@UnsafeVariance R>,
action1: Raise<R>.() -> A,
action2: Raise<R>.() -> B,
action3: Raise<R>.() -> C,
action4: Raise<R>.() -> D,
block: Raise<R>.(A, B, C, D) -> E
): E = zipOrAccumulate(
semigroup,
{ zipOrAccumulate(semigroup, action1, action2, action3) { x, y, z -> Triple(x, y, z) } },
action4
) { xyz, z -> block(xyz.first, xyz.second, xyz.third, z) }
/**
* Accumulate the errors obtained by executing the [block]
* over every element of [this] using the given [semigroup].
*/
public fun <A, B> Iterable<A>.mapOrAccumulate(
semigroup: Semigroup<@UnsafeVariance R>,
block: Raise<R>.(A) -> B
): List<B> {
// this could be implemented using [zipOrAccumulate],
// but we can have a faster implementation using [MutableList]
var error: Any? = EmptyValue
val results = mutableListOf<B>()
forEach {
fold<R, B, Unit>({
block(it)
}, { newError ->
error = semigroup.emptyCombine(error, newError)
}, {
results.add(it)
})
}
when (val e = error) {
is EmptyValue -> return results
else -> raise(EmptyValue.unbox(e))
}
}
/**
* Invoke an [EagerEffect] inside `this` [Raise] context.
* Any _logical failure_ raised are raised in `this` [Raise] context,
* and thus short-circuits the computation.
*
* @see [recover] if you want to attempt to recover from any _logical failure_.
*/
public operator fun <A> EagerEffect<R, A>.invoke(): A = invoke(this@Raise)
public fun <A> EagerEffect<R, A>.bind(): A = invoke(this@Raise)
/**
* Invoke an [Effect] inside `this` [Raise] context.
* Any _logical failure_ raised are raised in `this` [Raise] context,
* and thus short-circuits the computation.
*
* @see [recover] if you want to attempt to recover from any _logical failure_.
*/
public suspend operator fun <A> Effect<R, A>.invoke(): A = invoke(this@Raise)
public suspend fun <A> Effect<R, A>.bind(): A = invoke(this@Raise)
/**
* Extract the [Either.Right] value of an [Either].
* Any encountered [Either.Left] will be raised as a _logical failure_ in `this` [Raise] context.
* You can wrap the [bind] call in [recover] if you want to attempt to recover from any _logical failure_.
*
* ```kotlin
* fun main() {
* val left: Either<String, Int> = Either.Left("failed")
* either {
* recover({ left.bind() }) { failure : String ->
* "Recovered from $failure"
* }
* }.also(::println)
* ```
* ```text
* Either.Right(Recovered from failed)
* ```
*/
public fun <A> Either<R, A>.bind(): A = when (this) {
is Either.Left -> raise(value)
is Either.Right -> value
}
/**
* Extract the [Result.success] value out of [Result],
* because [Result] works with [Throwable] as its error type you need to [transform] [Throwable] to [R].
*
* Note that this functions can currently not be _inline_ without Context Receivers,
* but you can rely on [recover] if you want to run any suspend code in your error handler.
*
* ```kotlin
* fun main() {
* val failure: Result<Int> = Result.failure(RuntimeException("Boom!"))
* either {
* recover({ failure.bind() }) { failure: Throwable ->
* delay(10)
* raise("Something bad happened: ${failure.message}")
* }
* }.also(::println)
* ```
* ```text
* Either.Left(Something bad happened: Boom!)
* ```
*/
public fun <A> Result<A>.bind(transform: (Throwable) -> R): A =
fold(::identity) { throwable -> raise(transform(throwable)) }
/**
* Extract the [Some] value out of [Option],
* because [Option] works with [None] as its error type you need to [transform] [None] to [R].
*
* Note that this functions can currently not be _inline_ without Context Receivers,
* but you can rely on [recover] if you want to run any suspend code in your error handler.
*
* ```kotlin
* fun main() {
* val empty: Option<Int> = None
* either {
* recover({ empty.bind() }) { failure: None ->
* delay(10)
* raise("Something bad happened: ${failure.message}")
* }
* }.also(::println)
* ```
* ```text
* Either.Left(Something bad happened: Boom!)
* ```
*/
public fun <A> Option<A>.bind(transform: Raise<R>.(None) -> A): A =
when (this) {
None -> transform(None)
is Some -> value
}
/**
* Execute the [Effect] resulting in [A],
* and recover from any _logical error_ of type [E] by providing a fallback value of type [A],
* or raising a new error of type [R].
*
* ```kotlin
* suspend fun main() {
* either<Nothing, Int> {
* effect { raise("failed") }.recover { str -> str.length }
* }.also(::println)
*
* either<Int, Nothing> {
* effect { raise("failed") }.recover { str -> raise(-1) }
* }.also(::println)
* }
* ```
* ```text
* Either.Right(6)
* Either.Left(-1)
* ```
*/
@EffectDSL
public suspend infix fun <E, A> Effect<E, A>.recover(@BuilderInference resolve: suspend Raise<R>.(E) -> A): A =
recover({ invoke() }) { resolve(it) }
/** @see [recover] */
@EffectDSL
public infix fun <E, A> EagerEffect<E, A>.recover(@BuilderInference resolve: Raise<R>.(E) -> A): A =
recover({ invoke() }, resolve)
/**
* Execute the [Effect] resulting in [A],
* and recover from any _logical error_ of type [E], and [Throwable], by providing a fallback value of type [A],
* or raising a new error of type [R].
*
* @see [catch] if you don't need to recover from [Throwable].
*/
@EffectDSL
public suspend fun <E, A> Effect<E, A>.recover(
@BuilderInference action: suspend Raise<E>.() -> A,
@BuilderInference recover: suspend Raise<R>.(E) -> A,
@BuilderInference catch: suspend Raise<R>.(Throwable) -> A,
): A = fold({ action(this) }, { catch(it) }, { recover(it) }, { it })
@EffectDSL
public suspend fun <A> Effect<R, A>.catch(
@BuilderInference catch: suspend Raise<R>.(Throwable) -> A,
): A = fold({ catch(it) }, { raise(it) }, { it })
@EffectDSL
public fun <A> EagerEffect<R, A>.catch(
@BuilderInference catch: Raise<R>.(Throwable) -> A,
): A = fold({ catch(it) }, { raise(it) }, { it })
}
@EffectDSL
public inline fun <R, E, A> Raise<R>.recover(
@BuilderInference action: Raise<E>.() -> A,
@BuilderInference recover: Raise<R>.(E) -> A,
): A = fold<E, A, A>({ action(this) }, { throw it }, { recover(it) }, { it })
@EffectDSL
public inline fun <R, E, A> Raise<R>.recover(
@BuilderInference action: Raise<E>.() -> A,
@BuilderInference recover: Raise<R>.(E) -> A,
@BuilderInference catch: Raise<R>.(Throwable) -> A,
): A = fold({ action(this) }, { catch(it) }, { recover(it) }, { it })
@EffectDSL
public inline fun <R, A> Raise<R>.catch(
@BuilderInference action: Raise<R>.() -> A,
@BuilderInference catch: Raise<R>.(Throwable) -> A,
): A = fold({ action(this) }, { catch(it) }, { raise(it) }, { it })
@EffectDSL
@JvmName("catchReified")
public inline fun <reified T : Throwable, R, A> Raise<R>.catch(
@BuilderInference action: Raise<R>.() -> A,
@BuilderInference catch: Raise<R>.(T) -> A,
): A = catch(action) { t: Throwable -> if (t is T) catch(t) else throw t }
@EffectDSL
public inline fun <R> Raise<R>.ensure(condition: Boolean, raise: () -> R): Unit =
if (condition) Unit else raise(raise())
@OptIn(ExperimentalContracts::class)
@EffectDSL
public inline fun <R, B : Any> Raise<R>.ensureNotNull(value: B?, raise: () -> R): B {
contract { returns() implies (value != null) }
return value ?: raise(raise())
}
@EffectDSL
public inline fun <R, A> Raise<NonEmptyList<R>>.mapErrorNel(
crossinline block: Raise<R>.() -> A
): A = recover(block) { raise(it.nel()) }
/**
* Accumulate the errors obtained by executing the [block]
* over every element of [list].
*/
@EffectDSL
public inline fun <R, A, B> Raise<NonEmptyList<R>>.mapOrAccumulate(
list: Iterable<A>,
crossinline block: Raise<R>.(A) -> B
): List<B> =
list.mapOrAccumulate(Semigroup.nonEmptyList()) { elt -> mapErrorNel { block(elt) } }
/**
* Accumulate the errors from running both [action1] and [action2].
*/
@EffectDSL
public inline fun <R, A, B, C> Raise<NonEmptyList<R>>.zipOrAccumulate(
crossinline action1: Raise<R>.() -> A,
crossinline action2: Raise<R>.() -> B,
crossinline block: Raise<R>.(A, B) -> C
): C = zipOrAccumulate(
Semigroup.nonEmptyList(),
{ mapErrorNel(action1) },
{ mapErrorNel(action2) },
{ x, y -> mapErrorNel { block(x, y) } }
)
/**
* Accumulate the errors from running [action1], [action2], and [action3].
*/
@EffectDSL
public inline fun <R, A, B, C, D> Raise<NonEmptyList<R>>.zipOrAccumulate(
crossinline action1: Raise<R>.() -> A,
crossinline action2: Raise<R>.() -> B,
crossinline action3: Raise<R>.() -> C,
crossinline block: Raise<R>.(A, B, C) -> D
): D = zipOrAccumulate(
Semigroup.nonEmptyList(),
{ mapErrorNel(action1) },
{ mapErrorNel(action2) },
{ mapErrorNel(action3) },
{ x, y, z -> mapErrorNel { block(x, y, z) } }
)
/**
* Accumulate the errors from running [action1], [action2], [action3], and [action4].
*/
@EffectDSL
public inline fun <R, A, B, C, D, E> Raise<NonEmptyList<R>>.zipOrAccumulate(
crossinline action1: Raise<R>.() -> A,
crossinline action2: Raise<R>.() -> B,
crossinline action3: Raise<R>.() -> C,
crossinline action4: Raise<R>.() -> D,
crossinline block: Raise<R>.(A, B, C, D) -> E
): E = zipOrAccumulate(
Semigroup.nonEmptyList(),
{ mapErrorNel(action1) },
{ mapErrorNel(action2) },
{ mapErrorNel(action3) },
{ mapErrorNel(action4) },
{ x, y, z, u -> mapErrorNel { block(x, y, z, u) } }
)