Parsing comments that don't start with a space

84 views
Skip to first unread message

Christian Stewart

unread,
Nov 6, 2022, 2:55:32 PM11/6/22
to golang-nuts
Hi all,

I'm trying to use packages.Load to parse the following comment:

// Thing does something.
//
//my:value do-something

I'm trying to parse the my:value comment similar to go:embed.

Interestingly the comment does not appear in the AST unless I put a space:

// my:value do-something

My questions are:

 - Why does the comment not appear unless I put a space before? (in ast CommentMap)
 - What's the best way to detect these comments?

Thanks,
Christian Stewart

Dan Kortschak

unread,
Nov 6, 2022, 3:10:08 PM11/6/22
to golan...@googlegroups.com
On Sun, 2022-11-06 at 11:55 -0800, 'Christian Stewart' via golang-nuts
wrote:
>  - Why does the comment not appear unless I put a space before? (in
> ast CommentMap)

This is explained here https://pkg.go.dev/go/ast#CommentGroup.Text

> Comment directives like "//line" and "//go:noinline" are also
removed.

>  - What's the best way to detect these comments?

You can interact directly with the data in the CommentGroup struct List
field.

Christian Stewart

unread,
Nov 6, 2022, 3:11:29 PM11/6/22
to golang-nuts
Hi all,

Figured it out: the comments appear in the comment.List, but not comment.Text():

cmap := ast.NewCommentMap(fset, codeFile, codeFile.Comments)
for nod, comments := range cmap {
    for _, comment := range comments {
        comment.Text() // Does not contain comments w/o a space before the comment.
        for _, elem := range comment.List {
             elem.Text // - Contains the entire comment line: like: //my:foo
        }
}

Thanks,
Christian Stewart
Reply all
Reply to author
Forward
0 new messages