(这与Scala script in 2.11和Generating a class from string and instantiating it in Scala 2.10松散相关。)
在下面的代码中,我使用Toolbox将运行时代码解析为相应的AST。如何在AST中添加符号定义(prefix
)到AST,以便在表达式树中使用这些符号?
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox
object Main extends App {
val cm = runtimeMirror(getClass.getClassLoader)
val tb = cm.mkToolBox()
val expr = tb.parse("println(i)")
val build = internal.reificationSupport
val prefix = build.setInfo(build.newFreeTerm("i", 2), typeOf[Int])
// TODO: add prefix before expr by some AST manipulation
tb.eval(expr)
}