Skip to content

Instantly share code, notes, and snippets.

@dneumann42
Created September 27, 2024 01:16
Show Gist options
  • Save dneumann42/6d12e91fe3769dc83362cfa666e4af03 to your computer and use it in GitHub Desktop.
Save dneumann42/6d12e91fe3769dc83362cfa666e4af03 to your computer and use it in GitHub Desktop.
Error handling macros in nim
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