3

使用 Scala (runtime) reelection API,我正在尝试编译大量使用隐式的代码(实际上是 spire.math 库):

    val src = "(a: spire.math.Jet[Double],b: spire.math.Jet[Double]) => a + b"
    println( toolBox.eval(toolBox.parse(src)))

尽管这些隐式在调用 toolbox.eval 的范围内是可见的,但反射编译仍然失败:

could not find implicit value for parameter f: spire.algebra.Field[Double]

如何使工具箱可以使用此信息?

4

1 回答 1

4

在我们回答这个问题之前,让我们首先修复 Scala 版本并使您的问题可重现。假设我们使用 Scala 2.11.8、sbt 0.13.11 和 spire-math 0.11.0。

然后裸 build.sbt 可能如下所示:

name := "test"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value

libraryDependencies += "org.spire-math" %% "spire" % "0.11.0"

并且您的代码可以存储在Test.scala文件中,如下所示:

import spire.implicits._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

object Test {
  def main(args: Array[String]) = {
    val toolBox = currentMirror.mkToolBox()
    val src ="""
        |(a: spire.math.Jet[Double],b: spire.math.Jet[Double]) => a + b
      """.stripMargin
    println (toolBox.eval(toolBox.parse(src)))
  }
}

执行后sbt run,您获得:

$ sbt run
[info] Running Test 
[error] scala.tools.reflect.ToolBoxError: reflective compilation has failed:
[error] could not find implicit value for parameter f: spire.algebra.Field[Double]

因此,您的问题是,即使定义的隐式import spire.implicits._包含在toolBox实例化和eval调用的范围内,为什么这会失败。

好吧,请注意,在您的用例中,您有两个独立调用编译器的阶段。第一阶段是编译,Test.scala第二阶段是编译和执行(a: spire.math.Jet[Double],b: spire.math.Jet[Double]) => a + b

这两个阶段性不在同一运行时中运行。在第一阶段,将调用编译器来编译Test.scala文件,在第二阶段,它将在 JVM 运行时内调用以编译src字符串。结果,这两个阶段不会共享相同的范围,只是因为它们在不同的运行时执行。

这个问题的一个快速解决方案是在第二阶段的范围内“重新引入”隐含。换句话说,您import spire.implicits._在尝试编译的字符串中添加:

import spire.implicits._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

object Test {
  def main(args: Array[String]) = {
    val toolBox = currentMirror.mkToolBox()
    val src ="""
        |import spire.implicits._
        |(a: spire.math.Jet[Double],b: spire.math.Jet[Double]) => a + b
      """.stripMargin
    println (toolBox.eval(toolBox.parse(src)))
  }
}

结果是:

$ sbt run
[info] Running Test 
<function2>
[success] Total time: 5 s, completed Jul 13, 2016 1:48:59 AM

希望这能回答你的问题。如果您想深入了解 Scala 编译器如何在作用域中搜索隐式,那么这里就是一个好的开始。

于 2016-07-13T00:08:59.917 回答