2011-07-26 94 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方法。