微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Scala 3 宏特征参数

如何解决Scala 3 宏特征参数

这是基本设置:

trait MyProduct[A,B](a: A,b:  B)
class X
class Y

class XxY(x: X,y: Y) extends MyProduct(x,y)

我正在尝试检查 MyProduct 特征的参数。更具体地说,我想提取一些信息,例如字符串“x”和“y”,它们指示 XxY 的哪些字段被传递给 MyProduct

重要的是,我需要满足多个相同类型字段的情况,例如 class XxYxY(x: X,y1: Y,y2: Y) extends MyProduct3(x,y1,y2),因此仅凭类型参数进行推理是不够的。

我想问题可能在于我还没有找到一种方法获取 extends 子句本身的符号。我可以找到 ClassDefXxY,从中我可以提取 parents 并获得已经构造的类型 MyProduct[X,Y]。我还查看了封闭模块的 symbol.declarationsXxY.<init> 函数,以查看是否有可用于查找参数的数据,但这些似乎都没有我所了解的信息正在寻找。

查看封闭模块的树让我觉得这些信息可能被删除了,而是需要从源代码中解析为文本,但我希望有人有更好的解决方案。

评论中编辑:

作为输入,我有一个封闭对象/模块的 Type 实例。例如:

inline def simpleProductTest[T <: Singleton]: String = ${simpleProductTestImpl[T]}

def simpleProductTestImpl[T](using q: Quotes)(using Type[T]): Expr[String] = ???

作为输出,我想要一些允许我检查 extends 子句中使用的特征的参数的东西。

解决方法

如果你这样做

import scala.quoted.*

object Macros {
  inline def simpleProductTest[T]: Unit = ${simpleProductTestImpl[T]}

  def simpleProductTestImpl[T](using Quotes)(using Type[T]): Expr[Unit] = {
    import quotes.reflect.*
    println(TypeRepr.of[T].typeSymbol.tree.asInstanceOf[TypeDef].rhs)
    '{()}
  }
}

你会看到

object App {
  trait MyProduct[A,B](a: A,b:  B)
  class X
  class Y

  class XxY(x: X,y: Y,z: Int) extends MyProduct(x,y)

  Macros.simpleProductTest[XxY]
}

没有关于x,y的信息

Template(
  DefDef(
    <init>,List(List(
      ValDef(x,TypeTree[TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,module class <empty>)),module class App$)),class X)],EmptyTree),ValDef(y,class Y)],ValDef(z,TypeTree[TypeRef(TermRef(ThisType(TypeRef(NoPrefix,module class <root>)),object scala),class Int)],EmptyTree)
    )),class XxY)],EmptyTree
  ),List(
    TypeTree[TypeRef(ThisType(TypeRef(NoPrefix,module class lang)),class Object)],TypeTree[AppliedType(TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,trait MyProduct),List(
        TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,class X),TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,class Y)
      )
    )]
  ),ValDef(_,EmptyTree,List(
    ValDef(x,EmptyTree)
  )
)

Template 中不存在 scala.quoted.*,它是 dotty.tools.dotc.ast.Trees.Template

但是如果你用 TASTy inspection 打印 .tasty 文件

libraryDependencies += "org.scala-lang" %% "scala3-tasty-inspector" % "3.0.0"

import scala.quoted.*
import scala.tasty.inspector.*

class MyInspector extends Inspector:
  def inspect(using Quotes)(tastys: List[Tasty[quotes.type]]): Unit =
    import quotes.reflect.*
    for tasty <- tastys do
      val tree = tasty.ast
      println(tree)

@main def test: Unit =
  val tastyFiles = List("target/scala-3.0.0/classes/App.tasty")
  TastyInspector.inspectTastyFiles(tastyFiles)(new MyInspector)

你会看到

Template(
  DefDef(
    <init>,Ident(X),Ident(Y),Ident(Int),Unit)],List(
    Apply(Select(New(TypeTree[TypeRef(TermRef(ThisType(TypeRef(NoPrefix,module class java)),object lang),Object)]),<init>),List()),Apply(
      TypeApply(
        Select(New(Ident(MyProduct)),List(
          TypeTree[TypeRef(ThisType(TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,TypeTree[TypeRef(ThisType(TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,class Y)]
        )
      ),List(Ident(x),Ident(y))  <--- HERE!!!
    )
  ),Int)],EmptyTree)
  )
)

树略有不同,有关 x,y 的信息在那里。

在扩展方法 .tree of Symbol 的 Scaladoc 中是这样写的

     *  **Warning**: avoid using this method in macros.
     *
     *  **Caveat**: The tree is not guaranteed to exist unless the compiler
     *  option `-Yretain-trees` is enabled.

让我们打开-Yretain-trees

scalacOptions += "-Yretain-trees"

然后 Macros.simpleProductTest[XxY] 打印

Template(
  DefDef(
    <init>,TypeTree[TypeRef(ThisType(TypeRef(NoPrefix,module class scala)),class Unit)],List(
    Apply(Select(New(TypeTree[TypeRef(ThisType(TypeRef(NoPrefix,class Object)]),List(
          TypeTree[TypeVar(TypeParamRef(A) -> TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,class X))],TypeTree[TypeVar(TypeParamRef(B) -> TypeRef(ThisType(TypeRef(ThisType(TypeRef(NoPrefix,class Y))]
        )
      ),Ident(y))   <----  AGAIN HERE !!!!
    )
  ),EmptyTree)
  )
)

即树再次略有不同,但出现了有关 x,y 的信息。所以现在的问题只是如何提取这些信息,因为它是 dotty.tools.dotc.ast.*

case class Template[-T >: Untyped] private[ast](
  constr: DefDef[T],parentsOrDerived: List[Tree[T]],self: ValDef[T],private var preBody: LazyTreeList[T @uncheckedVariance]
)(implicit @constructorOnly src: SourceFile)

最后

libraryDependencies += "org.scala-lang" %% "scala3-compiler" % "3.0.0"

import scala.quoted.*

inline def simpleProductTest[T]: List[String] = ${simpleProductTestImpl[T]}

def simpleProductTestImpl[T](using Quotes)(using Type[T]): Expr[List[String]] = {
  import quotes.reflect.*
  Expr(
    TypeRepr.of[T].typeSymbol.tree.asInstanceOf[TypeDef].rhs
      .asInstanceOf[dotty.tools.dotc.ast.Trees.Template[?]]
      .parentsOrDerived
      .asInstanceOf[List[Apply]]
      .tail.head.args.map(_.symbol.name)
  )
}

Macros.simpleProductTest[XxY] // List(x,y)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。