Overview

Package printer implements printing of AST nodes.

nodes.go

func Fprint


Example:

  1. // Parse source file and extract the AST without comments for
  2. // this function, with position information referring to the
  3. // file set fset.
  4. funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
  5. // The file set is provided to the printer so that it knows
  6. // about the original source formatting and can add additional
  7. // line breaks where they were present in the source.
  8. var buf bytes.Buffer
  9. // Remove braces {} enclosing the function body, unindent,
  10. // and trim leading and trailing white space.
  11. s := buf.String()
  12. s = s[1 : len(s)-1]
  13. s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))
  14. // Print the cleaned-up body text to stdout.
  15. fmt.Println(s)
  16. // funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
  17. //
  18. // var buf bytes.Buffer
  19. // printer.Fprint(&buf, fset, funcAST.Body)
  20. //
  21. // s := buf.String()
  22. // s = s[1 : len(s)-1]
  23. // s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))
  24. //
  25. // fmt.Println(s)

A CommentedNode bundles an AST node and corresponding comments. It may be
provided as argument to any of the Fprint functions.

type

  1. type Config struct {
  2. Mode // default: 0
  3. Tabwidth int // default: 8
  4. Indent // default: 0 (all code is indented at least by this much)
  5. }

A Config node controls the output of Fprint.

Fprint “pretty-prints” an AST node to output for a given configuration cfg.
Position information is interpreted relative to the file set fset. The node type
must be ast.File, CommentedNode, []ast.Decl, []ast.Stmt, or
assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt.

    A Mode value is a set of flags (or 0). They control printing.