首页 > 解决方案 > 为方法的参数范围提取 ClassSymbols

问题描述

我正在尝试为ClassSymbol方法的所有类型参数的边界提取 s。

我想出的“解决方案”:

宏注解实现:

@compileTimeOnly("Compile-time only annotation")
class classSyms extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro impl
}

object classSyms {
  def impl(c: whitebox.Context)(annottees: c.Tree*) = {
    import c.universe._
    annottees.toList foreach {
      case q"$mods def $templatename[..$typeparams](...$paramss): $tpt = $body" =>
        typeparams foreach {
          case q"$mods type $name[..$tparams] >: $low <: $high" =>
            if (!high.isEmpty) {
              //requires FQCN, does not work with imported names
              val classSymbol = c.mirror.staticClass(high.toString)
              println(classSymbol)
            }
        }
    }
    q"..$annottees"
  }
}

示例

package pack.age

trait Test

package another.pack.age

import pack.age._

trait Bar{
  @classSyms
  def foo[M <: pack.age.Test, T](): Unit //works ok


  @classSyms
  def baz[M <: Test, T](): Unit //throws scala.ScalaReflectionException: class Test not found.
}

问题在于,将完全限定的类名指定为参数绑定的要求并没有使这个宏实现非常有用(没有人想写这么长的 fqcn 东西,尤其是在名称被导入的情况下)。

ClassSymbol是否可以通过导入的名称提取?

标签: scalametaprogrammingscala-macros

解决方案


尝试使用c.typecheck.

代替

val classSymbol = c.mirror.staticClass(high.toString)

val classSymbol = c.typecheck(tq"$high", mode = c.TYPEmode).symbol.asClass

推荐阅读