Ste*_* K. 6 compiler-construction scala scala-2.8
我想创建一个模板插件,并且第一步将任意字符串转换为它的"编译"AST表示(正如scala解释器所做的那样,我猜).所以编译器插件可以例如将someString分配给"HELLO WORLD":
@StringAnnotation("""("hello world").toString.toUpperCase""")
var someString = ""
Run Code Online (Sandbox Code Playgroud)
我目前的第一个镜头插件简而言之:
见: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")
Run Code Online (Sandbox Code Playgroud)
会工作?
我发现以下代码[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)");
Run Code Online (Sandbox Code Playgroud)
谢谢
完整代码:
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))
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道这是否对您有很大帮助,但是您可以使用 treeFrom( aString ),它是 scala 重构项目 ( http://scala-refactoring.org/ ) 的一部分,而不是摆弄解释器。不过,并没有回答你关于交叉绑定的问题......