[英]Scala macro annotation - case class with type parameters
我正在尝试为case类编写一个简单的宏注释,该注释将方法添加到伴随对象。 问题是新方法必须考虑带注释的案例类的类型参数。
这是我需要通过的测试
package my.macros
import org.scalatest._
class DefaultApplyTest extends FlatSpec with Matchers {
@defaultApply case class Generic[A, B](a: A, b: B)
it should "define defaultApply method in companion object" in {
assert(Generic.defaultApply("str", 1) == Generic("str", 1))
}
}
这是我为此编写的代码
package my.macros
import scala.reflect.macros._
import scala.language.experimental.macros
import scala.annotation.StaticAnnotation
class defaultApply extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro DefaultApply.impl
}
object DefaultApply {
def impl(c: blackbox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
def defaultApplyCompanion(classDecl: ClassDef) = {
val (name, typeParams, valueParams) = try {
val q"case class ${name: TypeName}[..${typeParams: Seq[TypeDef]}](..${valueParams: Seq[ValDef]}) extends ..$bases { ..$body }" = classDecl
(name, typeParams, valueParams)
} catch {
case e: MatchError =>
c.warning(c.enclosingPosition, e.toString)
c.abort(c.enclosingPosition, "Annotation is only supported on case class")
}
val applyDef = q"""${name.toTermName}.apply[..$typeParams]"""
c.warning(c.enclosingPosition, showRaw(applyDef))
q"""
object ${name.toTermName} {
def defaultApply: (..${valueParams.map(_.tpt)}) => $name[..$typeParams] = $applyDef
}
"""
}
def modifiedDeclaration(classDecl: ClassDef) = {
val compDecl = defaultApplyCompanion(classDecl)
c.Expr(q"""
$classDecl
$compDecl
""")
}
annottees.map(_.tree) match {
case (classDecl: ClassDef) :: Nil => modifiedDeclaration(classDecl)
case _ => c.abort(c.enclosingPosition, "Invalid annottee")
}
}
}
据我了解,问题是当我尝试将类型参数列表提升到结果语法树中时,它们与原始树的类型参数未被识别为相同类型。
所以我专注于宏的这一部分
val applyDef = q"""${name.toTermName}.apply[..$typeParams]"""
c.warning(c.enclosingPosition, showRaw(applyDef))
原始语法树被发出为
TypeApply(Select(Ident(TermName("Generic")), TermName("apply")), List(TypeDef(Modifiers(PARAM), TypeName("A"), List(), TypeBoundsTree(EmptyTree, EmptyTree)), TypeDef(Modifiers(PARAM), TypeName("B"), List(), TypeBoundsTree(EmptyTree, EmptyTree))))
但是编译器对此不满意
type arguments [<notype>,<notype>] do not conform to method apply's type parameter bounds [A,B]
最终用例是生成可缓存类型类的实例,该实例涉及1k行代码。 非参数版本已经可以使用,这只是锦上添花。 scalac的内部有些东西我不理解,但我想知道。 非常感谢您花时间阅读本文。
我正在使用Scala 2.11.8和宏天堂2.1.0
问题似乎是您在使用类型参数代替类型参数。 这似乎可行(我还必须将类型参数添加到defaultApply
方法声明中):
val typeArgs = typeParams.map(_.name)
val applyDef = q"""${name.toTermName}.apply[..$typeArgs]"""
c.warning(c.enclosingPosition, showRaw(applyDef))
q"""
object ${name.toTermName} {
def defaultApply[..$typeParams]:
(..${valueParams.map(_.tpt)}) => $name[..$typeArgs] = $applyDef
}
"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.