In scala 2.9.x I used tools.nsc.Global
directly to compile certain string into a class and execute it.
In scala 2.10, it is possible to replace it with something like the following:
import scala.reflect.runtime._;
val cm = universe.runtimeMirror(getClass.getClassLoader)
import scala.tools.reflect.ToolBox;
val tb = cm.mkToolBox()
tb.eval(tb.parse("class C; new C"))
And it works flawlessly. The only problem is that with old (deprecated) approach, I could get extremely pretty summary of all compilation failures using StoreReporter (with error messages, line numbers), and new approach just throws an exception on compilation error.
Is there some way to reify that?
scala> import scala.reflect.runtime._
import scala.reflect.runtime._
scala> val cm = universe.runtimeMirror(getClass.getClassLoader)
cm: reflect.runtime.universe.Mirror = JavaMirror with ...
scala> import scala.tools.reflect.ToolBox
import scala.tools.reflect.ToolBox
scala> val tb = cm.mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@712fe0c0
scala> tb.eval(tb.parse("class C; new D"))
scala.tools.reflect.ToolBoxError: reflective compilation has failed:
not found: type D
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.throwIfErrors(ToolBoxFactory.scala:312)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.compile(ToolBoxFactory.scala:248)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.compile(ToolBoxFactory.scala:407)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.eval(ToolBoxFactory.scala:410)
...
scala> tb.frontEnd.infos
res1: ... = Set(Info(NoPosition,not found: type D,ERROR))
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