Skip to content

Instantly share code, notes, and snippets.

@theunrepentantgeek
Created May 25, 2020 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theunrepentantgeek/c1cfbd8044bf273da61660d01995545c to your computer and use it in GitHub Desktop.
Save theunrepentantgeek/c1cfbd8044bf273da61660d01995545c to your computer and use it in GitHub Desktop.
Dump a Go source file as an Abstract Syntax Tree (AST)
package main
import (
"fmt"
"os"
"go/ast"
"go/format"
"go/parser"
"go/token"
//"github.com/davecgh/go-spew/spew"
)
func main() {
// positions are relative to fset
fset := token.NewFileSet()
// Read in the original file
snippet, err := parser.ParseFile(fset, "original.go", nil, parser.Trace | parser.ParseComments)
// Print structure to stdout
ast.Print(fset, snippet)
// Write to a final file for comparison
f, err := os.Create("demo.txt")
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
defer f.Close()
err = format.Node(f, fset, snippet)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// This is a generated file. Please do not make manual changes.
package main
func DemoFunc() (this *int, that *int) {
return nil, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment