在CompilerPlugin中编译String到AST?

时间:2011-01-26 22:14:06

标签: scala compiler-construction scala-2.8

我想创建一个模板插件,并且作为第一步将任意字符串转换为它的“已编译”AST表示(正如scala解释器所做的那样,我猜)。所以编译器插件可以例如将someString分配给“HELLO WORLD”:

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

我目前的第一个镜头插件简而言之:

  • runafter parser
  • 创建一个新的仅表示编译器和一个带注释内容的VirtualFile
  • 编译并打印unit.body

请参阅:http://paste.pocoo.org/show/326025/

A) 现在,"object o{val x = 0}"返回AST,但是"var x = 1+ 2"不会,因为它不是有效的.scala文件。我该如何解决这个问题?

b)中 只是演示是一个不错的选择吗?我是否应该使用适当的阶段覆盖computeInternalPhases或使用-Ystop:phase?

c)中 是否可以将外部编译器的环境绑定到内部编译器,例如

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

会起作用吗?

我发现以下代码[1]使用解释器和一个类似的变量:

  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

感谢

完整代码:

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))
      }
    }
  }

1 个答案:

答案 0 :(得分:1)

我不知道这对你有多大帮助,但是你可以使用treeFrom(aString)而不是摆弄解释器,它是scala重构项目(http://scala-refactoring.org/)的一部分。虽然没有回答关于交叉绑定的问题,但是......