¿Compilar cadena para AST dentro de CompilerPlugin?

Me gustaría crear un plugin de plantillas y como primer paso convertir una cadena arbitraria a su representación AST "compilada" (como lo hace el intérprete de scala, supongo). Por lo tanto, un complemento del compilador podría, por ejemplo, asignar someString a "HELLO WORLD":

  @StringAnnotation("""("hello world").toString.toUpperCase""")
  var someString = ""

Mi complemento de primer disparo actual lo hace en resumen:

analizador runaftercrear un nuevo compilador solo de representación y un VirtualFile con el contenido de la anotacióncompilar e imprimir unit.body

ver:http://paste.pocoo.org/show/326025/

a) ahora mismo"object o{val x = 0}" devuelve un AST, pero p."var x = 1+ 2" no porque no sería un archivo .scala válido. ¿Cómo puedo arreglar esto?

b) ¿OnlyPresentation es una buena opción? ¿Debería anular en cambio computeInternalPhases con las fases apropiadas o usar -Ystop: phase?

c) ¿Es posible vincular el entorno del compilador externo al interno, de modo que, p.

  var x = _
  (...)
  @StringAnnotation("x += 3")

¿trabajaría?

Encontré el siguiente código [1] usando un intérprete y una variable que hace algo similar:

  Interpreter interpreter = new Interpreter(settings);
  String[] context = { "FOO" };
  interpreter.bind("context", "Array[String]", context);
  interpreter
    .interpret("de.tutorials.scala2.Test.main(context)");
  context[0] = "BAR";
  interpreter
    .interpret("de.tutorials.scala2.Test.main(context)");

[1]http://www.tutorials.de/java/320639-beispiel-zur-einbindung-des-scala-interpreters-kompilierte-scala-anwendungen.html#post1653884

Gracias

Código completo:

class AnnotationsPI(val global: Global) extends Plugin {
  import global._
  val name = "a_plugins::AnnotationsPI" //a_ to run before namer
  val description = "AST Trans PI"
  val components = List[PluginComponent](Component)

  private object Component extends PluginComponent with Transform with TypingTransformers with TreeDSL {
    val global: AnnotationsPI.this.global.type = AnnotationsPI.this.global
    val runsAfter = List[String]("parser");
    val phaseName = AnnotationsPI.this.name

    def newTransformer(unit: CompilationUnit) = {
      new AnnotationsTransformer(unit)
    }

    val SaTpe = "StringAnnotation".toTypeName

    class AnnotationsTransformer(unit: CompilationUnit) extends TypingTransformer(unit) {

      /** When using <code>preTransform</code>, each node is
       *  visited before its children.
       */
      def preTransform(tree: Tree): Tree = tree match {
        case anno@ValDef(Modifiers(_, _, List(Apply(Select(New(Ident(SaTpe)), _), List(Literal(Constant(a))))), _), b, c, d) => //Apply(Select(New(Ident(SaTpe)), /*nme.CONSTRUCTOR*/_), /*List(x)*/x)
          val str = a.toString
          val strArr = str.getBytes("UTF-8")
          import scala.tools.nsc.{ Global, Settings, SubComponent }
          import scala.tools.nsc.reporters.{ ConsoleReporter, Reporter }

          val settings = new Settings()
          val compiler = new Global(settings, new ConsoleReporter(settings)) {
            override def onlyPresentation = true
          }

          val run = new compiler.Run
          val vfName = "Script.scala"
          var vfile = new scala.tools.nsc.io.VirtualFile(vfName)

          val os = vfile.output
          os.write(strArr, 0, str.size) // void  write(byte[] b, int off, int len) 
          os.close
          new scala.tools.nsc.util.BatchSourceFile(vfName, str)
          run.compileFiles(vfile :: Nil)
          for (unit <- run.units) {
            println("Unit: " + unit)
            println("Body:\n" + unit.body)
          }
          tree

        case _ =>
          tree
      }

      override def transform(tree: Tree): Tree = {
        super.transform(preTransform(tree))
      }
    }
  }

Respuestas a la pregunta(1)

Su respuesta a la pregunta