El patrón Scala 3 (Dotty) hace coincidir una función con una cita macro
Dec 08 2020
Estoy tratando de obtener el nombre de la función a través de macros en Scala 3.0.0-M2 La solución que se me ocurrió usa 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)
}
Cuando se llama, este código produce el nombre de la función:
case class B(field1: String)
println(getName[B](_.field1)) // "field1"
Me pregunto si esto se puede hacer de una manera más fácil usando comillas.
Respuestas
2 DmytroMitin Dec 13 2020 at 14:44
Supongo que es suficiente para definir
def getNameImpl[T: Type](f: Expr[T => Any])(using Quotes): Expr[String] = {
import quotes.reflect._
Expr(TypeTree.of[T].symbol.caseFields.head.name)
}
En realidad, no uso f
.
Pruebas:
println(getName[B](_.field1)) // "field1"
Probado en 3.0.0-M3-bin-20201211-dbc1186-NIGHTLY.
Cómo acceder a la lista de parámetros de la clase de caso en una macro chiflada
Alternativamente puedes probar
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)
}