如何调试在Nim中打印变量(名称)及其值?

时间:2017-11-22 20:14:24

标签: nim

在快速和脏调试期间,我经常使用如下表达式:

echo "variable1: ", variable1, " variable2: ", variable2

如何利用Nim的宏系统来避免重复变量名?

1 个答案:

答案 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