2016-02-17 17 views
4

當我嘗試宏註釋添加到我的情況下類:如何將宏註釋應用於具有上下文綁定的案例類?

@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) 
} 

Unannotated code Works:

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]) 

所以我的問題是:什麼是對宏註釋的正確方法支持上下文邊界?爲什麼編譯器對由宏註釋生成的代碼執行非私人蔘數類案例檢查,但不執行普通代碼檢查?

Scala版本2.11.7和2.12.0-M3都報告錯誤。以上所有代碼示例都按照預期在2.11.3中編譯和運行。

回答

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>(); 
    () 
    } 
}; 

前者對evidence$1額外<caseaccessor>標誌時,它不應該。似乎所有隱含的參數都被錯誤地賦予了這個標誌。

+0

看起來像一個bug,但它很混亂,因爲很難判斷'caseaccessor>的真正含義。在我看來,只有構造函數第一個參數列表中的參數應該標記爲,因爲在模式匹配中只有第一個參數列表匹配。隱式參數恰好在第二個參數列表中,所以它不應該是''。 –

+0

@SII_of_SII是的,沒錯。只有案例類的第一個參數列表的參數應該有該標誌。我注意到,如果您在案例類中有第二個參數列表(而不是隱式),也會出現此問題。 –

相關問題