Skip to content

Instantly share code, notes, and snippets.

@DavideGalilei
Last active December 8, 2021 16:26
Show Gist options
  • Save DavideGalilei/4c8cf85fd757adc1ed22517db002bc4e to your computer and use it in GitHub Desktop.
Save DavideGalilei/4c8cf85fd757adc1ed22517db002bc4e to your computer and use it in GitHub Desktop.
Nim with macro
import macros
proc replaceIdents(node: NimNode, name, to: string): NimNode =
result = node
for i in 0 ..< len(result):
if result[i].kind == nnkIdent and eqIdent(result[i], name):
result[i] = ident(to)
else:
result[i] = result[i].replaceIdents(name, to)
macro with(head: untyped, body: untyped): untyped =
head.expectKind(nnkInfix)
let name = head[2].strVal
let to = head[1].strVal
result = body.replaceIdents(name, to)
var x = 123
with x as y:
echo y
for i in 1 .. 5:
echo y + i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment