Martin Kolinek
Martin Kolinek

Reputation: 2010

Find actual type of a method parameter in macro

Suppose I have a macro implementation

def testImpl[T](c:Context)(implicit wtt:c.WeakTypeTag[T]):c.Tree = {
    import c.universe._

    def info(msg: Any) = c.info(c.enclosingPosition, msg.toString, true)

    val parameter = wtt.tpe.member(TermName("f")).paramLists(0)(0)

    info(parameter.typeSignature)

    q"{}"
}

And a macro definition

def test[T]:Unit = macro DerivingImpl.testImpl[T]

This macro finds function f in its type parameter, and prints information about its first parameter's type.

Now if I use this macro like this

trait Trait[A] {
    def f(x:A): Int
}

test[Trait[Int]]

I get A printed. I would like to get Int. I understand that calling member returns the method symbol which does not have information about the concrete applied type. So, what is the correct way to find the actual type of the parameter?

Thank you.

Upvotes: 1

Views: 327

Answers (1)

Eugene Burmako
Eugene Burmako

Reputation: 13048

val f = wtt.tpe.member(TermName("f"))
val MethodType(parameter :: Nil, _) = f.typeSignatureIn(wtt.tpe)
info(parameter.typeSignature)

Upvotes: 5

Related Questions