英文:
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
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论