Skip to content

Instantly share code, notes, and snippets.

@amb
Last active July 21, 2023 20:49
Show Gist options
  • Save amb/97b0366d733786bf5168dea9ff02e5a0 to your computer and use it in GitHub Desktop.
Save amb/97b0366d733786bf5168dea9ff02e5a0 to your computer and use it in GitHub Desktop.
Demo/test of Nim macros
import std/macros
macro makeVar(arg: varargs[untyped]): untyped =
result = newStmtList()
for a in arg:
result.add newVarStmt(a, a)
# echo result.treeRepr
macro lazyVar(arg: untyped): untyped =
var statements = newStmtList()
let fparms = arg.findChild(it.kind == nnkFormalParams)
for fp in fparms:
if fp.kind == nnkIdentDefs:
let vtype = fp[^2]
if vtype.kind == nnkVarTy:
# Operate only on constants
continue
if $vtype == "int":
for v in fp:
if v.kind == nnkIdent:
if v == vtype:
break
statements.add newVarStmt(v, v)
statements.add arg.body
arg.body = statements
return arg
proc add(a, b, c: int): int {.lazyVar.} =
c = c + a + b
return c
echo add(5, 4, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment