2011-07-26 44 views
2

我正在写一个插件,它监视@unmatchable注释,并在模式匹配中发现警告。Scala编译器类型参考ClassDef

我已经能够找到TypeRef,但我无法将其转换为ClassDef,因此我可以检查Annoations。

我猜我需要得到树的根目录并使用TreeOpts.find才能得到实际的ClassDef。但是,我无法找到根树的位置。

编辑:我需要超过根编译单位的情况下,库中包含可匹配的annoation。

这是我到目前为止。

class UnmatchablePlugin(val global: Global) extends Plugin { 
    val name = "unmatchable-check-gen" 
    val description = "marks a class unmatchable" 
    val components = List[PluginComponent](UnmatchableComponent) 

    private object UnmatchableComponent extends PluginComponent with Transform { 
    val global: UnmatchablePlugin.this.global.type = UnmatchablePlugin.this.global 
    val runsAfter = List("parser") 
    // Using the Scala Compiler 2.8.x the runsAfter should be written as below 
    // val runsAfter = List[String]("parser"); 
    val phaseName = UnmatchablePlugin.this.name 

    def newTransformer(unit: global.CompilationUnit) = UnmatchableTransformer 

    object UnmatchableTransformer extends global.Transformer { 
     override def transform(tree: global.Tree) = { 
     import global._ 

     tree match { 
      case cd @ global.CaseDef(global.Bind(_, global.Typed(exp,tpt)) , _, _) => { 

      //Need to turn tpt.tpe.sym into a ClassDef 
      println("sym: " + tpt.tpe.sym) 
      tree 
      } 
      case t => super.transform(t) 
     } 
     } 
    } 
    } 
} 

回答

0

一般情况下,你不能把类型/符号成树,因为有可能是具有与它没有树的象征。例如,当符号与二进制类文件中定义的类相对应时就是这种情况。

但是,据我了解你正在尝试做什么,你不需要ClassDef。您获得的符号已经包含关于注释的所有信息。检查Symbols.scala(第1115-1118行)中定义的hasAnnotation和getAnnotation方法。