我想从typer
阶段之后运行的Scala编译器插件访问文档注释。
scala.tools.nsc.Global
扩展DocComments
,所以我认为它就像调用global.cookedDocComment(symbol)
一样简单,但即使对于有注释的符号,它也会返回空字符串。
然后我查看了docComments
地图的更新位置:主要位置在交互式编译器的
private def forceDocComment(sym: Symbol, unit: RichCompilationUnit) {
unit.body foreachPartial {
case DocDef(comment, defn) if defn.symbol == sym =>
fillDocComment(defn.symbol, comment) // <- updates the map
EmptyTree
case _: ValOrDefDef =>
EmptyTree
}
}
所以我尝试添加以下遍历:
object FindCommentsTraverser extends Traverser {
override def traverse(tree: Tree): Unit = tree match {
case DocDef(comment, definition) =>
fillDocComment(definition.symbol, comment)
case _ => super.traverse(tree)
}
}
val unit: global.CompilationUnit = ...
FindCommentsTraverser.traverse(unit.body)
我可以验证调用遍历器,但它从未遇到DocDef
。
object FindCommentsTraverser extends Traverser {
override def traverse(tree: Tree): Unit = tree match {
case DocDef(comment, definition) =>
super.traverse(tree)
// FIXME definition.symbol is NoSymbol
// fillDocComment(definition.symbol, comment)
// For now work around by searching for name
val name = definition match {
case named: NameTree => named.name.toString
}
symbolMap.valuesIterator.find {
sym => sym.nameString == name
}.foreach {
sym => fillDocComment(sym, comment)
}
case _ => super.traverse(tree)
}
}
val analyzer = new ScaladocSyntaxAnalyzer[global.type](global) {
override val runsAfter: List[String] = Nil
override val runsRightAfter: Option[String] = None
}
val parser = new analyzer.ScaladocUnitParser(context.unit, Nil)
val treeWithDocs = parser.parse()
FindCommentsTraverser.traverse(treeWithDocs)
其中symbolMap
是我的插件的一部分。