Fix error when using an existing name as error variable

This commit is contained in:
Mark Spanbroek 2022-08-09 14:22:53 +02:00 committed by markspanbroek
parent 90ea780ba9
commit cfe17ca899
2 changed files with 18 additions and 5 deletions

View File

@ -1,12 +1,16 @@
import std/macros
import ./without
import ./private/binderror
template without*(condition, errorname, body): untyped =
macro without*(condition, errorname, body): untyped =
## Used to place guards that ensure that a Result contains a value.
## Exposes error when Result does not contain a value.
var error: ref CatchableError
let errorIdent = ident $errorname
without captureBindError(error, condition):
template errorname: ref CatchableError = error
body
quote do:
var error: ref CatchableError
without captureBindError(error, `condition`):
template `errorIdent`: ref CatchableError = error
`body`

View File

@ -281,6 +281,15 @@ suite "result":
check e2.msg == "error2"
check e1.msg == "error1"
test "without statement works in generic code using existing error name":
let existingName {.used.} = "some variable"
proc shouldCompile(_: type int): ?!int =
without _ =? int.failure "error", existingName:
return success 42
discard int.shouldCompile()
test "without statements with error work in nested calls":
proc bar(): ?!int =
without _ =? int.failure "error", err: