Scala工具箱类型检查中的自定义类和对象
我试图使用Scala中的工具箱对任意AST进行类型检查。基本上,我是在用准量子来构建表达式,比如Scala工具箱类型检查中的自定义类和对象,scala,Scala,我试图使用Scala中的工具箱对任意AST进行类型检查。基本上,我是在用准量子来构建表达式,比如 newTree = q"$oldTree + $x" newTree = Typecheck(newTree) 其中,$oldTree是一个AST,其类型我不知道。我需要根据oldTree和x中已经存在的信息填写newTree.tpe等字段 Typecheck()的定义如下: import scala.reflect.runtime.universe._ import scala.reflect.
newTree = q"$oldTree + $x"
newTree = Typecheck(newTree)
其中,$oldTree
是一个AST,其类型我不知道。我需要根据oldTree
和x
中已经存在的信息填写newTree.tpe
等字段
Typecheck()
的定义如下:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
import bitstream.types._
object Typecheck {
def apply[A](treeStr: String): A = {
val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()
val tree = toolbox.parse(treeStr)
toolbox.typecheck(tree).asInstanceOf[A]
}
}
目前,我正在尝试处理以下内容:
Typecheck("types.this.Bit.bit2Int(d2_old)")
其中Bit.bit2Int()
是在包bitstream.types
中的对象Bit
中定义的方法。这是一个包含自定义类和对象的包。我当前得到的错误是:
scala.tools.reflect.ToolBoxError: reflective typecheck has failed: types is not an enclosing class
我猜
bitstream.types
在上下文中不是工具箱使用的镜像,但我不知道如何解决这个问题。我认为是相关的,但我不确定如何解释问题页面上的讨论。也许您可以将导入
添加到树中
val tree = toolbox.parse("""
import bitstream.types._
${treeStr}
""")
试一试
i、 e.带包装和不带本
。
(我不知道什么是
d2_old
,如果你能把它放在那里。)不幸的是,我尝试过这个,但似乎没有任何效果。太棒了!这很有魅力。如前所述,d2_old
本身无效,但这是特定于我的程序的单独问题。
Typecheck("_root_.bitstream.types.Bit.bit2Int(d2_old)")