summaryrefslogtreecommitdiff
path: root/devdocs/go/go%2Fprinter%2Findex.html
blob: b801c9894a45c116982e46a93e6a0d5fedcca7dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<h1> Package printer  </h1>     <ul id="short-nav">
<li><code>import "go/printer"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package printer implements printing of AST nodes. </p>     <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#Fprint">func Fprint(output io.Writer, fset *token.FileSet, node any) error</a></li>
<li><a href="#CommentedNode">type CommentedNode</a></li>
<li><a href="#Config">type Config</a></li>
<li> <a href="#Config.Fprint">func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node any) error</a>
</li>
<li><a href="#Mode">type Mode</a></li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example_Fprint">Fprint</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>comment.go</span> <span>gobuild.go</span> <span>nodes.go</span> <span>printer.go</span>  </p>   <h2 id="Fprint">func <span>Fprint</span>  </h2> <pre data-language="go">func Fprint(output io.Writer, fset *token.FileSet, node any) error</pre> <p>Fprint "pretty-prints" an AST node to output. It calls <a href="#Config.Fprint">Config.Fprint</a> with default settings. Note that gofmt uses tabs for indentation but spaces for alignment; use format.Node (package go/format) for output that matches gofmt. </p>   <h4 id="example_Fprint"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">package printer_test

import (
    "bytes"
    "fmt"
    "go/ast"
    "go/parser"
    "go/printer"
    "go/token"
    "strings"
)

func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
    fset = token.NewFileSet()
    if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
        for _, d := range file.Decls {
            if f, ok := d.(*ast.FuncDecl); ok &amp;&amp; f.Name.Name == functionname {
                fun = f
                return
            }
        }
    }
    panic("function not found")
}

func printSelf() {
    // Parse source file and extract the AST without comments for
    // this function, with position information referring to the
    // file set fset.
    funcAST, fset := parseFunc("example_test.go", "printSelf")

    // Print the function body into buffer buf.
    // The file set is provided to the printer so that it knows
    // about the original source formatting and can add additional
    // line breaks where they were present in the source.
    var buf bytes.Buffer
    printer.Fprint(&amp;buf, fset, funcAST.Body)

    // Remove braces {} enclosing the function body, unindent,
    // and trim leading and trailing white space.
    s := buf.String()
    s = s[1 : len(s)-1]
    s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))

    // Print the cleaned-up body text to stdout.
    fmt.Println(s)
}

func ExampleFprint() {
    printSelf()

    // Output:
    // funcAST, fset := parseFunc("example_test.go", "printSelf")
    //
    // var buf bytes.Buffer
    // printer.Fprint(&amp;buf, fset, funcAST.Body)
    //
    // s := buf.String()
    // s = s[1 : len(s)-1]
    // s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
    //
    // fmt.Println(s)
}
</pre>   <h2 id="CommentedNode">type <span>CommentedNode</span>  </h2> <p>A CommentedNode bundles an AST node and corresponding comments. It may be provided as argument to any of the <a href="#Fprint">Fprint</a> functions. </p>
<pre data-language="go">type CommentedNode struct {
    Node     any // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt
    Comments []*ast.CommentGroup
}
</pre> <h2 id="Config">type <span>Config</span>  </h2> <p>A Config node controls the output of Fprint. </p>
<pre data-language="go">type Config struct {
    Mode     Mode // default: 0
    Tabwidth int  // default: 8
    Indent   int  // default: 0 (all code is indented at least by this much); added in Go 1.1
}
</pre> <h3 id="Config.Fprint">func (*Config) <span>Fprint</span>  </h3> <pre data-language="go">func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node any) error</pre> <p>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 *<span>ast.File</span>, *<a href="#CommentedNode">CommentedNode</a>, []<span>ast.Decl</span>, []<span>ast.Stmt</span>, or assignment-compatible to <span>ast.Expr</span>, <span>ast.Decl</span>, <span>ast.Spec</span>, or <span>ast.Stmt</span>. </p>
<h2 id="Mode">type <span>Mode</span>  </h2> <p>A Mode value is a set of flags (or 0). They control printing. </p>
<pre data-language="go">type Mode uint</pre> <pre data-language="go">const (
    RawFormat Mode = 1 &lt;&lt; iota // do not use a tabwriter; if set, UseSpaces is ignored
    TabIndent                  // use tabs for indentation independent of UseSpaces
    UseSpaces                  // use spaces instead of tabs for alignment
    SourcePos                  // emit //line directives to preserve original source positions
)</pre><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/go/printer/" class="_attribution-link">http://golang.org/pkg/go/printer/</a>
  </p>
</div>