Graham King

Solvitas perambulum

Dump Go Abstract Syntax Tree

Go has good support for examining and modifying Go source code. This is a huge help in writing refactoring and code analysis tools. The first step is usually to parse a source file into it’s Abstract Syntax Tree representation. Here’s a complete program to display the AST for a given Go file:

package main

import (
    "go/ast"
    "go/parser"
    "go/token"
    "os"
)

func main() {
    fset := new(token.FileSet)
    f, _ := parser.ParseFile(fset, os.Args[1], nil, 0)
    ast.Print(fset, f)
}

Use:

  • Save that as goast.go
  • Build it: go build goast.go
  • Run it: ./goast <myfile.go>