scala – 如何将宏注释应用于具有上下文绑定的案例类?
发布时间:2020-12-16 18:34:31 所属栏目:安全 来源:网络整理
导读:当我尝试向我的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.macrosimport s
当我尝试向我的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>(); () } }; 前者有一个额外的< caseaccessor>在不应该的情况下,在证据上标记1美元.似乎错误地给出了这个标志的所有隐含参数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |