scala - 使用 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()
使用新名称,虽然它返回了一些符号,但在宏扩展期间出现错误,找不到该类。
我的问题是:
- 是否有可能在不显式调用
new Class {}
的情况下派生自定义类型: 引号? - 是否
ClassDef.copy
注册一个可以帮助创建新实例的新名称? - 可以手动调用
ClassDef
创建类的实例吗? Symbol.requiredClass
即使之前没有定义,我如何使用 as 返回的符号?
我创建的代码:
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)
谢谢你的帮助。
解决方案
推荐阅读
- c++ - 顶级声明错误,但程序运行正确
- mongodb - Mongo DB:如何在聚合阶段 $group 后获取原始文档?
- amazon-web-services - 提高 aQuestion 回答、BERT 和 GPT 的性能,在没有 GPU 的情况下进行预测
- php - Laravel:如何按值从多维集合中删除项目
- spring-boot - JPA双向关系父为空
- perl - 防止编译器执行 BEGIN / UNITCHECK / CHECK / INIT 块
- c++ - Rust 中不止一个运算符重载
- python - 了解我的 while 循环中断的原因
- python - MQTT paho 上课时收不到消息
- sublimetext3 - 项目设置中的崇高主题