Rabarar's Blog

A blogging framework for mild hackers.

Golang on Golang

| Comments

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 go/parser and go/ast

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 ast.File

1
2
3
4
5
6
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
if err != nil {
        panic(err)
}

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
// Print the imports from the file's AST.
  for _, s := range f.Imports {
      fmt.Println(s.Path.Value)
  }

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 :)

Comments