Traversing AST with type information?

96 views
Skip to first unread message

Glen Mailer

unread,
Sep 27, 2020, 2:46:19 PM9/27/20
to golang-nuts

Hello!

I'm playing about with some go tooling, and I wanted to parse a package with type information to inspect it and derive some insights from the data.

I found the packages tool - https://godoc.org/golang.org/x/tools/go/packages - which on the surface appears to be exactly what I wanted.

However the output of this on a package (with all flags enabled) appears to be a slice of *ast.File nodes - which contain unresolved references, and a types.Package - from which I can inspect scopes.

I can't seem to find a way to inspect the resolved AST along with types - am I missing something or do I need to do more legwork myself?

Cheers
Glen

Dan

unread,
Sep 27, 2020, 5:28:03 PM9/27/20
to golang-nuts
The TypesInfo field of packages.Package holds the information you want.
https://godoc.org/golang.org/x/tools/go/packages#Package


Glen Mailer

unread,
Sep 27, 2020, 5:44:39 PM9/27/20
to golang-nuts
I think I'm now starting to get the hang of traversing around and looking up type info as needed now.

Are there any higher level libraries around which make navigating the ASTs easier? I'm finding I need to do a lot of conditional casts, which doesn't help the signal:noise ratio of my functions

Daniel T. Gorski

unread,
Sep 27, 2020, 7:28:20 PM9/27/20
to golang-nuts
On Sunday, 27 September 2020 at 20:46:19 UTC+2 Glen Mailer wrote:
I'm playing about with some go tooling, and I wanted to parse a package with type information to inspect it and derive some insights from the data.
[...]
I can't seem to find a way to inspect the resolved AST along with types - am I missing something or do I need to do more legwork myself?
Reply all
Reply to author
Forward
0 new messages