【问题标题】:Checking equality of types after type checking with scala.tools.reflect.ToolBox使用 scala.tools.reflect.ToolBox 进行类型检查后检查类型的相等性
【发布时间】:2020-03-20 04:47:12
【问题描述】:

我想确定语法树tree1tree2 表示的表达式是否属于同一类型。我尝试使用来自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>

我能否以某种方式检查tree1tree2 是否表示与上次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

【问题讨论】:

  • 什么是tree1tree2st1st2XY
  • @DmytroMitin 用略读的定义更新了我的问题
  • 如果我定义type st2 = { }type st1 = { }tb.typecheck(tree1).tpe =:= tb.typecheck(tree2).tpe实际上返回true

标签: scala reflection types scala-reflect structural-typing


【解决方案1】:

试试

val typ1 = tb.typecheck(tree1).tpe
val typ2 = tb.typecheck(tree2).tpe

tb.typecheck(q"implicitly[$typ1 =:= $typ2]")

或者,也一样,

tb.typecheck(q"_root_.scala.Predef.implicitly[_root_.scala.Predef.=:=[$typ1, $typ2]]")

或者试试

tb.inferImplicitValue(tb.typecheck(tq"$typ1 =:= $typ2", mode = tb.TYPEmode).tpe, silent = false)

或者试试

implicit class TypeOps(tp1: Type) {
  def =::= (tp2: Type): Boolean = tp1 <:< tp2 && tp2 <:< tp1
}

typ1 =::= typ2 // true

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多