首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >指定Toolbox解析的AST的源

指定Toolbox解析的AST的源
EN

Stack Overflow用户
提问于 2019-02-15 03:55:42
回答 2查看 186关注 0票数 1

我正在使用Scala的编译器API中的工具箱将代码编译成AST,然后对它们进行分解/拼接,并将它们组合成一棵树。为了调试目的,我试图跟踪哪个节点来自哪个源代码。

示例:

代码语言:javascript
复制
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox

// obtain toolbox
val tb = runtimeMirror(this.getClass.getClassLoader).mkToolBox()
// get and parse source code from file
val myCode = scala.io.Source.fromFile("MyCode.scala").mkString
val myTree = tb.parse(myCode)
// get and parse dynamically-generated source code
val genCode = com.example.CodeGenerator.gimmeCode
val genTree = tb.parse(genCode)
// get and parse source code from a string literal
val literalCode = """println("to life, the universe, and everything")"""
val literalTree = tb.parse(literalCode)
// an over-simplified combination of the trees
val frankensteinsTree = q"$myTree;$genTree;$literalTree"

// walk the tree an print the source of each element
val traverser = new Traverser() {

  override def traverse(tree: Tree): Unit = {

    println("This node originated from " + tree.pos.source)
    super.traverse(tree)
  }
}

// the root element prints "This node originated from <no source file>"
// the rest print "This node originated from <toolbox>"
traverser.traverse(frankensteinsTree)

在上面的示例中,除了根节点之外,所有其他节点都显示源是<toolbox>。(根节点表示<no source file>。)在剖析和重新组合它们之前,是否有一种方法可以指定tree.pos.source来识别每个节点的实际来源?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-29 02:45:27

不,目前(从2020年到05-28年)不能这样做。

票数 0
EN

Stack Overflow用户

发布于 2019-02-25 10:20:01

你是说

代码语言:javascript
复制
println("Position is:  " + "MyCode" + tree.pos.toString.stripPrefix("source-<toolbox>"))
// Position is:  MyCode,line-1,offset=7

试一试

代码语言:javascript
复制
val p = tree.pos
val pointMessage  = if (p.point > p.source.length) "out-of-bounds-" else "offset="
println(
  s"source-${p.source.file.canonicalPath},INSERT WHAT YOU WANT,line-${p.line},$pointMessage${p.point}"
) // source-<toolbox>,INSERT WHAT YOU WANT,line-1,offset=7
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54702475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档