How to apply macro annotation to case class with context binding?

When I try to add macro annotation to my case class:

@macid case class CC[A: T](val x: A)

I get an error message:

private[this] not allowed for case class parameters

@macid is just an identity function defined as a white box of 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)
}

Human code works:

case class CC[A: T](val x: A)

It works if I remove the context binding:

@macid case class CC[A](val x: A)

What happens is due to a context constraint in the private parameter. The following code snippet gets the same error:

@macid case class CC[A](val x: A)(implicit aIsT: T[A])

To get the working code, I make the implicit parameter publicly available with val:

@macid case class CC[A](val x: A)(implicit val aIsT: T[A])

So my questions are: What is the right way to annotate a macro to maintain context boundaries? Why does the compiler check non-private-parameters-of-case-classes of code generated by the macro, but fail to check regular code?

Scala 2.11.7 2.12.0-M3 . , , 2.11.3.

+4
1

. , :

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, . , case .

+2

Source: https://habr.com/ru/post/1629261/


All Articles