使用Scala 3宏覆盖方法

6ovsh4lw  于 2022-11-09  发布在  Scala
关注(0)|答案(1)|浏览(177)

我正在尝试使用Scala3宏和Tavy来覆盖一个方法。我想重写任何类型的任何方法。现在我从这个简单的案例开始。
我有一个测试基类:

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

我想要实现这一点,但使用Tasty时,我发现不可能使用引号和拼接在泛型类型上调用new A

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

我打印了上面代码的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 }) }
}

返回的代码打印为:

{
@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)
}

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

[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

用途:

val res:TestClass = NewClass.newClass[TestClass](new TestClass)

谢谢你的帮助。

7d7tgy0s

7d7tgy0s1#

使用新方法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]
  }
}

用途:

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

博客文章:在宏中生成任意类实现的可能性
Scaladoc:Symbol.newClass
问题:Support creating a new instance of a given Type[A] with Scala 3 macro
如何访问构造函数:

Scala 2 Append A Method To Class Body (Metaprogramming)(Scala 2,编译器插件)

相关问题