2

在 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)

我该如何解决?

谢谢

编辑 :

问题不仅在于准引号,甚至在我使用 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 _ =>
              }
4

1 回答 1

0

好吧,我想这是因为在控制台中,当您调用val tq"$a[$TheTypeThatIWant]" = d时,类型d实际上是已知的,但在宏中并非如此。

于 2014-03-17T10:11:14.577 回答