8

我正在尝试通过 Scala 3.0.0-M2 中的宏获取函数名称我想出的解决方案使用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)
}

调用此代码时,会生成函数的名称:

case class B(field1: String)
println(getName[B](_.field1)) // "field1"

我想知道这是否可以使用引号以更简单的方式完成。

4

1 回答 1

2

我想这足以定义

def getNameImpl[T: Type](f: Expr[T => Any])(using Quotes): Expr[String] = {
  import quotes.reflect._
  Expr(TypeTree.of[T].symbol.caseFields.head.name)
}

实际上,我不使用f.

测试:

println(getName[B](_.field1)) // "field1"

在 3.0.0-M3-bin-20201211-dbc1186-NIGHTLY 中测试。

如何在dotty宏中访问案例类的参数列表

或者你可以试试

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)
}
于 2020-12-13T07:44:19.980 回答