Created
October 15, 2018 20:54
-
-
Save karlmutch/fb43c6076a98d8c8e8aa5122b23c3aed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"go/ast" | |
"go/parser" | |
"go/token" | |
"go/format" | |
"os" | |
"reflect" | |
"bytes" | |
"fmt" | |
) | |
func main() { | |
// src is the input for which we want to print the AST. | |
src := | |
`// +build !test | |
package main | |
func main() { | |
v := []string{"constant"} | |
for _, x := range v { | |
} | |
} | |
` | |
// Create the AST by parsing src. | |
fset := token.NewFileSet() // positions are relative to fset | |
f, err := parser.ParseFile(fset, "", src, parser.ParseComments) | |
if err != nil { | |
panic(err) | |
} | |
// Print the modified AST. | |
var buf bytes.Buffer | |
if err := format.Node(&buf, fset, f); err != nil { | |
panic(err) | |
} | |
fmt.Printf("%s", buf.Bytes()) | |
// Print the AST. | |
ast.Print(fset, f) | |
ast.Fprint(os.Stdout, fset, f, func(name string, value reflect.Value) bool { | |
if ast.NotNilFilter(name, value) { | |
return value.Type().String() != "*ast.Object" | |
} | |
return false | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment