[英]How do I add a no-arg constructor to a Scala case class with a macro annotation?
[英]How can I apply a macro annotation to a case class with a context bound?
當我嘗試向我的case類添加宏注釋時:
@macid case class CC[A: T](val x: A)
我收到錯誤:
private[this] not allowed for case class parameters
@macid
只是身份函數,定義為whitebox 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)
發生的事情是將上下文綁定到私有參數中。 以下desugared代碼得到相同的錯誤:
@macid case class CC[A](val x: A)(implicit aIsT: T[A])
為了獲得工作代碼,我使用val
使隱式參數為public:
@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中的預期編譯和運行。
好像是一個bug。 這是宏看到的樹:
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>();
()
}
};
前者在evidence$1
時有一個額外的<caseaccessor>
標志,但不應該。 似乎錯誤地給出了這個標志的所有隱含參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.