使用 Scala 3 宏重写方法

ple*_*and 5 scala scala-macros scala-3

我正在尝试使用 Scala 3 宏和 TASTY 重写方法。我想重写任何类型的任何方法。现在我从这个简单的案例开始。

我有一个测试基类:

class TestClass {
  def func(s: String) = "base"
}
Run Code Online (Sandbox Code Playgroud)

我想实现这一点,但是通过使用 TASTY,我发现不可能调用new A带有引号和拼接的泛型类型:

'{
    new TestClass() {
       override def func(s: String) = "override"
    }
}.asExprOf[A]
Run Code Online (Sandbox Code Playgroud)

我打印了上述代码的 AST,并且几乎成功地重新创建了它。问题是我无法调用new生成的类 - 我没有找到访问新类的符号或类型的方法。我也尝试Symbol.requiredClass()使用新名称,尽管它返回了一些符号,但在宏扩展期间出现错误,未找到该类。

我的问题是:

  • 是否可以在不显式调用:的new Class {}情况下派生自定义类型?
  • 是否ClassDef.copy注册一个可以帮助创建新实例的新名称?
  • 可以手动调用ClassDef创建类的实例吗?
  • Symbol.requiredClass即使之前没有定义,如何使用返回的符号,因为它会返回某些内容?

我创建的代码:

import scala.quoted.*

object NewClass {

  def newClassImpl[A: Type](e: Expr[A])(using Quotes): Expr[A] = {
    import quotes.reflect.*

    val typeRep = TypeRepr.of[A]

    val ret = typeRep.classSymbol.map(_.tree) match {
      case Some(
            cd @ ClassDef(
              name: String,
              constr: DefDef,
              parents: List[Tree],
              selfOpt: Option[ValDef],
              body: List[Statement]
            )
          ) =>
        println(cd.show(using Printer.TreeAnsiCode))

        val newItemsOwner = Symbol.spliceOwner.owner
        println("newItemsOwner = " + newItemsOwner)

        def createFunction(args: Term)(using Quotes): Term = {
          args
        }

        val newConstrSymbol = Symbol.newMethod(
          newItemsOwner,
          "<init>",
          MethodType(Nil)(
            _ => Nil,
            _ => TypeRepr.of[Unit]
          ),
          Flags.EmptyFlags,
          Symbol.noSymbol
        )

        val newConstrDef: DefDef = DefDef(
          newConstrSymbol,
          {
            case List(List(paramTerm: Term)) =>
              Some(createFunction(paramTerm).changeOwner(newConstrSymbol))
            case _ => None
          }
        )

        val newMethodSymbol = Symbol.newMethod(
          newItemsOwner,
          "func",
          MethodType(List("s"))(
            _ => List(TypeRepr.of[String]),
            _ => TypeRepr.of[String]
          ),
          Flags.Override,
          Symbol.noSymbol
        )

        val newMethodDef: DefDef = DefDef(
          newMethodSymbol,
          {
            case List(List(paramTerm: Term)) =>
              Some(createFunction(paramTerm).changeOwner(newMethodSymbol))
            case _ => None
          }
        )

        val parentSel = Select.unique(New(TypeTree.of[A]), "<init>")
        val parent = Apply(parentSel, Nil)

        val newClassDef: ClassDef = ClassDef.copy(cd)(
          name + "$gen",
          newConstrDef,
          parent :: Nil,
          None,
          newMethodDef :: Nil
        )

        val app = Apply(
          Select(New(TypeIdent(Symbol.requiredClass(name + "$gen"))), newConstrDef.symbol),
          Nil
        )
      
        val block = Block(newClassDef :: Nil, Typed(app, TypeTree.of[A]))
        val finalTerm = Inlined(Some(TypeTree.of[NewClass$]), Nil, block)

        println(finalTerm.show(using Printer.TreeAnsiCode))
        println(finalTerm.show(using Printer.TreeStructure))

        finalTerm.asExprOf[A]


      case other =>
        println("No class def found: " + other)
        e
    }

    println("Returned:")
    println(ret.asTerm.show(using Printer.TreeAnsiCode))
    println(ret.asTerm.show(using Printer.TreeStructure))

    ret
  }

  inline def newClass[A](a: A): A = ${ newClassImpl[A]('{ a }) }
}
Run Code Online (Sandbox Code Playgroud)

返回的代码毫无怨言地打印为:

{
@scala.annotation.internal.SourceFile("src/main/scala/MethodsMain.scala") class TestClass$gen() extends TestClass {
    override def func(s: java.lang.String): java.lang.String = s
  }

  (new TestClass$gen(): TestClass)
}
Run Code Online (Sandbox Code Playgroud)

但如果由宏返回,我在扩展过程中会收到错误:

[error]   |Bad symbolic reference. A signature
[error]   |refers to TestClass$gen/T in package <empty> which is not available.
[error]   |It may be completely missing from the current classpath, or the version on
[error]   |the classpath might be incompatible with the version used when compiling the signature.
[error]   | This location contains code that was inlined from NewClass.scala:86
Run Code Online (Sandbox Code Playgroud)

用法:

val res:TestClass = NewClass.newClass[TestClass](new TestClass)
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。

Dmy*_*tin 3

使用新方法Symbol.newClass(Scala 3.1.3),这变得非常简单:

import scala.annotation.experimental
import scala.quoted.*

object NewClass {
  inline def newClass[A]: A = ${newClassImpl[A]}

  @experimental
  def newClassImpl[A: Type](using Quotes): Expr[A] = {
    import quotes.reflect.*

    val name: String = TypeRepr.of[A].typeSymbol.name + "Impl"
    val parents = List(TypeTree.of[A])

    def decls(cls: Symbol): List[Symbol] =
      List(Symbol.newMethod(cls, "func", MethodType(List("s"))(_ => List(TypeRepr.of[String]), _ => TypeRepr.of[String]), Flags.Override, Symbol.noSymbol))

    val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = parents.map(_.tpe), decls, selfType = None)
    val funcSym = cls.declaredMethod("func").head

    val funcDef = DefDef(funcSym, argss => Some('{"override"}.asTerm))
    val clsDef = ClassDef(cls, parents, body = List(funcDef))
    val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[A])

    Block(List(clsDef), newCls).asExprOf[A]
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

class TestClass {
  def func(s: String) = "base"
}

val res: TestClass = NewClass.newClass[TestClass]

//{
//  class TestClassImpl extends TestClass {
//    override def func(s: java.lang.String): java.lang.String = "override"
//  }
//
//  (new TestClassImpl(): TestClass)
//}

res.func("xxx") // override
Run Code Online (Sandbox Code Playgroud)

博客文章:在宏中生成任意类实现的可能性

Scaladoc:Symbol.newClass

问题:支持使用 Scala 3 宏创建给定 Type[A] 的新实例

如何访问构造函数:

Scala 2 将方法附加到类主体(元编程)(Scala 2,编译器插件)