Hi,
I am still very new to nim, so what I am trying to do may not be making sense at all. The thing I am trying to do with nim macro is simple: create a duplication of a proc. Everything remains the same except the name is changed to [proc_name]duplicate (I plan to do some manipulation with the proc but I stucked here) The code is:
import macros
macro duplicate(procStmt: typed): typed =
procStmt.expectKind nnkStmtList
let procDef = procStmt[0]
procDef.expectKind nnkProcDef
let name = newIdentNode($procDef[0] & "_duplicate")
var params: seq[NimNode]
params = @[]
for param_id in 0..<len(procDef[3]):
params.add copy(procDef[3][param_id])
let body = copy(procDef[6])
return newStmtList(newProc(name, params, body))
duplicate:
proc foo(x: int): void =
echo(x)
and when compiling I get:
duplicate.nim(19, 1) template/generic instantiation from here
duplicate.nim(21, 10) Error: internal error: environment misses: x
if the proc has a return value like this:
duplicate:
proc foo(x: int): int =
result = x
then there is a different error:
duplicate.nim(19, 1) template/generic instantiation from here
duplicate.nim(21, 5) Error: illegal capture 'result'
Am I doing something wrong? What is the correct way to do this?
Thanks!
Try instead
macro duplicate(procStmt: untyped): untyped =
...