当我尝试向我的案例类添加宏注释时:
@macid case class CC[A: T](val x: A)
我得到错误:
private[this] not allowed for case class parameters
@macid
只是标识函数,定义为白盒 StaticAnnotation:
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context
import scala.annotation.StaticAnnotation
class macid extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro macidMacro.impl
}
object macidMacro {
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
new Macros[c.type](c).macidMacroImpl(annottees.toList)
}
}
class Macros[C <: Context](val c: C) {
import c.universe._
def macidMacroImpl(annottees: List[c.Expr[Any]]): c.Expr[Any] =
annottees(0)
}
未注释的代码有效:
case class CC[A: T](val x: A)
如果我删除上下文绑定,它会起作用:
@macid case class CC[A](val x: A)
发生的事情是将上下文绑定脱糖为私有参数。以下脱糖代码得到相同的错误:
@macid case class CC[A](val x: A)(implicit aIsT: T[A])
为了获得工作代码,我将隐式参数公开val
:
@macid case class CC[A](val x: A)(implicit val aIsT: T[A])
所以我的问题是:宏注释支持上下文边界的正确方法是什么?为什么编译器对宏注释生成的代码执行 no-private-parameters-of-case-classes 检查,但不对普通代码执行检查?
Scala 版本 2.11.7 和 2.12.0-M3 都报告错误。以上所有代码示例在 2.11.3 中都按预期编译和运行。