在Scala宏(2.11 | 2.12)中,我找不到支持在配对对象中声明的类型(case类或case对象)的方法。
以下类型的示例...
sealed trait Foo
object Foo {
case class Bar(lorem: String) extends Foo
case object Ipsum extends Foo
}
...声明为下面的宏......
import language.experimental.macros
import scala.reflect.macros.whitebox.Context
def testImpl[A: c.WeakTypeTag](c: Context): c.Expr[Unit] = {
import c.universe._
val tpe = c.weakTypeOf[A]
c.typecheck(q"""$tpe.unapply(Foo.Bar("lorem"))""")
reify({})
}
def test[A] = macro testImpl[A]
...,当使用Foo.Bar
为类型test[Foo.Bar]
调用它时,会引发编译错误:
error: exception during macro expansion:
scala.reflect.macros.TypecheckException: value unapply is not a member of Foo.Bar
at scala.reflect.macros.contexts.Typers.$anonfun$typecheck$3(Typers.scala:32)
at scala.reflect.macros.contexts.Typers.$anonfun$typecheck$2(Typers.scala:26)
at scala.reflect.macros.contexts.Typers.doTypecheck$1(Typers.scala:25)
at scala.reflect.macros.contexts.Typers.$anonfun$typecheck$7(Typers.scala:38)
at scala.reflect.macros.contexts.Typers$$Lambda$676/541572263.apply(Unknown Source)
at scala.reflect.internal.Trees.wrappingIntoTerm(Trees.scala:1710)
at scala.reflect.internal.Trees.wrappingIntoTerm$(Trees.scala:1707)
at scala.reflect.internal.SymbolTable.wrappingIntoTerm(SymbolTable.scala:16)
at scala.reflect.macros.contexts.Typers.typecheck(Typers.scala:38)
at scala.reflect.macros.contexts.Typers.typecheck$(Typers.scala:20)
at scala.reflect.macros.contexts.Context.typecheck(Context.scala:6)
at scala.reflect.macros.contexts.Context.typecheck(Context.scala:6)
at .testImpl(<pastie>:31)
test[Foo.Bar]
^
直接使用c.typecheck(q"""Foo.Bar.unapply(Foo.Bar("lorem"))""")
进行测试没有错误,所以我猜有更多关于类型解析的事情。