Scala隐式宏:按子类型

时间:2016-10-12 11:03:08

标签: scala macros

我们说我有一个简单的impicit宏给了我一个weakTypeSymbol

@macrocompat.bundle
class ExampleMacro(val c: blackbox.Context) {
  def macroImpl[T : WeakTypeTag]: Tree = {
    val tpe = weakTypeOf[T]
    val subType = typeOf[SomeType].typeSymbol
    val target = tpe.decls.collect {
      case tp if tp.typeSignature.typeSymbol == subType => tp
    } 
    ...
  }
}

这是一个非常基本的版本,简而言之,我需要T的内部成员来满足特定的子类型关系。看起来内部成员上的类型目前尚未评估,因为tp.typeSignature.typeSymbol<none>

有没有一种已知的正确方法?

1 个答案:

答案 0 :(得分:0)

这适用于类似于反射的API:

    class TestMacro(val c: blackbox.Context) {
      import c.universe._
      def filterMembers[
        T : WeakTypeTag,
        Filter : TypeTag
      ]: List[Symbol] = {
        val tpe = weakTypeOf[T].typeSymbol.typeSignature

        (for {
          baseClass <- tpe.baseClasses.reverse
          symbol <- baseClass.typeSignature.members.sorted
          if symbol.typeSignature <:< typeOf[Filter]
        } yield symbol)(collection.breakOut)
      }
    }