如果需要或想要遍历宏中数据的结构,首先需要将变量 a const
。var
用于运行时,所以宏只会得到一个nnkSym
节点。一旦你做了那个,const
你就会得到相同的输入,就好像你在那里手动输入了值一样。我将使用treeRepr
宏和大量内容echo
向您展示您获得了什么样的 AST 以及您将如何使用它:
import macros
type
Tconfig = tuple
letters: seq[string]
numbers:seq[int]
const data: Tconfig = (@["aa", "bb"], @[11, 22])
macro mymacro(data: Tconfig): stmt =
echo "AST being passed in:\n", treeRepr(data)
echo "root type is ", data.kind
echo "number of children ", len(data)
let n1 = data[0]
echo "first child is ", n1.kind
echo "first child children ", len(n1)
let e2 = n1[1]
echo "second exp child is ", e2.kind
echo "second exp child children ", len(e2)
let v1 = e2[0]
echo "first seq value is ", v1.kind
echo "first seq value children ", len(v1)
echo "Final literal is ", v1.strVal
when isMainModule:
mymacro(data)
当我编译该示例时,我得到以下输出:
AST being passed in:
Par
ExprColonExpr
Sym "letters"
Bracket
StrLit aa
StrLit bb
ExprColonExpr
Sym "numbers"
Bracket
IntLit 11
IntLit 22
root type is nnkPar
number of children 2
first child is nnkExprColonExpr
first child children 2
second exp child is nnkBracket
second exp child children 2
first seq value is nnkStrLit
first seq value children 0
Final literal is aa