Teach chk about Result

This commit is contained in:
Zahary Karadjov 2020-04-07 18:32:20 +03:00
parent 12a6cc2027
commit 8fd43269dc
No known key found for this signature in database
GPG Key ID: C8936F8A3073D609
2 changed files with 29 additions and 1 deletions

View File

@ -2,6 +2,9 @@ import
typetraits, strutils,
shims/macros, results
export
results
const
enforce_error_handling {.strdefine.}: string = "yes"
errorHandlingEnforced = parseBool(enforce_error_handling)
@ -152,7 +155,13 @@ template raising*[E, R](x: Raising[E, R]): R =
## by the `errors` pragma.
distinctBase(x)
macro chk*[R, E](x: Raising[R, E], handlers: untyped): untyped =
template raising*[R, E](x: Result[R, E]): R =
tryGet(x)
macro chk*(x: Result, handlers): untyped =
discard
macro chk*(x: Raising, handlers: untyped): untyped =
## The `chk` macro can be used in 2 different ways
##
## 1) Try to get the result of an expression. In case of any

View File

@ -7,6 +7,18 @@ proc bar(x: int): int {.noerrors.} =
proc toString(x: int): string {.errors: (ValueError, KeyError, OSError).} =
$x
enum
ReadStatus = enum
FileNotFound
AccessDenied
HardwareError
proc readFromDevice(path: string): Result[seq[byte], ReadStatus] =
err AccessDenied
proc getGpsCoordinates(): Result[(float, float), cstring] =
ok (1.2, 3.4)
proc main =
let
a = bar(10)
@ -16,6 +28,13 @@ proc main =
KeyError as err: err.msg
OSError: raise
d = chk(readFromDevice("test"), @[1.byte, 2, 3])
e = chk readFromDevice("test"):
FileNotFound: raise newException()
HardwareError: quit 1
else: @[]
echo a
echo b
echo c