首页 > 解决方案 > 使用 Scala 3 宏覆盖方法

问题描述

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

我有一个测试基类:

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

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

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

我打印了上述代码的 AST,我几乎设法重新创建它。问题是我无法调用new生成的类 - 我看不到访问新类的符号或类型的方法。我也尝试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)

谢谢你的帮助。

标签: scalascala-macrosscala-3

解决方案


推荐阅读