【发布时间】:2014-04-22 11:24:55
【问题描述】:
在 scala 控制台中,我可以毫无问题地执行以下操作:
scala> val tree = q"def f():MySuperType[(Char,Char)]"
tree: universe.DefDef = def f(): MySuperType[scala.Tuple2[Char, Char]]
scala> val q"def $f():$d" = tree
f: universe.TermName = f
d: universe.Tree = MySuperType[scala.Tuple2[Char, Char]]
scala> val tq"$a[$TheTypeThatIWant]" = d
a: universe.Tree = MySuperType
TheTypeThatIWant: universe.Tree = scala.Tuple2[Char, Char]
我可以得到我想要的:TheTypeThatIWant
的内容现在,如果我尝试在 quasiquote 中执行此操作,则会收到匹配异常,并且我没有找到获取应用类型的内部类型的方法。
我的代码:
tree match {
case q"{..$body}" =>
body.foreach (_ match {
case q"def $functionName:$type = $osef" =>
val tq"$f[$typ]" = d //I want to get $typ !!
...
}
但我得到的只是:
exception during macro expansion:
exception during macro expansion:
scala.MatchError: MyMacro.MySuperType[(Char, Char)] (of class scala.reflect.internal.Trees$TypeTree)
at MyMacro$$anonfun$getBasicStructure$1$1.apply(MyMacro.scala:737)
at MyMacro$$anonfun$getBasicStructure$1$1.apply(MyMacro.scala:735)
at scala.collection.immutable.List.foreach(List.scala:383)
at MyMacro$.getBasicStructure$1(MyMacro.scala:735)
at MyMacro$.MyMacro_impl(MyMacro.scala:846)
我该如何解决?
谢谢
编辑:
问题不仅在于 quasiquotes,甚至在我使用 Trees 时也会出现问题:
case Block(stats,expr) =>
stats.foreach(_ match {
case DefDef(_,_,_,_,typ,_) =>
typ match {
case AppliedTypeTree(t,args) => //doesnt go there
case TypeApply(t,args) => //doesnt go there
case x:TypeTree => //goes there but can't get any info about the applied type
case _ =>
}
})
编辑2:
你必须这样做:
case q"def $name:${d:TypeTree} = $b" =>
d.tpe match {
case TypeRef(x,y,z) => //z is the list of applied types, see scaladoc
case _ =>
}
【问题讨论】:
-
这是一个已知错误:issues.scala-lang.org/browse/SI-8388。
-
哦,好的,有什么解决方法吗?
-
该修复刚刚合并到 2.11-RC4。它可能会在下周的某个时候被移植到天堂。
标签: scala macros types scala-quasiquotes