Ensure that optional binding works with closures
This commit is contained in:
parent
54516fd2d1
commit
93f5c919fb
|
@ -6,7 +6,8 @@ proc option[T](option: Option[T]): Option[T] =
|
||||||
|
|
||||||
template bindLet(name, expression): bool =
|
template bindLet(name, expression): bool =
|
||||||
let option = expression.option
|
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
|
option.isSome
|
||||||
|
|
||||||
template bindVar(name, expression): bool =
|
template bindVar(name, expression): bool =
|
||||||
|
|
|
@ -80,7 +80,10 @@ template `|?`*[T,E](value: Result[T,E], fallback: T): T =
|
||||||
|
|
||||||
proc option*[T,E](value: Result[T,E]): ?T =
|
proc option*[T,E](value: Result[T,E]): ?T =
|
||||||
if value.isOk:
|
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:
|
else:
|
||||||
T.none
|
T.none
|
||||||
|
|
||||||
|
|
|
@ -148,6 +148,20 @@ suite "optionals":
|
||||||
check 42.some.toString == "42"
|
check 42.some.toString == "42"
|
||||||
check int.none.toString == "none"
|
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":
|
test "without statement can be used for early returns":
|
||||||
proc test1 =
|
proc test1 =
|
||||||
without a =? 42.some:
|
without a =? 42.some:
|
||||||
|
|
|
@ -151,6 +151,20 @@ suite "result":
|
||||||
check 42.success.toString == "42"
|
check 42.success.toString == "42"
|
||||||
check int.failure(error).toString == "error"
|
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":
|
test "without statement works for results":
|
||||||
proc test1 =
|
proc test1 =
|
||||||
without a =? 42.success:
|
without a =? 42.success:
|
||||||
|
|
Loading…
Reference in New Issue