I'm trying to grok how macros work and I'm a bit confused.Is it possible to
evaluate an AST w/in a macro? In other words once I build up an AST, can I
evaluate it within the macro so I can apply additional procs to the results of
the evaluation before returning the results?
For example, I'm trying to write a macro which will take this syntax and return
two tables: 1) one mapping left values to right values and 2) the other mapping
right values to left values.
# Desired notation:
let (a,b) = DualMap:
1 <-> "one"
2 <-> "two"
# desired output
a = {1: "one", 2: "two"}
b = {"one":1, "two":2}
Run
Here's what I've got so far which builds up the desired table constructors
correctly. But now I want to call tables.toTable on the two constructed tables
(=arrays) before returning the results. Is this possible to do w/in a macro?
import macros, table
macro DualMap(body: untyped): untyped =
body.expectKind nnkStmtList
result = newStmtList()
var tbl1 = newTree(nnkTableConstr)
var tbl2 = newTree(nnkTableConstr)
for child in body:
if child.kind == nnkInfix and $child[0] == "<->":
var e1 = newColonExpr(child[1], child[2])
var e2 = newColonExpr(child[2], child[1])
tbl1.add(e1)
tbl2.add(e2)
result.add = newPar(tbl1, tbl2)
# but would really like to do result.add(newPar(tbl1.toTable, tbl2.toTable))
Run