5

当我尝试向我的案例类添加宏注释时:

@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 中都按预期编译和运行。

4

1 回答 1

2

似乎是一个错误。这是宏看到的树:

case class CC[A] extends scala.Product with scala.Serializable {
  <caseaccessor> <paramaccessor> val x: A = _;
  implicit <synthetic> <caseaccessor> <paramaccessor> private[this] val evidence$1: T[A] = _;
  def <init>(x: A)(implicit evidence$1: T[A]) = {
    super.<init>();
    ()
  }
}

并通过运行时反射 API:

case class CC[A] extends Product with Serializable {
  <caseaccessor> <paramaccessor> val x: A = _;
  implicit <synthetic> <paramaccessor> private[this] val evidence$1: $read.T[A] = _;
  def <init>(x: A)(implicit evidence$1: $read.T[A]) = {
    super.<init>();
    ()
  }
};

前者有一个额外的<caseaccessor>标志,evidence$1什么时候不应该。似乎案例类的所有隐式参数都被错误地赋予了这个标志。

于 2016-02-18T03:32:15.807 回答