ast_print.go 691 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "go/ast"
  6. "go/parser"
  7. "go/printer"
  8. "go/token"
  9. )
  10. func main() {
  11. // src is the input for which we want to print the AST.
  12. src := `
  13. package main
  14. func main() {
  15. fmt.Println(myNode.Node.Type.Hello)
  16. }
  17. `
  18. // Create the AST by parsing src.
  19. fset := token.NewFileSet() // positions are relative to fset
  20. f, err := parser.ParseFile(fset, "", src, 0)
  21. if err != nil {
  22. panic(err)
  23. }
  24. // (f.Decls[0].(*ast.GenDecl)).Specs[0].Name.Obj = nil
  25. // ((f.Decls[0].(*ast.GenDecl)).Specs[0].(*ast.TypeSpec).Name.Obj) = nil
  26. // f.Imports = nil
  27. ast.Print(fset, f)
  28. // Print the AST.
  29. var buf bytes.Buffer
  30. printer.Fprint(&buf, fset, f)
  31. fmt.Println(buf.String())
  32. }