How to Compile ASTs into functions that take arguments at runtime

I have been working on using Scala’s Toolbox to generate ASTs (Abstract Syntax Trees) from external files and then modifying these trees so that they can now be compiled into code that uses a different set of libraries. Now, I would like to take these ASTs and use Toolbox.compile() to create a function that uses these ASTs.

The problem that I have been running into is that Toolbox.compile() only returns a function of type

() => Any

which means that the AST that is compiled needs to be completely independent of the rest of my code. Instead I am looking for something more along these lines:

(x:Any, y:Any) => Any

Is there any way that I can compile ASTs so that the function can take arguments?

Thanks in advanced

I don’t understand. Do you want to have a function that takes two Trees, inserts those into another Tree and evaluates the resulting Tree? Or do you have a Tree that represents a function?

In the first case

def compile(tree: Tree): (Tree, Tree) => Any = {
// you can do something fancier here than putting everything in a Block of course
  (t1, t2) => toolbox.eval( Block(tree, t1, t2) )

In the second case

toolbox.eval(tree).asInstanceOf[(Any,Any) => Any]

I was actually just talking about a tree that is a chunk of code like the following:


However, your second case made me realized that I can simple modify the tree so that it returns a function that runs the code I originally had like this:

val test = (a:Integer, b:Integer) => {
return test

Turns out this works!
Thanks for the help!