1 Star 0 Fork 0

zhyulo/cxgo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
go_print.go 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
package cxgo
import (
"go/ast"
"go/format"
token2 "go/token"
"io"
"sort"
"strconv"
"strings"
"github.com/gotranspile/cxgo/libs"
)
func PrintGo(w io.Writer, pkg string, decls []GoDecl, donotedit bool) error {
if donotedit {
w.Write([]byte("// Code generated by cxgo. DO NOT EDIT.\n\n"))
}
return format.Node(w, token2.NewFileSet(), &ast.File{
Decls: decls,
Name: ident(pkg),
})
}
type usageVisitor struct {
used map[string]struct{}
}
func (v *usageVisitor) Visit(n ast.Node) ast.Visitor {
switch n := n.(type) {
case *ast.Ident:
sub := strings.SplitN(n.Name, ".", 2)
if len(sub) == 2 {
v.used[sub[0]] = struct{}{}
}
}
return v
}
func goUsedImports(used map[string]struct{}, decls []GoDecl) {
for _, d := range decls {
ast.Walk(&usageVisitor{used: used}, d)
}
}
// ImportsFor generates import specs for well-known imports required for given declarations.
func ImportsFor(e *libs.Env, decls []GoDecl) []GoDecl {
used := make(map[string]struct{})
goUsedImports(used, decls)
var list []string
for k := range used {
list = append(list, k)
}
sort.Strings(list)
var specs []ast.Spec
for _, name := range list {
path := e.ResolveImport(name)
specs = append(specs, &ast.ImportSpec{Path: &ast.BasicLit{
Kind: token2.STRING,
Value: strconv.Quote(path),
}})
}
if len(specs) == 0 {
return nil
}
return []GoDecl{
&ast.GenDecl{
Tok: token2.IMPORT,
Specs: specs,
},
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zhyulo/cxgo.git
git@gitee.com:zhyulo/cxgo.git
zhyulo
cxgo
cxgo
main

搜索帮助

0d507c66 1850385 C8b1a773 1850385