how to check errors happening inside scala interpreter programatically

半世苍凉 提交于 2019-12-03 17:34:46

The interpret method of the Interpreter returns a result value which indicates if the code could be successfully interpreted or not. Thus:

interp.beQuietDuring {
  interp.bind("res", res.getClass.getCanonicalName, res)
  interp.interpret("res.value = "+expression)
} match {
   case Results.Error => error( ... )
   case Results.Incomplete => error( ... )
   case Results.Success => res.value
}

Two more things: You don't need to bind "res" for every eval, it should be sufficient to do that once you initialize the interpreter. Also, note that there is a method mostRecentVar, so you may do away with the result binding altogether. Here is an example for Scala 2.9 (same as 2.8, but instead of Interpreter you use IMain):

import tools.nsc.interpreter.{IMain, Results}
import sys.error
val interp = new IMain()
def eval( expression: String ) : AnyRef =
   interp.interpret( expression ) match {
      case Results.Error => error( "Failed" )
      case Results.Incomplete => error( "Incomplete" )
      case Results.Success => interp.valueOfTerm( interp.mostRecentVar )
        .getOrElse( error( "No result" ))
   }

Testing:

scala> val x = eval( "1 + 2" )
res0: Int = 3
x: AnyRef = 3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!