为什么GO AST解析器会生成带有额外空格或缩进的代码?

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

Why does GO AST Parser regenerate code with extra spaces or indents?

问题

我正在尝试从Go程序的AST中重新生成源代码。在重新生成源代码后,我试图将其与原始源代码进行匹配。但是重新生成的源代码在某些位置上会有一些额外的空格。以下是代码示例:

fs := token.NewFileSet()
f, err := parser.ParseFile(fs, filename, nil, parser.ParseComments)
if err != nil {
    log.Println(err)
}
cfg := printer.Config{Mode: printer.RawFormat}
err = cfg.Fprint(&buffer, fs, f)
if err != nil {
    log.Println(err)
}
source_code, err := os.ReadFile(filename)
if err != nil {
    log.Println(err)
}
buffer_source_code := buffer.String()

有人可以帮助我吗?我应该怎么做才能从AST中获取与原始源代码完全相同的源代码?

英文:

I am trying to regenerate source code from ast of a go program. After regenerating the source code, I am trying to match that with the original source code. But the regenerated source code gives some extra spaces in some places of the code. The code is given below.

fs := token.NewFileSet()
f, err := parser.ParseFile(fs, filename, nil, parser.ParseComments)
if err != nil {
log.Println(err)
}
cfg := printer.Config{Mode: printer.RawFormat}
err = cfg.Fprint(&buffer, fs, f)
if err != nil {
log.Println(err)
}
source_code, err := os.ReadFile(filename)
if err != nil {
log.Println(err)
}
buffer_source_code := buffer.String()

Can someone help me what should I do to get the exact source code as the original from a ast?

答案1

得分: 1

请看Decorated Syntax Tree

dst包可以以高保真度操作Go语法树。装饰(例如注释和行间距)会随着树的修改而正确地附加到相应的节点上。

英文:

Have a look at Decorated Syntax Tree

The dst package enables manipulation of a Go syntax tree with high fidelity. Decorations (e.g. comments and line spacing) remain attached to the correct nodes as the tree is modified.

huangapple
  • 本文由 发表于 2022年12月15日 12:33:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/74806858.html
匿名

发表评论

匿名网友

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

确定