-
Notifications
You must be signed in to change notification settings - Fork 451
/
Raise.kt
438 lines (414 loc) · 13.9 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
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
@file:OptIn(ExperimentalTypeInference::class, ExperimentalContracts::class)
@file:Suppress("DEPRECATION")
@file:JvmMultifileClass
@file:JvmName("RaiseKt")
package arrow.core.raise
import arrow.core.Either
import arrow.core.Validated
import arrow.core.continuations.EffectScope
import arrow.core.getOrElse
import arrow.core.identity
import arrow.core.nonFatalOrThrow
import arrow.core.recover
import kotlin.coroutines.cancellation.CancellationException
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind.AT_MOST_ONCE
import kotlin.contracts.contract
import kotlin.experimental.ExperimentalTypeInference
import kotlin.jvm.JvmMultifileClass
import kotlin.jvm.JvmName
@DslMarker
public annotation class RaiseDSL
/**
* <!--- TEST_NAME RaiseKnitTest -->
*
* The [Raise] DSL allows you to work with _logical failures_ of type [Error].
* 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 [Error], and you can [recover] from them.
*
* <!--- INCLUDE
* import arrow.core.raise.Raise
* import arrow.core.raise.recover
* -->
* ```kotlin
* fun Raise<String>.failure(): Int = raise("failed")
*
* fun recovered(): Int =
* recover({ failure() }) { _: String -> 1 }
* ```
* <!--- KNIT example-raise-dsl-01.kt -->
*
* 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].
*
* You can also use the [recover] function inside the [Raise] DSL to transform the error type to a different type such as `List<Char>`.
* And you can do the same for other data types such as `Effect`, `Either`, etc. using [getOrElse] as an alternative to [recover].
*
* <!--- INCLUDE
* import arrow.core.getOrElse
* import arrow.core.left
* import arrow.core.raise.Raise
* import arrow.core.raise.effect
* import arrow.core.raise.recover
* import arrow.core.raise.getOrElse
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun Raise<String>.failure(): Int = raise("failed")
*
* fun Raise<List<Char>>.recovered(): Int =
* recover({ failure() }) { msg: String -> raise(msg.toList()) }
*
* suspend fun Raise<List<Char>>.recovered2(): Int =
* effect { failure() } getOrElse { msg: String -> raise(msg.toList()) }
*
* fun Raise<List<Char>>.recovered3(): Int =
* "failed".left() getOrElse { msg: String -> raise(msg.toList()) }
*
* fun test(): Unit {
* recover({ "failed".left().bind() }) { 1 } shouldBe "failed".left().getOrElse { 1 }
* }
* ```
* <!--- KNIT example-raise-dsl-02.kt -->
* <!--- TEST lines.isEmpty() -->
*
* 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.
*
* <!--- INCLUDE
* import arrow.core.Either
* import arrow.core.Ior
* import arrow.core.raise.Effect
* import arrow.core.raise.Raise
* import arrow.core.raise.either
* import arrow.core.raise.effect
* import arrow.core.raise.ior
* import arrow.core.raise.toEither
* import arrow.typeclasses.Semigroup
* import io.kotest.matchers.shouldBe
*
* fun Raise<String>.failure(): Int = raise("failed")
* -->
* ```kotlin
* suspend fun test() {
* val either: Either<String, Int> =
* either { failure() }
*
* val effect: Effect<String, Int> =
* effect { failure() }
*
* val ior: Ior<String, Int> =
* ior(String::plus) { failure() }
*
* either shouldBe Either.Left("failed")
* effect.toEither() shouldBe Either.Left("failed")
* ior shouldBe Ior.Left("failed")
* }
* ```
* <!--- KNIT example-raise-dsl-03.kt -->
* <!--- TEST lines.isEmpty() -->
*
* Arrow also exposes [Raise] based error handlers for the most common data types,
* which allows to recover from _logical failures_ whilst transforming the error type.
*
* <!--- INCLUDE
* import arrow.core.Either
* import arrow.core.getOrElse
* import arrow.core.raise.Raise
* import arrow.core.raise.either
* import arrow.core.raise.recover
* import arrow.core.recover
* import arrow.core.right
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun Raise<String>.failure(): Int = raise("failed")
*
* fun test() {
* val failure: Either<String, Int> = either { failure() }
*
* failure.recover { _: String -> 1.right().bind() } shouldBe Either.Right(1)
*
* failure.recover { msg: String -> raise(msg.toList()) } shouldBe Either.Left(listOf('f', 'a', 'i', 'l', 'e', 'd'))
*
* recover({ failure.bind() }) { 1 } shouldBe failure.getOrElse { 1 }
* }
* ```
* <!--- KNIT example-raise-dsl-04.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public interface Raise<in Error> {
/** Raise a _logical failure_ of type [Error] */
@RaiseDSL
public fun raise(r: Error): Nothing
@Deprecated("Use raise instead", ReplaceWith("raise(r)"))
public fun <A> shift(r: Error): A = raise(r)
@RaiseDSL
public suspend fun <A> arrow.core.continuations.Effect<Error, A>.bind(): A =
fold({ raise(it) }, ::identity)
// Added for source compatibility with EffectScope / EagerScope
@RaiseDSL
public suspend fun <A> arrow.core.continuations.EagerEffect<Error, A>.bind(): A =
fold({ raise(it) }, ::identity)
@Deprecated(
"Use getOrElse on Raise, Effect or EagerEffect instead.",
ReplaceWith("effect { f() }")
)
public suspend fun <OtherError, A> attempt(
@BuilderInference
f: suspend EffectScope<OtherError>.() -> A,
): arrow.core.continuations.Effect<OtherError, A> = arrow.core.continuations.effect(f)
@Deprecated(
"Use getOrElse on Raise, Effect or EagerEffect instead.",
ReplaceWith("fold({ recover(it) }, ::identity)")
)
public suspend infix fun <OtherError, A> arrow.core.continuations.Effect<OtherError, A>.catch(
recover: suspend Raise<Error>.(otherError: OtherError) -> A,
): A = fold({ recover(it) }, ::identity)
/**
* Invoke an [EagerEffect] inside `this` [Raise] context.
* Any _logical failure_ is 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<Error, A>.invoke(): A = invoke(this@Raise)
@RaiseDSL
public fun <A> EagerEffect<Error, 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<Error, A>.invoke(): A = invoke(this@Raise)
@RaiseDSL
public suspend fun <A> Effect<Error, 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_.
*
* <!--- INCLUDE
* import arrow.core.Either
* import arrow.core.right
* import arrow.core.raise.either
* import arrow.core.raise.recover
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun test() {
* val one: Either<Nothing, Int> = 1.right()
* val left: Either<String, Int> = Either.Left("failed")
*
* either {
* val x = one.bind()
* val y = recover({ left.bind() }) { failure : String -> 1 }
* x + y
* } shouldBe Either.Right(2)
* }
* ```
* <!--- KNIT example-raise-dsl-05.kt -->
* <!--- TEST lines.isEmpty() -->
*/
@RaiseDSL
public fun <A> Either<Error, A>.bind(): A = when (this) {
is Either.Left -> raise(value)
is Either.Right -> value
}
@Deprecated("Validated is deprecated in favor of Either.", ReplaceWith("toEither().bind()"))
@RaiseDSL
public fun <A> Validated<Error, A>.bind(): A = when (this) {
is Validated.Invalid -> raise(value)
is Validated.Valid -> value
}
}
/**
* Execute the [Raise] context function resulting in [A] or any _logical error_ of type [Error],
* and recover by providing a transform [Error] into a fallback value of type [A].
* Base implementation of `effect { f() } getOrElse { fallback() }`.
*
* <!--- INCLUDE
* import arrow.core.Either
* import arrow.core.raise.either
* import arrow.core.raise.recover
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun test() {
* recover({ raise("failed") }) { str -> str.length } shouldBe 6
*
* either<Int, String> {
* recover({ raise("failed") }) { str -> raise(-1) }
* } shouldBe Either.Left(-1)
* }
* ```
* <!--- KNIT example-raise-dsl-06.kt -->
* <!--- TEST lines.isEmpty() -->
*/
@RaiseDSL
public inline fun <Error, A> recover(
@BuilderInference block: Raise<Error>.() -> A,
@BuilderInference recover: (error: Error) -> A,
): A = fold(block, { throw it }, recover, ::identity)
/**
* Execute the [Raise] context function resulting in [A] or any _logical error_ of type [Error],
* and [recover] by providing a transform [Error] into a fallback value of type [A],
* or [catch] any unexpected exceptions by providing a transform [Throwable] into a fallback value of type [A],
*
* <!--- INCLUDE
* import arrow.core.raise.recover
* import arrow.core.raise.Raise
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun test() {
* recover(
* { raise("failed") },
* { str -> str.length }
* ) { t -> t.message ?: -1 } shouldBe 6
*
* fun Raise<String>.boom(): Int = throw RuntimeException("BOOM")
*
* recover(
* { boom() },
* { str -> str.length }
* ) { t -> t.message?.length ?: -1 } shouldBe 4
* }
* ```
* <!--- KNIT example-raise-dsl-07.kt -->
* <!--- TEST lines.isEmpty() -->
*/
@RaiseDSL
public inline fun <Error, A> recover(
@BuilderInference block: Raise<Error>.() -> A,
@BuilderInference recover: (error: Error) -> A,
@BuilderInference catch: (throwable: Throwable) -> A,
): A = fold(block, catch, recover, ::identity)
/**
* Execute the [Raise] context function resulting in [A] or any _logical error_ of type [Error],
* and [recover] by providing a transform [Error] into a fallback value of type [A],
* or [catch] any unexpected exceptions by providing a transform [Throwable] into a fallback value of type [A],
*
* <!--- INCLUDE
* import arrow.core.raise.recover
* import arrow.core.raise.Raise
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun test() {
* recover(
* { raise("failed") },
* { str -> str.length }
* ) { t -> t.message ?: -1 } shouldBe 6
*
* fun Raise<String>.boom(): Int = throw RuntimeException("BOOM")
*
* recover(
* { boom() },
* { str -> str.length }
* ) { t: RuntimeException -> t.message?.length ?: -1 } shouldBe 4
* }
* ```
* <!--- KNIT example-raise-dsl-08.kt -->
* <!--- TEST lines.isEmpty() -->
*/
@RaiseDSL
@JvmName("recoverReified")
public inline fun <reified T : Throwable, Error, A> recover(
@BuilderInference block: Raise<Error>.() -> A,
@BuilderInference recover: (error: Error) -> A,
@BuilderInference catch: (t: T) -> A,
): A = fold(block, { t -> if (t is T) catch(t) else throw t }, recover, ::identity)
/**
* Allows safely catching exceptions without capturing [CancellationException],
* or fatal exceptions like `OutOfMemoryError` or `VirtualMachineError` on the JVM.
*
* <!--- INCLUDE
* import arrow.core.Either
* import arrow.core.raise.either
* import arrow.core.raise.catch
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun test() {
* catch({ throw RuntimeException("BOOM") }) { t ->
* "fallback"
* } shouldBe "fallback"
*
* fun fetchId(): Int = throw RuntimeException("BOOM")
*
* either {
* catch({ fetchId() }) { t ->
* raise("something went wrong: ${t.message}")
* }
* } shouldBe Either.Left("something went wrong: BOOM")
* }
* ```
* <!--- KNIT example-raise-dsl-09.kt -->
* <!--- TEST lines.isEmpty() -->
*
* Alternatively, you can use `try { } catch { }` blocks with [nonFatalOrThrow].
* This API offers a similar syntax as the top-level [catch] functions like [Either.catch].
*/
@RaiseDSL
public inline fun <A> catch(block: () -> A, catch: (throwable: Throwable) -> A): A =
try {
block()
} catch (t: Throwable) {
catch(t.nonFatalOrThrow())
}
/**
* Allows safely catching exceptions of type `T` without capturing [CancellationException],
* or fatal exceptions like `OutOfMemoryError` or `VirtualMachineError` on the JVM.
*
* <!--- INCLUDE
* import arrow.core.Either
* import arrow.core.raise.either
* import arrow.core.raise.catch
* import io.kotest.matchers.shouldBe
* -->
* ```kotlin
* fun test() {
* catch({ throw RuntimeException("BOOM") }) { t ->
* "fallback"
* } shouldBe "fallback"
*
* fun fetchId(): Int = throw RuntimeException("BOOM")
*
* either {
* catch({ fetchId() }) { t: RuntimeException ->
* raise("something went wrong: ${t.message}")
* }
* } shouldBe Either.Left("something went wrong: BOOM")
* }
* ```
* <!--- KNIT example-raise-dsl-10.kt -->
* <!--- TEST lines.isEmpty() -->
*
* Alternatively, you can use `try { } catch(e: T) { }` blocks.
* This API offers a similar syntax as the top-level [catch] functions like [Either.catch].
*/
@RaiseDSL
@JvmName("catchReified")
public inline fun <reified T : Throwable, A> catch(block: () -> A, catch: (t: T) -> A): A =
catch(block) { t: Throwable -> if (t is T) catch(t) else throw t }
@RaiseDSL
public inline fun <Error> Raise<Error>.ensure(condition: Boolean, raise: () -> Error) {
contract {
callsInPlace(raise, AT_MOST_ONCE)
returns() implies condition
}
return if (condition) Unit else raise(raise())
}
@RaiseDSL
public inline fun <Error, B : Any> Raise<Error>.ensureNotNull(value: B?, raise: () -> Error): B {
contract {
callsInPlace(raise, AT_MOST_ONCE)
returns() implies (value != null)
}
return value ?: raise(raise())
}