fields of structs with particular comment using ast

270 views
Skip to first unread message

amarjeeta...@gmail.com

unread,
Jun 20, 2020, 11:47:25 AM6/20/20
to golang-nuts
Hi
How can I find the list of fields of all structs with some particular comment using ast(or maybe other tool available in the lang)?

Using ast.Inspect(), we get different callbacks for diff ast nodes, like:-
  • *ast.Comment :- gives comment
  • *ast.TypeSpec: gives the name of the struct
  • *ast.StructType: gives the list of fields of a struct

But my problem is --
  • When type is *ast.Comment,     I have comments, but I don't have access to struct name and its fields
  • When type is *ast.TypeSpec,     I have struct name but I don't haves access to it's comments.
  • When type is *ast.StructType,   I have access to its fields, but I don't have access to comment & struct name.

My question is how can I merge all these three callbacks to ensure this is the same comments and fields belonging to the same struct?


amarjeeta...@gmail.com

unread,
Jun 20, 2020, 11:59:01 AM6/20/20
to golang-nuts
Will try to explain with an example --

// expectedComment
type StructNameA struct {
NameA string
AgeA int
}

// some diff comment
type StructNameB struct {
NameB string
AgeB int
}


Now I want the name of StructNameA struct along with its fields because it contains expectedComment at the top.
To check if the comment is expectedComment, I will need that too.
So basically I will need the list of triplet {comment, typeSpec, structType}.

Bebop Leaf

unread,
Jun 20, 2020, 4:01:56 PM6/20/20
to golang-nuts

Generally, you are looking for a `*ast.GenDecl` and its doc, which contains a `ast.TypeSpec`, when it is written as `type Name Type{ ... }`. However, though nearly never happened, people can write it as `type ( Name Type{....} )`, just like a `var` statement would. In that case, you are looking directly into `*ast.TypeSpec`s.

I have written a library for it some time ago, but I got extremely busy immediately so it was not documented, but you can read it (with help of tests) here: https://git.sr.ht/~leaf_bebop/astutil/tree/master/typedoc
Reply all
Reply to author
Forward
0 new messages