如何以编程方式调用 Scala 编译器? [英] How to invoke the Scala compiler programmatically?
问题描述
我希望我的 Scala 代码将 Scala 类作为输入,编译并执行该类.如何以编程方式调用 Scala 编译器?我将使用最新的 Scala 版本,即 2.10.
I want my Scala code to take a Scala class as input, compile and execute that class. How can I programmatically invoke a Scala compiler? I will be using the latest Scala version, i.e. 2.10.
推荐答案
ToolBox
我认为调用 Scala 编译器的正确方法是通过 概述一>.具体来说,通过解析工具箱创建树部分在符号,树"中和 Types 讨论了使用 ToolBox
将 String
解析为 Tree
.然后你可以调用 eval()
等等.
ToolBox
I think the proper way of invoking the Scala compiler is doing it via Reflection API documented in Overview. Specifically, Tree Creation via parse on ToolBoxes section in 'Symbols, Trees, and Types' talks about parsing String
into Tree
using ToolBox
. You can then invoke eval()
etc.
但正如 Shyamendra Solanki 所写,实际上您可以驱动 scalac 的 Global
来完成更多工作.我写了 CompilerMatcher 生成的代码例如,用于进行集成测试的示例代码.
But as Shyamendra Solanki wrote, in reality you can drive scalac's Global
to get more done. I've written CompilerMatcher so I can compile generated code with sample code to do integration tests for example.
您可以调用 REPL IMain
来评估代码(如果您想要一些适用于 Scala 2.10 的东西,这也可以在上面的 CompilerMatcher
中使用):
You can invoke the REPL IMain
to evaluate the code (this is also available in the above CompilerMatcher
if you want something that works with Scala 2.10):
val main = new IMain(s) {
def lastReq = prevRequestList.last
}
main.compileSources(files.map(toSourceFile(_)): _*)
code map { c => main.interpret(c) match {
case IR.Error => sys.error("Error interpreting %s" format (c))
case _ =>
}}
val holder = allCatch opt {
main.lastReq.lineRep.call("$result")
}
这一点在 Josh Suereth 于 2009 年发表的嵌入 Scala 解释器帖子中得到了证明.
This was demonstrated in Embedding the Scala Interpreter post by Josh Suereth back in 2009.
这篇关于如何以编程方式调用 Scala 编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!