Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Created May 20, 2011 19:33
Show Gist options
  • Save mathieuancelin/983611 to your computer and use it in GitHub Desktop.
Save mathieuancelin/983611 to your computer and use it in GitHub Desktop.
import tools.nsc.interpreter.Results._
import tools.nsc.interpreter.IMain
import tools.nsc.Settings
class ResultHolder(var value : Any)
class ScalaInterpreter(settings: Settings) extends IMain(settings) {
val writer = new java.io.StringWriter()
def resetWriter = {
writer.getBuffer.setLength(0)
}
}
object Interpreter {
val settings = new Settings
settings.usejavacp.value = true
val interpreter = new ScalaInterpreter(settings);
def bind(name : String, value : AnyRef) {
interpreter.bind(name, value.getClass.getName, value)
}
def eval(code : String) : Any = {
interpreter.resetWriter
val holder = new ResultHolder(null)
bind("$result__", holder);
val result = interpreter.interpret("$result__.value = " + code);
result match {
case Success => holder.value
case Error => throw new RuntimeException("error in: '" + code + "'\n" + interpreter.writer toString)
case Incomplete => throw new RuntimeException("incomplete in :'" + code + "'\n" + interpreter.writer toString)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment