Hello,
I'm trying to achieve something like this:
proc someProc() {.script.} =
# do stuff
# then use each proc annotated with {.script.} as a proc argument
I was thinking I could use pragmas to build a compile-time sequence of procs with the script pragma, but I don't know how to do so.
Is what I'm trying to do possible, and if it is, how can I achieve it?
To be able to process the code containing the proc definitons, they have to be passed to a macro. This can be done by indenting and passing the code block like this
import processcode
processCode:
proc someProc() {.script.} = discard
or, without indenting the code, with a source code filter which processes the entire module:
#? stdtmpl(emit="")
#import processcode
#processModuleSrc "" &
proc someProc() {.script.} = discard
In both cases, processcode.nim is needed:
import macros, strutils
# define the custom pragma
template script* {.pragma.}
macro processCode*(body: untyped): untyped =
result = body
# analyze the body and build whatever you need to add to the result.
macro processModuleSrc*(src: string): typed =
getAst(processCode(src.strVal.parseStmt))
You can use something like this:
import macros
var procs {.compileTime.}: seq[NimNode]
macro script(p: typed): typed =
procs.add p
proc someProc() {.script.} =
discard
static:
echo procs.repr
However, this requires global compile time state, which will likely not be supported this way when incremental compilation is finished. See https://github.com/nim-lang/Nim/issues/7874