使Scala解释器在解释调用之间无视

是否可以配置
Scala解释器(tools.nsc.IMain),以便在我运行下一个interpret()调用时“忘记”以前执行的代码?

通常,当它编译源时,它会将它们包装在嵌套对象中,因此所有先前定义的变量,函数和绑定都可用.

它不足以生成嵌套对象(或抛弃它们),虽然我更喜欢一种解决方案,它甚至可以再次从类加载器中删除以前编译的类.

是否有设置,方法,或者我可以覆盖的东西,或IMain的替代方案可以实现这一目标?我需要仍然能够从主机VM访问生成的对象/类.

基本上我想隔离后续的interpret()调用,而不是像为每次迭代创建一个新的IMain那么重.

最佳答案 这是一个可能的答案.基本上有方法reset()调用以下内容(大多数是私有的,所以你要么购买整个软件包):

clearExecutionWrapper()
resetClassLoader()
resetAllCreators()
prevRequests.clear()
referencedNameMap.clear()
definedNameMap.clear()
virtualDirectory.clear()

在我的例子中,我使用自定义执行包装器,因此需要再次设置,并且还通过常规解释周期处理导入,因此要么再次添加它们,要么更好 – 只需将它们与执行包装器一起添加.

我想保留我的绑定,它们也消失了:

import tools.nsc._
import interpreter.IMain

object Test {
  private final class Intp(cset: nsc.Settings)
    extends IMain(cset, new NewLinePrintWriter(new ConsoleWriter, autoFlush = true)) {

    override protected def parentClassLoader = Test.getClass.getClassLoader
  }

  object Foo {
    def bar() { println("BAR" )}
  }

  def run() {
    val cset = new nsc.Settings()
    cset.classpath.value += java.io.File.pathSeparator + sys.props("java.class.path")
    val i = new Intp(cset)
    i.initializeSynchronous()
    i.bind[Foo.type]("foo", Foo)
    val res0 = i.interpret("foo.bar(); val x = 33")
    println(s"res0: $res0")
    i.reset()
    val res1 = i.interpret("println(x)")
    println(s"res1: $res1")
    i.reset()
    val res2 = i.interpret("foo.bar()")
    println(s"res2: $res2")
  }
}

这将在第一次迭代中找到Foo,在第二次迭代中正确地忘记x,但是在第三次迭代中,可以看出foo绑定也丢失了:

foo: Test.Foo.type = Test$Foo$@8bf223
BAR
x: Int = 33
res0: Success
<console>:8: error: not found: value x
              println(x)
                      ^
res1: Error
<console>:8: error: not found: value foo
              foo.bar()
              ^
res2: Error

以下似乎没问题:

for(j <- 0 until 3) {
  val user  = "foo.bar()"
  val synth =  """import Test.{Foo => foo}
               """.stripMargin + user
  val res = i.interpret(synth)
  println(s"res$j: $res")
  i.reset()
}
点赞