Created
September 27, 2024 01:16
-
-
Save dneumann42/6d12e91fe3769dc83362cfa666e4af03 to your computer and use it in GitHub Desktop.
Error handling macros in nim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template `?`* [T](o: Option[T]) = | |
block: | |
if o.isNone: | |
return none(T) | |
o.get() | |
macro R(T, F, p: untyped) = | |
expectKind(p, nnkProcDef) | |
p[3][0] = nnkBracketExpr.newTree(newIdentNode("Result"), T, F) | |
let templateDefs = quote do: | |
template Err(f: `F`): auto = | |
Result[`T`, `F`].err(f) | |
template Ok(t: `T`): auto = | |
Result[`T`, `F`].ok(t) | |
var body = p[^1] | |
var newBody = newStmtList() | |
newBody.add(templateDefs) | |
for i in 0 ..< body.len: | |
newBody.add(body[i]) | |
p[^1] = newBody | |
result = p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment