Ensure that optional binding works with closures

This commit is contained in:
Mark Spanbroek 2021-05-31 16:24:21 +02:00
parent 54516fd2d1
commit 93f5c919fb
4 changed files with 34 additions and 2 deletions

View File

@ -6,7 +6,8 @@ proc option[T](option: Option[T]): Option[T] =
template bindLet(name, expression): bool =
let option = expression.option
template name: auto {.used.} = option.unsafeGet()
const default = typeof(option.unsafeGet()).default
let name = if option.isSome: option.unsafeGet() else: default
option.isSome
template bindVar(name, expression): bool =

View File

@ -80,7 +80,10 @@ template `|?`*[T,E](value: Result[T,E], fallback: T): T =
proc option*[T,E](value: Result[T,E]): ?T =
if value.isOk:
value.unsafeGet.some
try: # workaround for erroneouos exception tracking when T is a closure
value.unsafeGet.some
except Exception as exception:
raise newException(Defect, exception.msg, exception)
else:
T.none

View File

@ -148,6 +148,20 @@ suite "optionals":
check 42.some.toString == "42"
check int.none.toString == "none"
test "=? works with closures":
var called = false
let closure = some(proc () = called = true)
if a =? none(proc ()):
a()
check not called
if a =? closure:
a()
check called
test "without statement can be used for early returns":
proc test1 =
without a =? 42.some:

View File

@ -151,6 +151,20 @@ suite "result":
check 42.success.toString == "42"
check int.failure(error).toString == "error"
test "=? works with closures":
var called = false
let closure = success(proc () = called = true)
if a =? failure(proc (), error):
a()
check not called
if a =? closure:
a()
check called
test "without statement works for results":
proc test1 =
without a =? 42.success: