go/printer

Package printer

  • import "go/printer"

  • 概述

  • 索引

  • 示例

概述

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(显示源代码)

func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error

Fprint“漂亮地”输出一个A ST 节点。它使用默认设置调用 Config.Fprint。请注意,gofmt使用制表符缩进但使用空​​格对齐;使用format.Node(go/format包)来匹配 gofmt 的输出。

示例

代码:

// 解析源文件并提取没有注释的AST // 这个函数,位置信息参考 // 文件集fset。 funcAST, fset := parseFunc("example_test.go", "ExampleFprint") // 将函数体打印到缓冲区buf中。 // 文件集提供给打印机,以便它知道 // 关于原始源格式,可以添加其他内容 // 它们存在于源中的换行符。 var buf bytes.Buffer printer.Fprint(&buf, fset, funcAST.Body) // 删除包围函数体的大括号{},unindent, // 并修剪前导和尾随空白区域。 s := buf.String() s = s[1 : len(s)-1] s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1)) // 将清理后的正文文本打印到标准输出。 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)

type CommentedNode(显示源代码)

CommentedNode 捆绑了一个 AST 节点和相应的注释。它可以作为任何 Fprint 函数的参数提供。

type CommentedNode struct { Node interface{} // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt Comments []*ast.CommentGroup }

type Config(显示源代码)

Config 节点控制 Fprint 的输出。

type Config struct { Mode Mode // 默认值: 0 Tabwidth int // 默认值: 8 Indent int // 默认值:0(所有代码至少按此缩进)

func (*Config) Fprint(显示源代码)

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 或赋值兼容。

type Mode(显示源代码)

Mode 值是一组标志(或0)。他们控制打印。

type Mode uint

const ( RawFormat Mode = 1 << iota // 不要使用tabwriter; 如果设置,则忽略UseSpaces TabIndent // 使用制表符进行缩进,与UseSpaces无关 UseSpaces // 使用空格而不是制表符进行对齐 SourcePos // 发出//line 指令以保留原始源位置 )