0

Say I have a macro annotation AnnProxy and the following code:

trait MyTrait
{
  def x: Int
}

@AnnProxy
class MyClass extends MyTrait

I now need to get the Type of MyTrait so that I can proxy it's methods. So far my code looks like:

@compileTimeOnly("enable macro paradise to expand macro annotations")
class AnnProxy extends StaticAnnotation
{
    def macroTransform(annottees: Any*): Any = macro IdentityMacro.impl
}

object IdentityMacro
{
  def impl(c: whitebox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._

    val inputs = annottees.map(_.tree).toList

    val classDef = inputs.head.asInstanceOf[ClassDef]
    val superclass= // how do I get the Type of the superclass?

    c.Expr[Any] {
        q"""
      class ${classDef.name} {
        def doit() : Unit = println("doit")
      }
  """
    }
}
}
kostas.kougios
  • 945
  • 10
  • 21

1 Answers1

1

you can use pattern matching

class SuperClass extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro SuperClassImpl.apply

}

class SuperClassImpl(val c: Context) {

  def showInfo(s: String) =
    c.info(c.enclosingPosition, s.split("\n").mkString("\n |---macro info---\n |", "\n |", ""), true)

  import c.universe._

  def apply(annottees: c.Expr[Any]*) = {

    val superClass = annottees.map(_.tree).head match {
      case q"$mod class $name(..$params) extends ..$superClass { ..$body }" =>
        superClass
    }

    showInfo(show(superClass))
    q"{..$annottees}"
  }
}

test

trait AA
trait BB
trait CC
@SuperClass
class SuperClassUsing extends AA with BB with CC //when show info List(AA,BB,CC)
余杰水
  • 1,404
  • 1
  • 11
  • 14
  • Hi, the problem is that superClass.map(_.tpe) is a list of nulls. I think it has something to do with the macro's running at a point when types are not checked but how do I get the tpe so that I can get a list of tpe's methods? – kostas.kougios Dec 01 '15 at 12:45
  • 1
    this can get super class Symbol `c.typecheck(annottees.map(_.tree).head).symbol.asClass.baseClasses.tail` – 余杰水 Dec 01 '15 at 12:53
  • I've a followup question here : http://stackoverflow.com/questions/34023763/annotation-macro-that-rewrites-and-impls-a-trait-generics-not-processed-correct , any help would be appreciated, thanks – kostas.kougios Dec 01 '15 at 15:18