在Scala编译器插件中访问文档注释

时间:2018-03-29 09:47:47

标签: scala scala-compiler

我想从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是我的插件的一部分。

0 个答案:

没有答案