I generate two AST's using two different templates. Replacing one node of the fist tree with the whole second tree woks fine. How can I define a variable in the first template and use it in the second?
template first(): untiped =
var n = 1
echo "this very line gets replaced with code from another template"
template second(): untiped =
n = 2 # <-- undefined
Working with macros without using templates is an exhausting affair. A couple lines of code produces a giant tree.
I can't use one single template because I can't iterate over passed arguments. So I've come up with such a solution: to generate tees separately and then merge them into one.
can't you pass the variable? if you just want to reuse it in a macro, you should generate the name outside and quote
let n = ident"n"
let first = quote:
var `n` = 1
..
let second = quote:
`n` = 2
# now first and second are NimNode with that AST, instead of expanding templates
inline templates are also useful, but I find quote nice for macros too!!
var n {.inject.} = 1 # makes it visible outside of the template body
This should help. Work through the macro- and template-related parts of the manual before trying too much, it saves a lot of time.
Tip: post code which compiles. Makes replies more likely.
Thank you for a useful advice. I create a mock of a procedure. I load module file, get a procedure AST out of it. Then I try to replace its body with assert statements.
assert(a == values.a)
assert(b == values.b)
where a and b are arguments of the procedure
Ah, sorry for misunderstanding you.
I managed to achieve this combination of two AST trees using the quote feature.
The only thing I dislike is how the result variable of the surrounding function travels inside the quote block. But they say it has been already fixed last summer (for macros).
https://github.com/nim-lang/Nim/issues/7323#issuecomment-451684288
The activity of AST stitching resembles to me DOM manipulation in JS.