2017-10-09 51 views
1

我有一個宏註釋{類型T}:如何檢查是否F [T] <:G [T] FORALL在宏

import language.experimental.macros 
import reflect.macros.whitebox.Context 

class annot extends StaticAnnotation { 
    def macroTransform(annottees: Any*): Any = macro annot.impl 
} 
object annot { 
    def impl(c: Context)(annottees: c.Tree*): c.Tree = ... 
} 

我希望它被使用如下:

@annot case class A[B1, B2, ...](c: C) extends D1 with D2 with ... 

,但只應工作,如果(C <: D1 with D2 with ...) forAll { type B1; type B2; ... }

@annot case class OK1(i: Int) extends Any 
@annot case class NO1(s: String) extends AnyVal 
@annot case class OK2[A <: Other1, B[_]](bas: Other2[B[A]]) 
    extends (Other2[B[T]] forSome { type T <: Other1 }) 
type ConstLInt[A] = List[Int] 
@annot case class NO2[T](ts: List[T]) extends ConstLInt[T] // Only works if T = Int 

我能得到一半了,因爲如果D1, D2, ...不依賴於B1, B2, ...,那麼我的條件相當於(C forSome { type B1; type B2; ... }) <: D1 with D2 with ...,我可以檢查作爲

val fieldTypeE = c.typecheck(ExistentialTypeTree(fieldType, tparams), c.TYPEmode).tpe 
parents.forall(fieldTypeE <:< _) 

這是足以讓

@annot case class D[E[A] <: Seq[A]](ei: E[Int]) extends Seq[Int] 

但不足以讓

@annot case class D[E, C <: E](c: C) extends E // extends clause references E 

我如何推廣?

回答

0

這裏有一個簡單的解決方案:

val implicitly = q"_root_.scala.Predef.implicitly" 
val <:< = tq"_root_.scala.Predef.<:<" 
val checks = parents.map { parent => 
    q"$implicitly[${<:<}[$fieldType, $parent]]" 
} 
// checks = Seq(q"implicitly[C <:< D1]", q"implicitly[C <:< D2]", ...) 
val checker = q"trait ${TypeName(c.freshName())} { ..$tparams; ..$checks }" 
// trait <syn> { 
// type B1 
// type B2 // Bring them into scope as abstract types (the forall part) 
// .. 
// implicitly[C <:< D1] 
// implicitly[C <:< D2] // Do checks against them, knowing only their constraints 
// .. 
// } 
c.typecheck(checker) 
相關問題