我想从typer
阶段后运行的 Scala 编译器插件访问文档注释。
scala.tools.nsc.Global
extends 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
我的插件的一部分在哪里。