From 8dd1c6a802b8c0c01fa8a3ec0eee66442fde5115 Mon Sep 17 00:00:00 2001 From: Raphael Jolly Date: Tue, 23 Mar 2021 21:30:19 +0100 Subject: [PATCH] Add try method in safe throws strawman --- tests/run/safeThrowsStrawman2.check | 3 ++ tests/run/safeThrowsStrawman2.scala | 47 +++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 tests/run/safeThrowsStrawman2.check create mode 100644 tests/run/safeThrowsStrawman2.scala diff --git a/tests/run/safeThrowsStrawman2.check b/tests/run/safeThrowsStrawman2.check new file mode 100644 index 000000000000..3b8b7ee861f0 --- /dev/null +++ b/tests/run/safeThrowsStrawman2.check @@ -0,0 +1,3 @@ +1 +failed +failed diff --git a/tests/run/safeThrowsStrawman2.scala b/tests/run/safeThrowsStrawman2.scala new file mode 100644 index 000000000000..490f9c6dbe99 --- /dev/null +++ b/tests/run/safeThrowsStrawman2.scala @@ -0,0 +1,47 @@ +import language.experimental.erasedDefinitions + +object scalax: + erased class CanThrow[-E <: Exception] + + infix type throws[R, +E <: Exception] = CanThrow[E] ?=> R + + class Fail extends Exception + + def raise[E <: Exception](e: E): Nothing throws E = throw e + + private class Result[T]: + var value: T = scala.compiletime.uninitialized + + def try1[R, E <: Exception](body: => R throws E): (E => Unit) => R = { c => + val res = new Result[R] + try + given CanThrow[E] = ??? + res.value = body + catch c.asInstanceOf[Throwable => Unit] + res.value + } + + extension [R, E <: Exception](t: (E => Unit) => R) def catch1(c: E => Unit) = t(c) + +import scalax._ + +def foo(x: Boolean): Int throws Fail = + if x then 1 else raise(Fail()) + +def bar(x: Boolean)(using CanThrow[Fail]): Int = foo(x) +def baz: Int throws Exception = foo(false) + +@main def Test = + try1 { + println(foo(true)) + println(foo(false)) + } catch1 { + case ex: Fail => + println("failed") + } + try1 { + println(baz) + } catch1 { + case ex: Fail => + println("failed") + }