Golang AST - 添加导入" C"

时间:2016-09-24 11:57:50

标签: go abstract-syntax-tree

我试图在开始时向AST添加import "C"。我想在导入节点中添加一些doc注释。想看起来像这样:

package main

/*
#include "postgres.h"
#include "fmgr.h"
*/
import "C"

func main() {}

这样做:

//parse the file
fset := token.NewFileSet()
f, err := parser.ParseDir(fset, dir, nil, parser.ParseComments)
if err != nil {
    panic(err)
}
//get the package main
packageAst, ok := f["main"]
if !ok {
    fmt.Println("No package main in", dir)
    return
}
//add the import "C" with the comment
for _, file := range packageAst.Files {
    comment := &ast.CommentGroup{
        List: []*ast.Comment{
            &ast.Comment{
                Slash: file.Package,
                Text:  "/*\n#include \"postgres.h\"\n#include \"fmgr.h\"\n*/",
            },
        },
    }
    importC := &ast.GenDecl{
        TokPos: file.Package,
        Tok:    token.IMPORT,
        Specs:  []ast.Spec{&ast.ImportSpec{Doc: comment, Path: &ast.BasicLit{Kind: token.STRING, Value: "\"C\""}}},
    }
    file.Decls = append([]ast.Decl{importC}, file.Decls...)
    break
}

输出是这样的:

package main

import "C"

func main() {}

评论不存在。我做错了什么?

0 个答案:

没有答案