Get fully qualified method name in scala macros

884 Views Asked by At

I use Scala macros and match Apply and I would like to get fully qualified name of the function which is called.

Examples:

println("") -> scala.Predef.println
scala.Predef.println("") -> scala.Predef.println
class Abc {
  def met(): Unit = ???
}
case class X { 
  def met(): Unit = ???
  def abc(): Abc = ???
}
val a = new Abc()
val x = new Abc()
a.met() -> Abc.met
new Abc().met() -> Abc.met
X() -> X.apply
X().met() -> X.met
x.met() -> X.met
x.abc.met() -> Abc.met

On the left side is what I have in code and on the right side after arrow is what I want to get. Is it possible? And how?

1

There are 1 best solutions below

1
On BEST ANSWER

Here is the macro:

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

object ExampleMacro {

  final val useFullyQualifiedName = false

  def methodName(param: Any): String = macro debugParameters_Impl

  def debugParameters_Impl(c: blackbox.Context)(param: c.Expr[Any]): c.Expr[String] = {
    import c.universe._

    param.tree match {
      case Apply(Select(t, TermName(methodName)), _) =>
        val baseClass = t.tpe.resultType.baseClasses.head // there may be a better way than this line
        val className = if (useFullyQualifiedName) baseClass.fullName else baseClass.name
        c.Expr[String](Literal(Constant(className + "." + methodName)))
      case _ => sys.error("Not a method call: " + show(param.tree))
    }
  }
}

Usage of the macro:

object Main {

  def main(args: Array[String]): Unit = {

    class Abc {
      def met(): Unit = ???
    }
    case class X() {
      def met(): Unit = ???

      def abc(): Abc = ???
    }
    val a = new Abc()
    val x = X()

    import sk.ygor.stackoverflow.q53326545.macros.ExampleMacro.methodName

    println(methodName(Main.main(Array("foo", "bar"))))
    println(methodName(a.met()))
    println(methodName(new Abc().met()))
    println(methodName(X()))
    println(methodName(X().met()))
    println(methodName(x.met()))
    println(methodName(x.abc().met()))
    println(methodName("a".getClass))
  }

}

Source code for this example contains following:

  • it is a multi module SBT project, because macros have to be in a separate compilation unit than classes, which use the macro
  • macro modules depends explicitly on libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value,