©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
import "go/printer"
Overview
Index
Examples
Package printer实现了AST节点的打印。
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
type CommentedNode
type Config
func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
type Mode
Fprint
nodes.go printer.go
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
Fprint“漂亮地”输出一个AST节点。它使用默认设置调用Config.Fprint。请注意,gofmt使用制表符缩进但使用空格对齐; 使用format.Node(包go /格式)来匹配gofmt的输出。
代码:
// 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", "ExampleFprint")// 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(&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.Replace(s, "\n\t", "\n", -1))// Print the cleaned-up body text to stdout.fmt.Println(s)
输出:
funcAST, fset := parseFunc("example_test.go", "ExampleFprint")var buf bytes.Buffer printer.Fprint(&buf, fset, funcAST.Body)s := buf.String()s = s[1 : len(s)-1]s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))fmt.Println(s)
CommentedNode捆绑了一个AST节点和相应的注释。它可以作为任何Fprint函数的参数提供。
type CommentedNode struct { Node interface{} // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt Comments []*ast.CommentGroup}
Config节点控制Fprint的输出。
type Config struct { Mode Mode // default: 0 Tabwidth int // default: 8 Indent int // default: 0 (all code is indented at least by this much)}
func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
Fprint“漂亮地打印”AST节点以输出给定的配置cfg。位置信息相对于文件集fset进行解释。节点类型必须为ast.Expr,ast.Decl,ast.Spec或ast.Stmt的* ast.File,* CommentedNode,[] ast.Decl,[] ast.Stmt或赋值兼容。
Mode值是一组标志(或0)。他们控制打印。
type Mode uint
const ( RawFormat Mode = 1 << 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)