scala - Scala 宏注释错误的解决方法
问题描述
我有一个宏注释,用于将隐式类型类注入伴随方法。
@MyMacro case class MyClass[T](a: String, b: Int, t: T)
大多数时候它按预期工作,但是当我使用类型约束表示法时它会中断:
@MyMacro case class MyClass[T: TypeClass](a: String, b: Int, t: T)
// private[this] not allowed for case class parameters
此错误在 SO 上进行了描述并报告为错误。
事情是:不再维护宏(v1),所以我不能指望这会得到修复。
所以我想知道的是:我可以在宏中自己解决这个问题吗?这种对 AST 的更改是否以某种我可以撤消的方式进行?我想尝试在宏中修复它,而不是强制所有用户将他们的代码重写为...(implicit tc: TypeClass[T])
.
解决方案
class AnnotationType() extends scala.annotation.StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro AnnotationTypeImpl.impl
}
class AnnotationTypeImpl(val c: blackbox.Context) {
import c.universe._
def impl(annottees: Tree*): Tree = {
val tree = annottees.head.asInstanceOf[ClassDef]
val newTree = tree match {
case ClassDef(mods, name, tparams, impl@Template(parents, self, body)) =>
val newBody = body.map {
case ValDef(mods, name, tpt, rhs) =>
// look here
// the flag of `private[this]` is Flag.PRIVATE | Flag.LOCAL
// the flag of `private` is Flag.PRIVATE
// drop Flag.LOCAL in Modifiers.flags , it will change `private[this]` to `private`
val newMods =
if(mods.hasFlag(Flag.IMPLICIT))
mods.asInstanceOf[scala.reflect.internal.Trees#Modifiers].&~(Flag.LOCAL.asInstanceOf[Long]).&~(Flag.CASEACCESSOR.asInstanceOf[Long]).asInstanceOf[Modifiers]
else
mods
ValDef(newMods, name, tpt, rhs)
case e => e
}
ClassDef(mods, name, tparams, Template(parents, self, newBody))
}
println(show(tree))
println(show(newTree))
q"..${newTree +: annottees.tail}"
}
}
// 测试
@AnnotationType()
case class AnnotationTypeTest[T: Option](a: T){
def option = implicitly[Option[T]]
}
object AnnotationTypeTest {
def main(args: Array[String]): Unit = {
implicit val x = Option(1)
println(AnnotationTypeTest(100))
println(AnnotationTypeTest(100).option)
println(AnnotationTypeTest(100).copy(a =2222))
println(AnnotationTypeTest(100).copy(a =2222)(Some(999)).option)
}
}
推荐阅读
- javascript - 通过按钮数组使事件监听器循环
- java - 将参数传递给自定义视图android
- r - 计算AME、MEM、MER的最简单方法?
- jquery - WP上jquery datepicker中的日期格式
- php - 为什么会打印
什么时候做这个 Laravel?
- python - 我可以在没有 GPU 的机器上使用 PyTorch 或 Tensorflow 项目吗?
- typescript - 推断对象键的特定类型的值
- google-apps-script - 使用谷歌脚本通过电子邮件发送范围
- python - 对于python中的SQL循环日期变量
- parameters - 如何在 Tableau 的 4 个象限中的每个象限中显示文本(带有记录数)?