Skip to content

Commit

Permalink
Implement Suspend Dsl for Future, Function1, and TailRec
Browse files Browse the repository at this point in the history
  • Loading branch information
Atry committed Dec 24, 2021
1 parent a9a62fb commit fa067f3
Showing 1 changed file with 40 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,49 @@ package com.thoughtworks.dsl
package keywords
import Dsl.IsKeyword
import Dsl.cpsApply
import scala.concurrent.Future
import scala.concurrent.ExecutionContext
import scala.util.control.TailCalls.TailRec
import scala.util.control.TailCalls

opaque type Suspend[+Keyword] <: Dsl.Keyword.Opaque = Dsl.Keyword.Opaque.Of[() => Keyword]
object Suspend {
@inline def apply[Keyword]: (() => Keyword) =:= Suspend[Keyword] = Dsl.Keyword.Opaque.Of.apply
opaque type Suspend[+Keyword] <: Dsl.Keyword.Opaque =
Dsl.Keyword.Opaque.Of[() => Keyword]
object Suspend extends Suspend.LowPriority0 {
@inline def apply[Keyword]: (() => Keyword) =:= Suspend[Keyword] =
Dsl.Keyword.Opaque.Of.apply

given[Upstream, UpstreamValue](using upstreamIsKeyword: => IsKeyword[Upstream, UpstreamValue]): IsKeyword[Suspend[Upstream], UpstreamValue] with {}
given [Upstream, UpstreamValue](using
upstreamIsKeyword: => IsKeyword[Upstream, UpstreamValue]
): IsKeyword[Suspend[Upstream], UpstreamValue] with {}

given [Keyword, Domain, Value](using
Dsl.Searching[Keyword, Domain, Value]
): Dsl.Composed[Suspend[Keyword], Domain, Value] = Dsl.Composed {
(keyword: Suspend[Keyword], handler: Value => Domain) =>
keyword().cpsApply(handler)
private[Suspend] trait LowPriority0:
given [Keyword, Domain, Value](using
Dsl.Searching[Keyword, Domain, Value]
): Dsl.Composed[Suspend[Keyword], Domain, Value] = Dsl.Composed {
(keyword: Suspend[Keyword], handler: Value => Domain) =>
keyword().cpsApply(handler)
}

given [Keyword, State, Domain, Value](using
Dsl.Searching[Keyword, State => Domain, Value]
): Dsl.Composed[Suspend[Keyword], State => Domain, Value] = Dsl.Composed {
(keyword: Suspend[Keyword], handler: Value => State => Domain) => value =>
keyword().cpsApply(handler)(value)
}

given [Keyword, Result, Value](using
Dsl.Searching[Keyword, Future[Result], Value],
ExecutionContext
): Dsl.Composed[Suspend[Keyword], Future[Result], Value] = Dsl.Composed {
(keyword: Suspend[Keyword], handler: Value => Future[Result]) =>
Future.delegate(keyword().cpsApply(handler))
}

given [Keyword, Result, Value](using
Dsl.Searching[Keyword, TailRec[Result], Value]
): Dsl.Composed[Suspend[Keyword], TailRec[Result], Value] = Dsl.Composed {
(keyword: Suspend[Keyword], handler: Value => TailRec[Result]) =>
TailCalls.tailcall { keyword().cpsApply(handler) }
}

}

0 comments on commit fa067f3

Please sign in to comment.