printer

package
v0.0.0-...-256ef38 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 12, 2018 License: BSD-3-Clause Imports: 12 Imported by: 1

Documentation

Overview

Package printer implements printing of AST nodes.

Index

Examples

Constants

View Source
const (
	SeeNext = -32768
)

Variables

This section is empty.

Functions

func Fprint

func Fprint(formatOptions *FormatOptions, src []byte, output io.Writer, fset *token.FileSet, node interface{}) error

Fprint "pretty-prints" an AST node to output for a given set of formatOptions. 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. src is the source code from which fset is derived.

formatOptions:

  • formatOptions must not be nil.
  • The last entry in the formatOptions linked list must have all fields != SeeNext.
Example
package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"strings"
	"winterdrache.de/goformat/printer"
)

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 && f.Name.Name == functionname {
				fun = f
				return
			}
		}
	}
	panic("function not found")
}

func main() {
	// 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)

}
Output:

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)

Types

type CommentedNode

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

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

type Context

type Context uint

A Context is a set of flags, set depending on what's currently being printed. The user can specify different formatting options depending on context. If multiple flags are asserted that means the context is the intersection of these flags, e.g. CtxFileHeader|CtxBlockComment means a block comment in the file's header area. Some flags are mutually exclusive, e.g. CtxLineComment and CtxBlockComment.

const (
	CtxLineComment  Context = 1 << iota // line comment, i.e. //...
	CtxBlockComment                     // block comment i.e. /*...*/
	CtxFileHeader                       // everything before the "package" keyword
	CtxSwitch                           // switch or type switch
	CtxCase                             // case clause
	CtxSelect                           // select
)

type FormatOptions

type FormatOptions struct {
	Next         *FormatOptions // next (lower priority) in the chain of options
	Context                     // which context these options apply to
	Mode         Mode           // default: 0, SeeNext => unset, use Next
	Tabwidth     int            // default: 8, this is the width of 1 indentation step, SeeNext => unset, use Next
	Indent       int            // default: 0 (add this many Tabwidth sized indents before each line), SeeNext => unset, use Next
	Column       int            // default: 0, min width of columns for alignment (excluding indentation which is Tabwidth)
	Pad          int            // default: 1, number of spaces to add to each column (except indentation)
	Shift        int            // default: 0, number of spaces to add after indentation
	Enter0       int            // default: 0, indent steps for blocks that gofmt has a default of 0 for
	Enter        int            // default: 1, indent steps for blocks that gofmt has a default of 1 for
	InlineBlocks int            // default: 0 (always insert newline after { and before }, 1: respect original formatting
}

A FormatOptions node controls the output of Fprint.

func FormatOptionsDefault

func FormatOptionsDefault() *FormatOptions

func FormatOptionsUninitialized

func FormatOptionsUninitialized() *FormatOptions

func ParseStyle

func ParseStyle(style string) (*FormatOptions, error)

Parses a style definition into a linked list of FormatOptions. The last entry in the list is always complete, i.e. has no SeeNext fields.

func (*FormatOptions) Equals

func (fo *FormatOptions) Equals(fo2 *FormatOptions) bool

Returns true iff the formatting fields of fo and fo2 are equal. Context and Next links are ignored.

func (*FormatOptions) ForContext

func (fo *FormatOptions) ForContext(ctx Context) *FormatOptions

Returns a complete set (i.e. without SeeNext entries) of FormatOptions for the given context.

func (*FormatOptions) TabWriterOptions

func (cfg *FormatOptions) TabWriterOptions() (minwidth, minwidth_empty, tabwidth, padding int, padchar byte, twmode uint)

Returns arguments for tabwriter.NewWriter() corresponding to these FormatOptions

type Mode

type Mode int

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

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
	KeepIndent                  // (overrides TabIndent) use original indentation from source
	NoIndent                    // (overrides TabIndent/KeepIndent but not FormatOptions.Indent) left-align all lines
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL