GoLang ast:生成并打印一棵没有位置信息的树

huangapple go评论77阅读模式
英文:

GoLang ast: generating and printing a tree without position information

问题

我正在寻找一种工具,可以根据给定的输入生成方法存根。我看过 ast 包,但它似乎表示已经解析过的 AST,其中包含有关源文件中每个元素位置的信息。重要的是,您需要提供源信息。

我正在考虑以编程方式生成源文件,所以我不知道我的 AST 节点最终会出现在文件的哪个位置。

我想知道:

  • 是否有更好的 AST 工具可以在不提供源文件位置信息的情况下生成代码?
  • 如果我在 ast 包中为位置提供虚拟信息,它是否会正确地进行漂亮打印(即忽略位置信息)?

我意识到我可以使用文本生成来完成所有这些,但那似乎是不安全的类型,并且更难处理。

英文:

I'm looking to make a tool which generates method stubs from some given input. I've seen the ast package, but it seems to represent an already parsed AST, which has information about where in the source file everything is. Importantly, you need to provide source information

I'm looking at generating a source file programatically, so I have no idea where in the final file my AST nodes will end up.

I'm wondering:

  • Is there a better AST tool which lets you generate code without giving source file position information?
  • If I give dummy information for positions in the ast package, will it pretty-print properly (i.e. ignore the position information)?

I realize I could do this all with text generation, but that seems type-unsafe and harder to deal with.

答案1

得分: 3

考虑使用https://github.com/lu4p/astextract,它具有更好的AST,可以打印为go代码。

我知道你已经考虑过这个问题,但实际上,在生成的字符串上使用text/templategoimports是相当合理的。它更容易编写,并且转换为普通的go代码更好。正如你所指出的,它不是类型安全的(这没关系,因为稍后在运行goimports时会强制执行)。最大的缺点实际上是很难进行测试(我们最终编写了一组生成的测试和手动编写的测试)。

(编辑:刚意识到这是一个很久以前的问题-我会将我的答案保留下来,因为我相信你现在已经找到了解决方法)

英文:

Consider https://github.com/lu4p/astextract which has a nicer AST to work with that can be printed into go code.

I know you've thought about this, but using text/template and goimports on the resulting string is actually quite reasonable. It's way easier to write and it translates much better to writing normal go code. As you note, it's not type-safe (which is fine because running goimports on it later enforces that). The biggest con is actually that it's hard to test (we ended up writing a set of generated tests and manual written tests).

(EDIT: just realized how old of a question this is - going to leave my answer up for others as I'm sure you've found some way to solve this for yourself by now)

huangapple
  • 本文由 发表于 2016年11月2日 01:24:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/40365301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定