Does anybody have a macro or template that can create a proc from a string?
Given a seq like @[2,4,6], I'd like to generate "proc sig2()", "proc sig4()", and "proc sig6()" using strings s2, s4, and s6 as the body of each proc.
Alternately, I could "include sig2, sig4, sig6", but I don't want to put hundreds of thousands of procs in their own files. They ideally need to be in a single file or a database, so I'm looking for a way to build a proc from a string. I know it's possible, since I see a related macro mechanism in https://github.com/BlaXpirit/nimception. To actually build the strings, I'm thinking of using parsecfg's ability to parse triple-quoted string literals.
I initially thought I could just import all the procs as-required (i.e. "from sigs import sig2, sig4, sig6"), but that still compiles the entire "sigs" file, with my hundreds of thousands of procs, right? I don't want to get into trouble by running out of stack space or other issues by importing a monstrously huge file.
Thanks.
It's a bit fiddly because I didn't find a way to get the variable s2 from the string "s2" directly, so I added a second macro:
import macros
const
s2 = "echo \"foo\""
s4 = "echo \"bar\""
s6 = "echo \"baz\""
macro makeProc(name, body: static[string]): stmt =
result = newProc(name = ident(name), body = parseStmt(body))
macro makeProcs(xs: static[seq[int]]): stmt =
result = newStmtList()
for x in xs:
result.add newCall("makeProc", newStrLitNode("sig" & $x), ident("s" & $x))
makeProcs(@[2,4,6])
sig2()
sig4()
sig6()