Golang packages “go/parser” and “go/ast”
Golang Parsing Golang:
Included as part of the built-in golang packages are libraries that provide for programatic parsing and inspecting of golang source code.
The two key packages are
Let’s take a look Parsing process. To start, we must create an Abstract Syntax Tree (AST). Next, we can Parse a source file (or string), which upon success returns a pointer to and AST,
*ast.File. All the meat is inside the
1 2 3 4 5 6
Now we can look at different aspects within the parse. For example, if we want to see what imports are included in the source file:
1 2 3 4
Lots of opportunities to parse through and look for declarations, functions, specific language mechanisms, expressions, etc. The opportunities are virtually limitless!
There’s a ton of reflection at play in this package. You’ll need to inspect and assert to look at the specific elements within a structure. A close read of the AST Print is a worthwhile exercise :)