Fix: disregard early symbol lookup for error variable

This commit is contained in:
Mark Spanbroek 2022-08-10 11:11:45 +02:00 committed by markspanbroek
parent cfe17ca899
commit 9e3a822877
2 changed files with 22 additions and 1 deletions

View File

@ -2,12 +2,32 @@ import std/macros
import ./without
import ./private/binderror
macro without*(condition, errorname, body): untyped =
proc undoSymbolResolution(expression, ident: NimNode): NimNode =
## Finds symbols in the expression that match the `ident` and replaces them
## with `ident`, effectively undoing any symbol resolution that happened
## before.
const symbolKinds = {nnkSym, nnkOpenSymChoice, nnkClosedSymChoice}
if expression.kind in symbolKinds and eqIdent($expression, $ident):
return ident
for i in 0..<expression.len:
expression[i] = undoSymbolResolution(expression[i], ident)
expression
macro without*(condition, errorname, body: untyped): untyped =
## Used to place guards that ensure that a Result contains a value.
## Exposes error when Result does not contain a value.
let errorIdent = ident $errorname
# Nim's early symbol resolution might have picked up a symbol with the
# same name as our error variable. We need to undo this to make sure that our
# error variable is seen.
let body = body.undoSymbolResolution(errorIdent)
quote do:
var error: ref CatchableError

View File

@ -286,6 +286,7 @@ suite "result":
proc shouldCompile(_: type int): ?!int =
without _ =? int.failure "error", existingName:
check existingName.msg == "error"
return success 42
discard int.shouldCompile()