Hi,
Is it possible to evaluate function body, or some other code block, in a different context, e.g. consider this simple repro:
import macros
# this macro evaluates function body in a different context
# and prints result at compile time
macro eval1(fun: untyped): untyped =
fun.expectKind nnkProcDef
let body = fun.body
let stmt = body[0]
echo stmt.treeRepr
let e =
quote do:
let x = 42
`stmt`
echo e # i'd like to see value 48 printed at compile time,
proc stmt1 {.eval1.}=
2*x
What I'd like is to evaluate the function body in a different context inside the macro. I seem unable to find out how to accomplish this.
Thanks
import macros
# this macro evaluates function body in a different context
# and prints result at compile time
macro eval1(fun: untyped): untyped =
fun.expectKind nnkProcDef
let body = fun.body
let stmt = body[0]
echo stmt.treeRepr
let x = ident"x" # Avoid capturing an inexisting ident x
result =
quote do:
block: # Create a new scope
static: # i'd like to see value 48 printed at compile time,
let `x` = 42
echo `stmt`
proc stmt1 {.eval1.}=
2*x
# Returns 84