Search code examples
elixirabstract-syntax-tree

Using "quote do" with a "nil" context


is there an alternative to this non-working code?

ast = quote context: nil do 
  x = y 
end
Code.eval_quoted(ast, y: 2)

I want the AST to be : {:=, [], [{:x, [], nil}, {:y, [], nil}]} (so the eval knows the y is coming from the bindings)

Is it possible or must I create a context?


Solution

  • The whole quote/1 block has its own context, in the first place. Just passing y: 2 as the second parameter of Code.eval_quoted/2 won’t work without bypassing macro hygiene explicitly.

    That said, if one wants to get y from the context, they must use Kernel.var!/2 within the macro body.

    That said, the question cannot be answered as it’s stated: to enforce y coming from context, which in turn can be only passed to Code.eval_quoted/2 through explicit bindings, one might use

    ast = quote do: x = var!(y)
    

    but then the question where x comes from then would be raised.