如何用Scala 3 Tasty Inspector提取源码注释并关联目标元素
问题描述
我正在解析Scala源码对应的Tasty文件,示例源码如下:
/** Some comments */ trait LsFunctions: ...
我希望提取其中的Some comments注释,并将其与特质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结合tasty-inspector时,发现Tasty文件中保留了这些注释。
解决方案
要提取Tasty文件中与特质关联的注释,可以利用Dotty编译器内置的注释处理API,基于你已有的代码修改即可:
导入注释处理依赖
在代码顶部添加Dotty注释相关类的导入:import dotty.tools.dotc.core.Comments在TypeDef匹配逻辑中提取注释
你已经获取了编译器上下文ctx,直接通过ctx.comment方法获取对应语法树节点的注释,再做文本清理即可:val types = stats.collect { case td @ TypeDef(typeName, Template(constr, parentsOrDerived, self, preBody: List[_])) => // 获取当前TypeDef节点的关联注释 val commentOpt: Option[Comments.Comment] = ctx.comment(td) // 清理注释文本,去除/**和*/标记 val cleanComment: Option[String] = commentOpt.map { c => c.rawText.trim .replaceFirst("^/\\*\\*", "") .replaceFirst("\\*/$", "") .trim } // 将特质名称与注释关联 (typeName.toString, cleanComment) }关键细节说明
ctx.comment(node)返回Option[Comments.Comment],无注释时为NoneComments.Comment.rawText保存了原始注释内容,需要手动清理掉注释标记符- 该方法适用于所有带注释的语法树节点(类、方法、参数等)
内容的提问来源于stack exchange,提问作者kostas.kougios
相关产品推荐
相关产品推荐

