If you need or want to traverse the structure of the data in the macro, first you need to make the variable a const
. var
are for runtime, so the macro will just get a nnkSym
node. Once you make that a const
you get the same input as if you had typed yourself the value manually there. I'll use the treeRepr
macro and plenty of echo
to show you what kind of AST you get and how you would walk it:
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)
When I compile that example I get the following output:
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