Skip to content

Implemented submarine error propagation for Handle #619

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
5ddf622
Implemented submarine error propagation for `Handle`
djspiewak Apr 30, 2023
5d3c47e
Added headers
djspiewak Apr 30, 2023
4936fef
Collapsed `Handle` tests and fixed Scala 3 issues
djspiewak Apr 30, 2023
c62bcdb
Swapped `ensure` for `allow`
djspiewak Jan 3, 2025
bc17ca3
Swapped `recover` for `rescue`
djspiewak Jan 3, 2025
b273d1f
Happy now?
djspiewak Mar 3, 2025
b7861fb
Add extra typing for raise to fix the nested tests
lenguyenthanh Mar 6, 2025
b255b4c
Update scalafmt runner dialect for scala 3 code
lenguyenthanh Mar 6, 2025
25d703c
Fix scala 2.12 compilation
lenguyenthanh Mar 6, 2025
4f19410
Use using instead of implicit for scala 3
lenguyenthanh Mar 6, 2025
cb545b9
Remove duplicated files
lenguyenthanh Mar 7, 2025
0b20cfc
Use AnyVal to avoid allocations
lenguyenthanh Mar 7, 2025
74dda73
Use HandleCrossCompat to follow code convention
lenguyenthanh Mar 7, 2025
85e418b
Add inline for AdhocSyntaxWired.apply
lenguyenthanh Mar 8, 2025
d1167df
Use FunSuite instead of BaseSuite
lenguyenthanh Mar 8, 2025
a70b9f4
Use dummy Byte instead of Unit to avoid warning
lenguyenthanh Mar 9, 2025
4c26d00
Use method call with implicit to avoid one extra allocation
lenguyenthanh Mar 10, 2025
e9c0d37
Extract InnerHandler out of rescue
lenguyenthanh Mar 12, 2025
d1382bd
Inlining inner function
lenguyenthanh Jul 23, 2025
3f7973f
minor stylistic update
lenguyenthanh Jul 23, 2025
5de654a
Inline arguments of inner
lenguyenthanh Jul 23, 2025
fb9f86f
union tests for scala 3
lenguyenthanh Aug 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,9 @@ rewriteTokens {
"→": "->"
"←": "<-"
}

fileOverride {
"glob:**/scala-3/cats/mtl/**" {
runner.dialect = scala3
}
}
20 changes: 20 additions & 0 deletions core/src/main/scala-2/cats/mtl/HandleCrossCompat.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright 2021 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats
package mtl

private[mtl] trait HandleCrossCompat
46 changes: 46 additions & 0 deletions core/src/main/scala-3/cats/mtl/HandleCrossCompat.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2021 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats
package mtl

private[mtl] trait HandleCrossCompat { this: Handle.type =>
import Handle.Submarine

inline def allow[E]: AdHocSyntaxWired[E] =
new AdHocSyntaxWired[E]()

private[mtl] final class AdHocSyntaxWired[E]:
inline def apply[F[_], A](inline body: Handle[F, E] ?=> F[A]): InnerWired[F, E, A] =
new InnerWired(body)

private[mtl] final class InnerWired[F[_], E, A](body: Handle[F, E] ?=> F[A]):
def rescue(h: E => F[A]): ApplicativeThrow[F] ?=> F[A] =
val Marker = new AnyRef

def inner[B](fb: F[B])(f: E => F[B]): F[B] =
ApplicativeThrow[F].handleErrorWith(fb):
case Submarine(e, Marker) => f(e.asInstanceOf[E])
case t => ApplicativeThrow[F].raiseError(t)

given Handle[F, E] with
def applicative = Applicative[F]
def raise[E2 <: E, B](e: E2): F[B] =
ApplicativeThrow[F].raiseError(Submarine(e, Marker))
def handleWith[B](fb: F[B])(f: E => F[B]): F[B] = inner(fb)(f)

inner(body)(h)
}
39 changes: 38 additions & 1 deletion core/src/main/scala/cats/mtl/Handle.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package mtl
import cats.data._

import scala.annotation.implicitNotFound
import scala.util.control.NoStackTrace

@implicitNotFound(
"Could not find an implicit instance of Handle[${F}, ${E}]. If you\nhave a good way of handling errors of type ${E} at this location, you may want\nto construct a value of type EitherT for this call-site, rather than ${F}.\nAn example type:\n\n EitherT[${F}, ${E}, *]\n\nThis is analogous to writing try/catch around this call. The EitherT will\n\"catch\" the errors of type ${E}.\n\nIf you do not wish to handle errors of type ${E} at this location, you should\nadd an implicit parameter of this type to your function. For example:\n\n (implicit fhandle: Handle[${F}, ${E}}])\n")
Expand Down Expand Up @@ -217,6 +218,42 @@ private[mtl] trait HandleInstances extends HandleLowPriorityInstances {
}
}

