Source file src/go/printer/example_test.go

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package printer_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/parser"
    12  	"go/printer"
    13  	"go/token"
    14  	"strings"
    15  )
    16  
    17  func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
    18  	fset = token.NewFileSet()
    19  	if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
    20  		for _, d := range file.Decls {
    21  			if f, ok := d.(*ast.FuncDecl); ok && f.Name.Name == functionname {
    22  				fun = f
    23  				return
    24  			}
    25  		}
    26  	}
    27  	panic("function not found")
    28  }
    29  
    30  func printSelf() {
    31  	// Parse source file and extract the AST without comments for
    32  	// this function, with position information referring to the
    33  	// file set fset.
    34  	funcAST, fset := parseFunc("example_test.go", "printSelf")
    35  
    36  	// Print the function body into buffer buf.
    37  	// The file set is provided to the printer so that it knows
    38  	// about the original source formatting and can add additional
    39  	// line breaks where they were present in the source.
    40  	var buf bytes.Buffer
    41  	printer.Fprint(&buf, fset, funcAST.Body)
    42  
    43  	// Remove braces {} enclosing the function body, unindent,
    44  	// and trim leading and trailing white space.
    45  	s := buf.String()
    46  	s = s[1 : len(s)-1]
    47  	s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
    48  
    49  	// Print the cleaned-up body text to stdout.
    50  	fmt.Println(s)
    51  }
    52  
    53  func ExampleFprint() {
    54  	printSelf()
    55  
    56  	// Output:
    57  	// funcAST, fset := parseFunc("example_test.go", "printSelf")
    58  	//
    59  	// var buf bytes.Buffer
    60  	// printer.Fprint(&buf, fset, funcAST.Body)
    61  	//
    62  	// s := buf.String()
    63  	// s = s[1 : len(s)-1]
    64  	// s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
    65  	//
    66  	// fmt.Println(s)
    67  }
    68  

View as plain text