【发布时间】:2020-03-20 04:47:12
【问题描述】:
我想确定语法树tree1 和tree2 表示的表达式是否属于同一类型。我尝试使用来自scala.tools.reflect.ToolBox 的类型检查方法这样做,但它似乎与实际的 Scala 类型不一致。
我在这里创建工具箱:
scala> val tb = runtimeMirror(getClass.getClassLoader).mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type]
= scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@1ad29bfd
它报告类型不等式:
scala> tb.typecheck(tree1).tpe =:= tb.typecheck(tree2).tpe
res81: Boolean = false
我要求类型的表示:
scala> tb.typecheck(tree1).tpe
res82: tb.u.Type = st1 with st2{val x: X; val y: Y}
scala> tb.typecheck(tree2).tpe
res83: tb.u.Type = scala.AnyRef{val x: X; val y: Y}
现在这些类型成功统一了:
scala> implicitly[st1 with st2{val x: X; val y: Y} =:= scala.AnyRef{val x: X; val y: Y}]
res84: =:=[st1 with st2{val x: X; val y: Y},AnyRef{val x: X; val y: Y}] = <function1>
我能否以某种方式检查tree1 和tree2 是否表示与上次sn-p 中类似类型的表达式?
编辑:最小定义
trait X
trait Y
type st1 = { val x: X }
type st2 = { val y: Y }
val s1: st1 = new { val x: X = new X {} }
val s2: st2 = new { val y: Y = new Y {} }
def foo(s1: st1, s2: st2): st1 with st2 { val x: X; val y: Y } = ???
val pure = new { val x: X = new X {}; val y: Y = new Y {}}
val tree1 = reify { foo(s1, s2) }.tree
val tree2 = reify { pure }.tree
【问题讨论】:
-
什么是
tree1、tree2、st1、st2、X、Y? -
@DmytroMitin 用略读的定义更新了我的问题
-
如果我定义
type st2 = { }和type st1 = { },tb.typecheck(tree1).tpe =:= tb.typecheck(tree2).tpe实际上返回true。
标签: scala reflection types scala-reflect structural-typing