Dealias在课堂范围内

时间:2014-08-22 16:28:06

标签: scala scala-macros

我编写了一个简单的注释宏来扩展类型同义词并将结果保存在字符串中。它在块中工作正常,但在用于声明类成员时不起作用。为什么呢?

这是编译和运行所必需的all the code

客户代码:

object Client extends App {
  type Synonym = Int

  /** fails to compile due to TypeCheckException: not found: type Synonym
    * should expand to:
    *
    *   val classScope : String = "Int"
    */
  // @dealias val classScope : Synonym = ?

  /** this works */
  val blockScope = {
    @dealias val blockScope : Synonym = ?
    blockScope
  }

  println(s"Inside a block, `Synonym` dealiases to `$blockScope`.")
}

宏实施:

def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
  import c.universe._
  annottees.head.tree match {
    case q"val $lhs : $typeTree = $rhs" =>
      val tpe = c.typecheck(q"{ ??? : $typeTree }").tpe
      val dealiased = tpe.dealias
      c.Expr(q"val $lhs : String = ${dealiased.toString}")
  }
}

1 个答案:

答案 0 :(得分:0)

这适用于SeparatedClient:

c.Expr(q"val $lhs : String = reflect.runtime.universe.typeOf[$typeTree].dealias.toString")

我可以想象在扩展期间封闭类仍然不可用,但是类上的注释可以工作。

这只是一个不使用这些东西的人的猜测。

scala> SeparatedClient.run
Inside a block, `Synonym` dealiases to `scala.Int`.
Inside a member, `Synonym` dealiases to `scala.Int`.