In scala macros, how to get the full `extends` clause for a class?

Considering

trait A[T]
class B[T] extends A[Option[T]]

In the macro, I see that it Ais a supertype Band Ba subtype A, but there is no specificity of how the type parameters match.

How can I get the full information extends A[Option[T]]?

+4
source share
1 answer

I assume that you need this information, given the type, not the tree (which is pretty simple, but less general). The trick is to use baseTypeto get an instance of a type Athat is a supertype of yours B, and then pull out its type parameters, matching TypeRef:

import scala.language.experimental.macros
import scala.reflect.macros.whitebox

def whateverImpl[X: c.WeakTypeTag, Y: c.WeakTypeTag](c: whitebox.Context) = {
  import c.universe._

  val xSymbol = weakTypeOf[X].typeSymbol
  val ySymbol = weakTypeOf[Y].typeSymbol

  ySymbol.typeSignature.baseType(xSymbol) match {
    case TypeRef(_, _, List(arg)) => println(arg)
    case _ => c.abort(c.enclosingPosition, "Types don't work.")
  }

  q"()"
}

def whatever[X, Y]: Unit = macro whateverImpl[X, Y]

trait A[T]
class B[T] extends A[Option[T]]

And then:

scala> whatever[A[_], B[_]]
Option[T]

2.10, whitebox.

+6

All Articles