Consider the following nim source:
import macros, os, strutils
macro dumbMacro(debug = false): typed =
let
debug = if debug.boolVal: "stderr.writeLine \"DEBUG ON\"" else: ""
parseStmt("""
echo "Hello from dumbMacro!"
{debug}
""".replace("{debug}", debug)
)
proc main() =
let debug = "-d" in commandLineParams()
dumbMacro debug
when isMainModule:
main()
I expect it to say DEBUG ON when I supply -d as a command line argument, but it doesn't. How can I make it do so? Also, on a side note, is there a way to force inline a procedure? The macro I'm messing with is the body of a loop that gets executed many times; while I can make it a simple procedure, the performance goes down considerably.
This works:
# ...
proc main() =
let debug = "-d" in commandLineParams()
if debug:
dumbMacro true
else:
dumbMacro false
# ...
But this does not:
# ...
proc main() =
let debug = "-d" in commandLineParams()
dumbMacro(if debug: true else: false)
# ...
Why is that? I thought if debug: true else: false would get 'resolved' to either true or false, but clearly something else is going on. Is there a way to 'extract' the boolean value of (the identifier) debug in the macro, so I don't have to write 4 lines?
The macro will slurp if debug: true else: false as expression. It will not be resolved; instead, inside the macro, you will have this whole expression in your variable debug.
Is there a way to 'extract' the boolean value of (the identifier) debug in the macro
It does not have a value when the macro is executed. The macro is executed at compile-time. The debug in main() is a let variable, i.e. is set at run-time. The macro cannot possibly know its value when it executes, because it isn't set yet.
The macro I'm messing with is the body of a loop that gets executed many times; while I can make it a simple procedure, the performance goes down considerably.
It seems like you want to use a simple template instead:
template dumbMacro(debug: bool = false): typed =
if debug:
stderr.writeLine "DEBUG ON"
echo "Hello from dumbMacro!"
proc main() =
let debug = "-d" in commandLineParams()
dumbMacro debug
when isMainModule:
main()