golang ast 生成函数时,函数的注释跟函数关联不起来(生成的位置有误),有大佬帮忙解答一下吗?

317 天前
 japeth

stackoverflow 地址: https://stackoverflow.com/questions/76947041/code-generation-in-golang-using-the-go-ast-package-to-add-doc-comments-but-comm

当我在 errrmsg 目录中执行 GO GENERATE 时,函数的注释不在正确的位置

// Code generated by gen_code. DO NOT EDIT.
// 提示内容:"成功"
// 状态码:10000
// 提示内容:"失败"
// 状态码:10001

package errmsg

const (
    TypeCodeSuccess = 10000
    TypeCodeFailed  = 10001
)

func GetSuccess() Resp {
    return Resp{Code: TypeCodeSuccess, Msg: TypeMsgSuccess}
}

func GetFailed() Resp {
    return Resp{Code: TypeCodeFailed, Msg: TypeMsgFailed}
}

这是我的代码地址: https://github.com/KingPuiWong/generrcode/blob/master/gencode/main.go

当我试着这样做,但还是不起作用时,你知道怎么解决它吗?谢谢。

    commentMap := ast.NewCommentMap(fset, file, file.Comments)
    ast.Inspect(file, func(node ast.Node) bool {
        switch x := node.(type) {
        case *ast.FuncDecl:
            if strings.HasPrefix(x.Name.Name, "Get") {
                commentText := x.Doc.List[0].Text
                fmt.Println()
                fmt.Printf("comment:%s", commentText)
                commentMap[x] = []*ast.CommentGroup{{List: []*ast.Comment{{Text: commentText, Slash: token.Pos(int(x.Pos() - 1))}}}}
            }
        }
        return true
    })

    ast.Print(fset, file)
    //os.Exit(1)
    // 保存已分配的错误码
    err = saveLastErrorCode(projectName, lastCode)
    if err != nil {
        return err
        }

这是我想要生成的。

// Code generated by gen_code. DO NOT EDIT.
package errmsg

const (
    TypeCodeSuccess = 10000
    TypeCodeFailed  = 10001
)

// 提示内容:"成功"
// 状态码:10000
func GetSuccess() Resp {
    return Resp{Code: TypeCodeSuccess, Msg: TypeMsgSuccess}
}


// 提示内容:"失败"
// 状态码:10001
func GetFailed() Resp {
    return Resp{Code: TypeCodeFailed, Msg: TypeMsgFailed}
}
1003 次点击
所在节点    Go 编程语言
9 条回复
8520ccc
317 天前
代码生成推荐用 text/template ,舒服多了
joesonw
317 天前
ast 包一般都拿来读的,第一次见到写的。
代码生成用 text/template 或者 jennifer 。
chai2010
317 天前
感觉 pos 位置计算有点问题,int(x.Pos() - 1) 可能不是前一行。

pos 的定义可参考这里 https://chai2010.cn/go-ast-book/ch1/index.html 的 1.5 Position 位置信息
joyme
317 天前
https://go.dev/talks/2015/gofmt-en.slide#14 gofmt 的作者介绍过 comments 的处理,不知道对你是否有用。
japeth
317 天前
@8520ccc
@joesonw
谢谢,想先学习一下如何用 ast 直接生成,然后再写一个用 text/template 生成的
japeth
317 天前
@chai2010 晚上回去试一下,但是我猜测大概率不会是这个问题
japeth
317 天前
@chai2010 改成 x.post() 也是一样的效果
harmless
316 天前
可以试试 github.com/dave/dst ,注释友好,用法与 ast 差不多
japeth
316 天前
@harmless 谢谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/967224

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX