Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke the Scala compiler programmatically?

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.

like image 357
Anuj Mehta Avatar asked Dec 02 '13 07:12

Anuj Mehta


People also ask

How do I compile and run a Scala program?

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.

How does the Scala compiler work?

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.

Which compiler is used in Scala?

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.

Does Scala use compiler or interpreter?

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.


1 Answers

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.

scala.tools.nsc.Global

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.

scala.tools.ncs.IMain

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.

like image 58
Eugene Yokota Avatar answered Sep 23 '22 09:09

Eugene Yokota