斯卡拉宏注释 - 具有类型参数的案例类
问题描述:
我想为向伴随对象添加方法的案例类编写一个简单的宏注释。问题在于新方法必须考虑带注释的案例类的类型参数。斯卡拉宏注释 - 具有类型参数的案例类
下面是我需要传递
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))
}
}
这里是我写我的理解是,当我尝试lift的做到这一点
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与macro paradise 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
}
"""
就是这样。谢谢! – dbaumann