在快速和脏调试期间,我经常使用如下表达式:
echo "variable1: ", variable1, " variable2: ", variable2
如何利用Nim的宏系统来避免重复变量名?
答案 0 :(得分:5)
您可以使用迭代参数的varargs宏,并生成一个AST,它打印节点的字符串文字及其值。像这样:
import macros
macro debug*(n: varargs[typed]): untyped =
result = newNimNode(nnkStmtList, n)
for i in 0..n.len-1:
if n[i].kind == nnkStrLit:
# pure string literals are written directly
result.add(newCall("write", newIdentNode("stdout"), n[i]))
else:
# other expressions are written in <expression>: <value> syntax
result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i])))
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": ")))
result.add(newCall("write", newIdentNode("stdout"), n[i]))
if i != n.len-1:
# separate by ", "
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(", ")))
else:
# add newline
result.add(newCall("writeLine", newIdentNode("stdout"), newStrLitNode("")))
使用示例:
let x = 2
let y = 3
debug("hello", x, y, x*y)
输出:
hello, x: 1, y: 2, x * y: 6