使用Scala2,我可以使用tq准引用语法实现宏和生成类型,例如:
q"""
new Foo {
type Bar = ${tq"(..$params)"}
}
"""我能用这个语法做两件事-
Bar定义类型params。params。如何使用Scala 3实现这一点?
发布于 2022-09-26 12:06:42
Scala 3中没有准引号 (q"..."、tq"..."、pq"..."、cq"..."、fq"...")。
Scala 3 引文 '{...} (和剪接${...})不仅必须在主代码的编译时(即宏的运行时,宏展开的时间),而且必须在宏自身的编译时更早地进行类型检查。这是Scala 2中的相似 to reify {...} (和.splice)。
new Foo {...}实际上是一个扩展Foo的匿名类的实例。看你之前的问题Scala 3中的宏类名展开,用Scala 3宏重写方法
这一切取决于Foo和params是否是静态已知的。如果是这样,那么一切都很容易:
import scala.quoted.*
trait Foo
inline def doSmth[A](x: Int): Unit = ${doSmthImpl[A]('x)}
def doSmthImpl[A](x: Expr[Int])(using Quotes, Type[A]): Expr[Unit]= {
// import quotes.reflect.*
'{
new Foo {
type Bar = (Double, Boolean)
}
// doing smth with this instance
}
}或
val params = Type.of[(Double, Boolean)]
'{
new Foo {
type Bar = $params
}
}或
'{
new Foo {
type Bar = params.Underlying
}
}在评论中,@Jasper建议当我们拥有Foo时,如何静态地处理Foo,而params不是静态的:
type X
given Type[X] = paramsTypeTree.tpe.asType.asInstanceOf[Type[X]]
'{
new Foo {
type Bar = X
}
}或
paramsTypeTree.tpe.asType match {
case '[x] =>
'{
new Foo {
type Bar = x
}
}
} 现在假设Foo不是静态已知的。由于没有拟引号,在Scala 3中构建树的唯一不同方法是深入到美味的反射级别并手动构建树。因此,您可以打印一棵静态排字代码树,并尝试手动重构它。密码
println('{
new Foo {
type Bar = (Double, Boolean)
}
}.asTerm.underlyingArgument.show版画
{
final class $anon() extends App.Foo {
type Bar = scala.Tuple2[scala.Double, scala.Boolean]
}
(new $anon(): App.Foo)
}和
println('{
new Foo {
type Bar = (Double, Boolean)
}
}.asTerm.underlyingArgument.show(using Printer.TreeStructure))版画
Block(
List(ClassDef(
"$anon",
DefDef("<init>", List(TermParamClause(Nil)), Inferred(), None),
List(
Apply(Select(New(Inferred()), "<init>"), Nil),
TypeIdent("Foo")
),
None,
List(TypeDef(
"Bar",
Applied(
Inferred(),
List(TypeIdent("Double"), TypeIdent("Boolean")) // this should be params
)
))
)),
Typed(
Apply(Select(New(TypeIdent("$anon")), "<init>"), Nil),
Inferred()
)
)这里的另一个复杂问题是Scala 3宏接受类型化树,并且必须返回类型化树。所以我们也必须处理符号。
实际上,在反射API i 能看见 Symbol.newMethod、Symbol.newClass、Symbol.newVal、Symbol.newBind中,没有Symbol.newType。(结果是新类型成员的方法没有暴露在反射API中,因此我们必须使用内部 dotty.tools.dotc.core.Symbols.newSymbol。)
我能想象出
val fooTypeTree = TypeTree.ref(Symbol.classSymbol("mypackage.App.Foo"))
val parents = List(TypeTree.of[AnyRef], fooTypeTree)
def decls(cls: Symbol): List[Symbol] = {
given dotty.tools.dotc.core.Contexts.Context =
quotes.asInstanceOf[scala.quoted.runtime.impl.QuotesImpl].ctx
import dotty.tools.dotc.core.Decorators.toTypeName
List(dotty.tools.dotc.core.Symbols.newSymbol(
cls.asInstanceOf[dotty.tools.dotc.core.Symbols.Symbol],
"Bar".toTypeName,
Flags.EmptyFlags/*Override*/.asInstanceOf[dotty.tools.dotc.core.Flags.FlagSet],
TypeRepr.of[(Double, Boolean)]/*params*/.asInstanceOf[dotty.tools.dotc.core.Types.Type]
).asInstanceOf[Symbol])
}
val cls = Symbol.newClass(Symbol.spliceOwner, "FooImpl", parents = parents.map(_.tpe), decls, selfType = None)
val typeSym = cls.declaredType("Bar").head
val typeDef = TypeDef(typeSym)
val clsDef = ClassDef(cls, parents, body = List(typeDef))
val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), fooTypeTree)
Block(List(clsDef, newCls), '{()}.asTerm).asExprOf[Unit]
//{
// class FooImpl extends java.lang.Object with mypackage.App.Foo {
// type Bar = scala.Tuple2[scala.Double, scala.Boolean]
// }
//
// (new FooImpl(): mypackage.App.Foo)
// ()
//}
package mypackage
object App {
trait Foo
}Scala 3宏是def宏,所有生成的定义只能在宏扩展到的块中看到。
也许,如果在预编译时生成代码就足够了,您可以考虑使用斯卡梅塔。q"..."、t"..."、p"..."、param"..."、tparam"..."、init"..."、self"..."、template"..."、mod"..."、enumerator"..."、import"..."、importer"..."、importee"..."、source"..."。
https://stackoverflow.com/questions/73852787
复制相似问题