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

How to debug print a variable (name) and its value in Nim?

在快速而肮脏的调试过程中,我经常使用如下表达式:

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

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

您可以使用可变参数宏来遍历参数,并生成一个 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