object Handle extends HandleInstances {
object Handle extends HandleInstances with HandleCrossCompat {

def apply[F[_], E](implicit ev: Handle[F, E]): Handle[F, E] = ev

def allowF[F[_], E]: AdHocSyntaxTired[F, E] =
new AdHocSyntaxTired[F, E](())

@scala.annotation.nowarn("msg=dubious usage of method hashCode with unit value")
private[mtl] final class AdHocSyntaxTired[F[_], E](private val unit: Unit) extends AnyVal {
def apply[A](body: Handle[F, E] => F[A]): Inner[F, E, A] =
new Inner(body)
}

private[mtl] final class Inner[F[_], E, A](private val body: Handle[F, E] => F[A])
extends AnyVal {
def rescue(h: E => F[A])(implicit F: ApplicativeThrow[F]): F[A] = {
val Marker = new AnyRef

def inner[B](fb: F[B])(f: E => F[B]): F[B] =
ApplicativeThrow[F].handleErrorWith(fb) {
case Submarine(e, Marker) => f(e.asInstanceOf[E])
case t => ApplicativeThrow[F].raiseError(t)
}

val fa = body(new Handle[F, E] {
def applicative = Applicative[F]
def raise[E2 <: E, B](e: E2): F[B] =
ApplicativeThrow[F].raiseError(Submarine(e, Marker))
def handleWith[B](fb: F[B])(f: E => F[B]): F[B] = inner(fb)(f)
})

inner(fa)(h)
}
}

private[mtl] final case class Submarine[E](e: E, marker: AnyRef)
extends RuntimeException
with NoStackTrace
}
59 changes: 59 additions & 0 deletions tests/shared/src/test/scala-3/cats/mtl/tests/Handle3Tests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2021 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats
package mtl
package tests

import cats.data.EitherT
import cats.mtl.syntax.all.*
import cats.syntax.all.*
import cats.mtl.Handle.*

class Handle3Tests extends munit.FunSuite:

type F[A] = EitherT[Eval, Throwable, A]

test("submerge custom errors (scala 3)"):
enum Error:
case First, Second, Third

val test =
allow[Error]:
Error.Second.raise[F, String].as("nope")
.rescue:
case Error.First => "0".pure[F]
case Error.Second => "1".pure[F]
case Error.Third => "2".pure[F]

assert.equals(test.value.value.toOption, Some("1"))

test("submerge two independent errors (scala 3)"):
enum Error1:
case First, Second, Third
enum Error2:
case Fourth
val test =
allow[Error1]:
allow[Error2]:
Error1.Third.raise[F, String].as("nope")
.rescue:
case e => e.toString.pure[F]
.rescue:
case Error1.First => "first1".pure[F]
case Error1.Second => "second1".pure[F]
case Error1.Third => "third1".pure[F]
assert.equals(test.value.value.toOption, Some("third1"))
85 changes: 84 additions & 1 deletion tests/shared/src/test/scala/cats/mtl/tests/HandleTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,16 @@ package cats
package mtl
package tests

import cats.data.{Kleisli, WriterT}
import cats.data.{EitherT, Kleisli, WriterT}
import cats.laws.discipline.arbitrary._
import cats.mtl.syntax.all._
import cats.syntax.all._

import org.scalacheck.{Arbitrary, Cogen}, Arbitrary.arbitrary

class HandleTests extends BaseSuite {
type F[A] = EitherT[Eval, Throwable, A]

test("handleForApplicativeError") {
case class Foo[A](bar: A)

Expand All @@ -39,4 +46,80 @@ class HandleTests extends BaseSuite {
Handle[Kleisli[Foo, Unit, *], String]
Handle[WriterT[Foo, String, *], String]
}

test("submerge custom errors") {
sealed trait Error extends Product with Serializable

object Error {
case object First extends Error
case object Second extends Error
case object Third extends Error
}

val test =
Handle.allowF[F, Error](implicit h => Error.Second.raise.as("nope")) rescue {
case Error.First => "0".pure[F]
case Error.Second => "1".pure[F]
case Error.Third => "2".pure[F]
}

assert(test.value.value.toOption == Some("1"))
}

test("submerge two independent errors") {
sealed trait Error1 extends Product with Serializable

object Error1 {
case object First extends Error1
case object Second extends Error1
case object Third extends Error1
}

sealed trait Error2 extends Product with Serializable

val test = Handle.allowF[F, Error1] { implicit h1 =>
Handle.allowF[F, Error2] { implicit h2 =>
val _ =
h2 // it's helpful to test the raise syntax infers even when multiple handles are present
Error1.Third.raise.as("nope")
} rescue { e => e.toString.pure[F] }
} rescue {
case Error1.First => "first1".pure[F]
case Error1.Second => "second1".pure[F]
case Error1.Third => "third1".pure[F]
}

assert(test.value.value.toOption == Some("third1"))
}

{
final case class Error(value: Int)

object Error {
implicit val arbError: Arbitrary[Error] =
Arbitrary(arbitrary[Int].flatMap(Error(_)))

implicit val cogenError: Cogen[Error] =
Cogen((_: Error).value.toLong)

implicit val eqError: Eq[Error] =
Eq.by((_: Error).value)
}

implicit val eqThrowable: Eq[Throwable] =
Eq.fromUniversalEquals[Throwable]

val test = Handle.allowF[F, Error] { implicit h =>
EitherT liftF {
Eval later {
checkAll(
"Handle.allowF[F, Error]",
cats.mtl.laws.discipline.HandleTests[F, Error].handle[Int])
}
}
} rescue { case Error(_) => ().pure[F] }

test.value.value
()
}
}