format

package
v0.8.0-test2 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2023 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package format implements standard formatting of Go source.

Note that formatting of Go source code changes over time, so tools relying on consistent formatting should execute a specific version of the gofmt binary instead of using this package. That way, the formatting will be stable, and the tools won't need to be recompiled each time gofmt changes.

For example, pre-submit checks that use this package directly would behave differently depending on what Go version each developer uses, causing the check to be inherently fragile.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func File

func File(vfs fs.FS, filename string, src interface{}) (text []byte, changed bool, err error)

func Node

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

Node formats node in canonical gofmt style and writes the result to dst.

The node type must be *ast.File, *printer.CommentedNode, []ast.Decl, []ast.Stmt, or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt. Node does not modify node. Imports are not sorted for nodes representing partial source files (for instance, if the node is not an *ast.File or a *printer.CommentedNode not wrapping an *ast.File).

The function may return early (before the entire result is written) and return a formatting error, for instance due to an incorrect AST.

Example
package main

import (
	"bytes"
	"fmt"
	"log"

	"wa-lang.org/wa/internal/format"
	"wa-lang.org/wa/internal/parser"
	"wa-lang.org/wa/internal/token"
)

func main() {
	const expr = "(6+2*3)/4"

	// parser.ParseExpr parses the argument and returns the
	// corresponding ast.Node.
	node, err := parser.ParseExpr(expr)
	if err != nil {
		log.Fatal(err)
	}

	// Create a FileSet for node. Since the node does not come
	// from a real source file, fset will be empty.
	fset := token.NewFileSet()

	var buf bytes.Buffer
	err = format.Node(&buf, fset, node)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(buf.String())

}
Output:

(6 + 2*3) / 4

func SourceExpr

func SourceExpr(src []byte) ([]byte, error)

格式化表达式

func SourceFile

func SourceFile(src []byte) ([]byte, error)

格式化文件

Types

This section is empty.

Jump to

Keyboard shortcuts

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