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.
Press "control o" to save the file and then press enter. Press "control x" to exit the nano editor. To compile the code, type "scalac hello_world. scala" and press enter.
The Scala compiler compiles your Scala code into Java Byte Code which can then be executed by the scala command. The scala command is similar to the java command, in that it executes your compiled Scala code. Since the Scala compiler can be a bit slow to startup, Scala has a compiler daemon you can run.
Scala Native is a Scala compiler that targets the LLVM compiler infrastructure to create executable code that uses a lightweight managed runtime, which uses the Boehm garbage collector.
Scala gives you an illusion of an interpreted language. But actually it is a compiled language, wherein everything you type gets compiled to the byte code and it runs within the JVM.
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.
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.
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")
}
This was demonstrated in Embedding the Scala Interpreter post by Josh Suereth back in 2009.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With