I'm trying to get the function name via macros in Scala 3.0.0-M2
The solution that I came up with uses TreeAccumulator
import scala.quoted._
inline def getName[T](inline f: T => Any): String = ${getNameImpl('f)}
def getNameImpl[T](f: Expr[T => Any])(using Quotes): Expr[String] = {
import quotes.reflect._
val acc = new TreeAccumulator[String] {
def foldTree(names: String, tree: Tree)(owner: Symbol): String = tree match {
case Select(_, name) => name
case _ => foldOverTree(names, tree)(owner)
}
}
val fieldName = acc.foldTree(null, Term.of(f))(Symbol.spliceOwner)
Expr(fieldName)
}
When called this code produces the name of the function:
case class B(field1: String)
println(getName[B](_.field1)) // "field1"
I wonder if this can be done in an easier way using quotes.
I guess it's enough to define
def getNameImpl[T: Type](f: Expr[T => Any])(using Quotes): Expr[String] = {
import quotes.reflect._
Expr(TypeTree.of[T].symbol.caseFields.head.name)
}
Actually, I don't use f
.
Testing:
println(getName[B](_.field1)) // "field1"
Tested in 3.0.0-M3-bin-20201211-dbc1186-NIGHTLY.
How to access parameter list of case class in a dotty macro
Alternatively you can try
def getNameImpl[T](f: Expr[T => Any])(using Quotes): Expr[String] = {
import quotes.reflect._
val fieldName = f.asTerm match {
case Inlined(
_,
List(),
Block(
List(DefDef(
_,
List(),
List(List(ValDef(_, _, _))),
_,
Some(Select(Ident(_), fn))
)),
Closure(_, _)
)
) => fn
}
Expr(fieldName)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With