0

(This is loosely related to Scala script in 2.11 and Generating a class from string and instantiating it in Scala 2.10).

In the code below I have a code parsed runtime using Toolbox into a corresponding AST. How can add symbol definitions (prefix in the code below) to the AST so that those symbols can be used in the expression tree?

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)
}
Community
  • 1
  • 1
Suma
  • 33,181
  • 16
  • 123
  • 191
  • You need to traverse `expr` using a subclass of `Traverser` and then for all occurrences of `i` (i.e. Idents that say `i`) call `tree.setSymbol(prefix)`. – Eugene Burmako May 13 '15 at 12:27
  • Alternatively, you could build `expr` with the correct symbols to begin with, e.g. something like `q"println($prefix)"`. – Eugene Burmako May 13 '15 at 12:27
  • @EugeneBurmako Thanks, I will try the Traverser and post results here (if it works, you or I can post it as a full answer). Building with correct symbols seems difficult, as the expr is a script edited by users. I therefore want its syntax to be as natural as possible, using $xxx for predefined variables is possible, but if there is other solution, I will prefer it. – Suma May 13 '15 at 19:36

0 Answers0