-
Notifications
You must be signed in to change notification settings - Fork 29
/
TryFinally.scala
55 lines (51 loc) · 1.48 KB
/
TryFinally.scala
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
package com.thoughtworks.dsl
package keywords
import Dsl.IsKeyword
import scala.util.control.Exception.Catcher
import scala.concurrent._
import scala.util.control.NonFatal
import scala.util.Success
import scala.util.Failure
import scala.util.Try
case class TryFinally[+TryKeyword, +FinalizerKeyword](
block: () => TryKeyword,
finalizer: () => FinalizerKeyword
) extends Dsl.Keyword.Trait
object TryFinally {
type DslComposer[OuterDomain, Value, BlockDomain] =
TryCatch.DslComposer[OuterDomain, Try[Value], BlockDomain]
given [
Value,
OuterDomain,
BlockKeyword,
BlockDomain,
FinalizerKeyword
](using
DslComposer[OuterDomain, Value, BlockDomain],
Dsl.Searching[BlockKeyword, BlockDomain, Value],
Dsl.Searching[FinalizerKeyword, OuterDomain, Unit]
): Dsl.Composed[TryFinally[
BlockKeyword,
FinalizerKeyword
], OuterDomain, Value] = Dsl.Composed {
case (TryFinally(blockKeyword, finalizerKeyword), handler) =>
val transformedAst = FlatMap(
TryCatch(
() =>
FlatMap(
blockKeyword(),
(successValue: Value) => Pure(Success(successValue))
),
{ case NonFatal(e) =>
Pure(Failure[Value](e))
}
),
(result: Try[Value]) =>
FlatMap(finalizerKeyword(), (_: Unit) => Pure(result.get))
)
summon[Dsl.Searching[transformedAst.type, OuterDomain, Value]](
transformedAst,
handler
)
}
}