Created
May 20, 2011 19:33
-
-
Save mathieuancelin/983611 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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