3

I am trying to invoke scala interpreter programmatically using the following code

val settings = new Settings()
settings.usejavacp.value = true
settings.embeddedDefaults[Probe]
classPath.map(settings.classpath.prepend(_))
classPath.map(settings.bootclasspath.prepend(_))
settings.withErrorFn(err => println(s"error while compiling $err"))
val compile = new Global(settings)
val run = new compile.Run
val sourceFiles = run.compile("Test.scala")

Test.scala looks like

class Test {
   println ("Hello World!")
}

build.sbt dependencies looks like

libraryDependencies ++= Seq(
  "org.scala-lang" % "scala-compiler" % "2.11.7",
  "org.scala-lang" % "scala-library" % "2.11.7",
  "org.scala-lang" % "scala-reflect" % "2.11.7"
)

and getting following error

[error] (run-main-1e) scala.reflect.internal.FatalError: class StringContext does not have a member f

I have tried prepending scala-reflect-2.11.7.jar and scala-library-2.11.7.jar, but nothing seems to do work

np-hard
  • 5,725
  • 6
  • 52
  • 76
  • don't know whether it meats your requirements or not, but it might be much simpler to use [ToolBox](http://www.scala-lang.org/files/archive/nightly/docs-2.10.3/compiler/index.html#scala.tools.reflect.ToolBox) if you need to interpret only a script. Btw, you're more like calling the compiler (not interpreter) in your example – dk14 Feb 02 '16 at 07:00
  • http://stackoverflow.com/questions/20322543/how-to-invoke-the-scala-compiler-programmatically – dk14 Feb 02 '16 at 07:09
  • toolbox cant load package statements, unfortunately i need to parse files with package statements – np-hard Feb 02 '16 at 19:36
  • Any luck with this? I'm also having the same problem. – metasim May 19 '16 at 20:52
  • I was eventually able to do this using scala presentation compiler, you can download scala source code and look at this test, could be a starting point https://github.com/scala/scala/blob/99a82be91cbb85239f70508f6695c6b21fd3558c/test/files/presentation/t7915/Test.scala – np-hard Jun 10 '16 at 22:41

1 Answers1

0

Remove settings.usejavacp.value = true, that should help.

PS: no need for Probe, you can just use settings.embeddedDefaults(getClass.getClassLoader)

tim zh
  • 93
  • 6