go - 使用包加载器,如何更新包含注释的ast并打印结果代码

标签 go abstract-syntax-tree

给定此代码,我如何在不破坏注释节点的情况下使用额外的导入规范打印它。

https://play.golang.org/p/N6_y1ehM1Qc

package main

import (
    "go/ast"
    "go/parser"
    "go/printer"
    "go/token"
    "log"
    "os"

    "golang.org/x/tools/go/loader"
)

func main() {

    var conf loader.Config
    conf.ParserMode = parser.ParseComments

    f, err := conf.ParseFile("main.go", `// some comment goes here 
package main

// some comment here.

// main comment here.
func main(){
}
`)
    if err != nil {
        log.Fatal(err)
    }
    conf.CreateFromFiles("main", f)
    prog, err := conf.Load()
    if err != nil {
        log.Println(err)
    }

    g := &ast.GenDecl{}
    g.Tok = token.IMPORT
    spec := &ast.ImportSpec{
        Path: &ast.BasicLit{Value: "package/path"},
    }
    g.Specs = append(g.Specs, spec)
    f.Decls = append([]ast.Decl{g}, f.Decls...)
    _ = prog
    printer.Fprint(os.Stdout, token.NewFileSet(), f)
    //printer.Fprint(os.Stdout, prog.Fset, f)
}

该程序显示
package main // some comment goes here
// some comment here.
// main comment here.
import package/path

func main() {
}

我期望得到类似的输出(不确定import语句是在单独的第二个注释行之前还是之后)
// some comment goes here
package main

// some comment here.
import package/path

// main comment here.
func main() {
}

在更复杂的程序中,输出中断。我得到了混乱的go代码,例如
// some comment goes here
package main

import // some comment here.
package/path

// main comment here.
func main() {
}

最佳答案

对于我的特定用例,添加一个import语句,解决方案是使用astutil.AddImport,如@mkopriva所建议

astutil.AddImport(prog.Fset, f, "package/path")

关于go - 使用包加载器,如何更新包含注释的ast并打印结果代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955135/

相关文章:

go - 如何确保 go build 使用 vendor 目录中的所有依赖项

go - Golang修复jpeg错误的EOF格式

go - 在 golang 模板之间共享变量

java - 如何在CompilationUnit中获取有关导入的问题

Python 3,ast.literal_eval(node_or_string) 中是否有任何已知的安全漏洞?

python - 尝试通过添加更多键 :value pairs 来增加嵌套字典

go - 如何将字符串作为参数传递给 Golang 指针接收函数?

go - 如何将字节数组转换为 io.流并将其转换回字节数组?

parsing - 如何构建解析器以将 Lucene 语法解析为 AST

php - 我可以在代码上强制执行哪些类型的模式以使其更容易转换为另一种编程语言?