Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala 3 (Dotty) Pattern match a function with a macro quotation

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.

like image 861
Yevhenii Melnyk Avatar asked Dec 07 '20 21:12

Yevhenii Melnyk


Video Answer


1 Answers

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)
}
like image 75
Dmytro Mitin Avatar answered Sep 21 '22 05:09

Dmytro Mitin