假设我正在解析一些 scala 源文件的美味文件,例如这个源文件:
/** Some comments
*/
trait LsFunctions:
...
我想提取“一些评论”评论,并理想地将其与特征 LsFunctions 相关联。
目前我的代码如下所示:
import codegen.tastyextractor.model.{EMethod, EPackage, EParam, EType}
import dotty.tools.dotc.ast.Trees.*
import scala.quoted.*
import scala.tasty.inspector.*
class StructureExtractorInspector extends Inspector:
override def inspect(using Quotes)(tastys: List[Tasty[quotes.type]]): Unit =
for tasty <- tastys do
val ctx = scala.quoted.quotes.asInstanceOf[scala.quoted.runtime.impl.QuotesImpl].ctx
given dotty.tools.dotc.core.Contexts.Context = ctx
tasty.ast match {
case PackageDef(pid, stats) =>
val types = stats.collect { case TypeDef(typeName, Template(constr, parentsOrDerived, self, preBody: List[_])) =>
...
但是我找不到任何可以给我评论的方法。使用美味检查器运行 scalac,我发现美味文件保留了注释。
我在上面的评论中使用了加斯顿提供的链接,并复制了一些代码,最终成功地从美味的文件中提取了评论。这里给出解决方案供参考。就我而言,我必须使用多个 TreeAccumulators,但我的代码的简化版本如下:
import scala.quoted.*
import scala.tasty.inspector.*
// something to collect the results including the scalaDocs
case class EType(name: String, scalaDocs: Option[String])
class StructureExtractorInspector extends Inspector:
override def inspect(using Quotes)(tastys: List[Tasty[quotes.type]]): Unit =
import quotes.reflect.*
object TypeTraverser extends TreeAccumulator[List[EType]]:
def foldTree(existing: List[EType], tree: Tree)(owner: Symbol): List[EType] =
val r = tree match
case c: ClassDef =>
val t = EType(c.name, c.symbol.docstring)
List(t)
case _ =>
Nil
foldOverTree(existing ++ r, tree)(owner)
end TypeTraverser
for tasty <- tastys do
val tree = tasty.ast
val results = TypeTraverser.foldTree(Nil, tree)(tree.symbol)
... do something with the results ...
最后运行它:
TastyInspector.inspectAllTastyFiles(Nil, jars, Nil)(inspector)