elixir eval ast
In Elixir, the Code.eval_quoted/3
function can be used to evaluate an abstract syntax tree (AST). This function takes three arguments: the AST to evaluate, the context in which to evaluate it, and a list of options.
Here is an example of how to use Code.eval_quoted/3
to evaluate an AST:
ast = quote do
2 + 2
end
context = %{}
result = Code.eval_quoted(ast, context)
IO.inspect(result)
In this example, we define an AST using the quote
macro, which represents the expression 2 + 2
. We then create an empty context using the %{}
syntax. Finally, we call Code.eval_quoted/3
with the AST, the context, and store the result in the result
variable. We use IO.inspect/1
to print the result to the console.
When you run this code, it will output 4
, which is the result of evaluating the AST 2 + 2
in the given context.
Note that evaluating arbitrary ASTs can be dangerous, as it can execute arbitrary code. It is important to ensure that the AST being evaluated comes from a trusted source to prevent potential security vulnerabilities.