format

package
v1.2.23 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Copyright Consensys Software Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

SPDX-License-Identifier: Apache-2.0

Copyright Consensys Software Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

SPDX-License-Identifier: Apache-2.0

Copyright Consensys Software Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

SPDX-License-Identifier: Apache-2.0

Copyright Consensys Software Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

SPDX-License-Identifier: Apache-2.0

Index

Constants

View Source
const DEFAULT_INDENTATION uint = 4

DEFAULT_INDENTATION sets the default level of indentation (in spaces).

Variables

View Source
var (
	// DEFAULT_INSERTION_RULES contains the set of default whitespace insertion rules to use.
	DEFAULT_INSERTION_RULES []InsertionRule
	// ONE_SPACE is a fixed token representing a single space
	ONE_SPACE = lex.Token{Kind: parser.SPACES, Span: source.NewSpan(0, 1)}
	// ONE_NEWLINE is a fixed token representing a single newline
	ONE_NEWLINE = lex.Token{Kind: parser.NEWLINE, Span: source.NewSpan(0, 1)}
)
View Source
var (
	// DEFAULT_REMOVAL_RULES contains the set of default token removal rules to use.
	DEFAULT_REMOVAL_RULES []RemovalRule
)

Functions

This section is empty.

Types

type Formatter

type Formatter struct {
	// contains filtered or unexported fields
}

Formatter provides a configurable mechanism for formatting source files (e.g. where indentation, maximum line length, etc can be specified). The intention is that, having constructed a formatter, it is then configured before finally applying Format().

func NewFormatter

func NewFormatter(out io.Writer, srcfile *source.File) (*Formatter, []source.SyntaxError)

NewFormatter constructs a new formatter. This begins by attempting to parse the source file. If this fails, then context-dependent formatting rules will not be used.

func (*Formatter) Format

func (p *Formatter) Format() error

Format the source file, pretty printing result to out. This operates by directly manipulating the token set to remove / insert whitespace and newlines. Specifically, it begins by removing all whitespace except newlines and comments. Then, it reinserts whitespace to meet the indentation requirements according to a given set of rules. If the original source file could not be parsed, then context-dependent rules are disabled.

func (*Formatter) IndentWithSpaces

func (p *Formatter) IndentWithSpaces(spaces uint) *Formatter

IndentWithSpaces configures the formatter to indent using a given number of spaces.

func (*Formatter) IndentWithTabs

func (p *Formatter) IndentWithTabs() *Formatter

IndentWithTabs configures the formatter to indent using tabs, rather than spaces.

func (*Formatter) ReinsertWhiteSpace

func (p *Formatter) ReinsertWhiteSpace(tokens []lex.Token) (ntokens []lex.Token)

ReinsertWhiteSpace reinserts whitespace according to a given set of insertion rules.

func (*Formatter) StripWhiteSpace

func (p *Formatter) StripWhiteSpace(tokens []lex.Token) []lex.Token

StripWhiteSpace strips white space from the given set of tokens, whilst retaining new lines.

type InsertionRule

type InsertionRule interface {
	// Before indicates whether or not to insert whitespace before a given token
	// and, if so, what whitespace to insert (i.e. either WHITESPACE or
	// NEWLINE, etc).  The prev iterator yields preceding tokens in reverse order
	// (most recent first), allowing rules to look back as far as needed.
	Before(indent uint, prev iter.Iterator[lex.Token]) []lex.Token
	// After indicates whether or not to insert whitespace after a given token
	// and, if so, what whitespace to insert (i.e. either WHITESPACE or
	// NEWLINE, etc).  The next iterator yields following tokens in forward order
	// (nearest first), allowing rules to look ahead as far as needed.
	After(indent uint, next iter.Iterator[lex.Token]) []lex.Token
}

InsertionRule represents a rule for inserting whitespace of some kind (e.g. newlines, tabs or spaces). Observe the spans for inserted token do not correspond with the orignal source file. Rather, for the WHITESPACE token, it simply determines how many spaces to insert.

func InsertAfter

func InsertAfter(token lex.Token) InsertionRule

InsertAfter constructs a rule which always inserts the given token afterwards.

func InsertForCloseCurly

func InsertForCloseCurly(indent uint) InsertionRule

InsertForCloseCurly constructs a rule for '}' that inserts a newline+indent before it unless the output already ends with a newline (possibly followed by indentation).

func InsertForOpenCurly

func InsertForOpenCurly(indent uint) InsertionRule

InsertForOpenCurly constructs a rule for '{' that inserts a space before (unless already spaced) and a newline+indent after (unless a newline or comment already follows).

func InsertIndent

func InsertIndent(indent uint) InsertionRule

InsertIndent constructs a rule which always inserts the given token afterwards.

func InsertSemicolonSpace

func InsertSemicolonSpace() InsertionRule

InsertSemicolonSpace constructs a rule for ';' that inserts a space after the semicolon in most contexts (e.g. for-loop headers) but suppresses it inside square brackets (fixed-size array types like [u8;3]).

func InsertSpaceAfter

func InsertSpaceAfter() InsertionRule

InsertSpaceAfter constructs a rule which inserts a space after the matched token, unless the following token is a NEWLINE (avoiding a trailing space on the last item of a line, e.g. a comma at the end of a line).

func InsertSpaceAfterIfString

func InsertSpaceAfterIfString() InsertionRule

InsertSpaceAfterIfString constructs a rule which inserts a space after the matched token only when the immediately following token is a STRING. Used for keywords like 'fail' whose string argument is optional, so that a bare keyword does not gain a trailing space.

func InsertSpaceAround

func InsertSpaceAround() InsertionRule

InsertSpaceAround constructs a rule which inserts a space both before and after the matched token, unless the following token is a NEWLINE (avoiding a trailing space when the operator appears at the end of a line).

func InsertSpaceBefore

func InsertSpaceBefore() InsertionRule

InsertSpaceBefore constructs a rule which inserts a space before the matched token only when the preceding token's rule did not already emit a trailing space. This avoids double-spacing when two rules would otherwise both contribute whitespace at the same boundary (e.g. "else {").

type RemovalRule

type RemovalRule interface {
	// Before returns true if the token should be removed based on the preceding
	// tokens.  The prev iterator yields already-emitted tokens in reverse order
	// (most recent first).
	Before(prev iter.Iterator[lex.Token]) bool
	// After returns true if the token should be removed based on the following
	// tokens.  The next iterator yields upcoming tokens in forward order
	// (nearest first).
	After(next iter.Iterator[lex.Token]) bool
}

RemovalRule decides whether a token should be removed from the output stream based on the surrounding context. When either Before or After returns true, the token and any insertions that would have been associated with it are omitted.

func RemoveExcessNewlines

func RemoveExcessNewlines() RemovalRule

RemoveExcessNewlines returns a rule that removes a NEWLINE token when it is already preceded by two or more NEWLINEs, collapsing runs of blank lines to at most one blank line.

type TokenWriter

type TokenWriter struct {
	// contains filtered or unexported fields
}

TokenWriter is a simple mechanism for writing tokens to an output stream.

func NewTokenWriter

func NewTokenWriter(out io.Writer, runes []rune) TokenWriter

NewTokenWriter constructs a new token writer for tokens generated from the given source file.

func (*TokenWriter) Flush

func (p *TokenWriter) Flush() error

Flush the writer to the original output stream.

func (*TokenWriter) String

func (p *TokenWriter) String(token lex.Token) string

String extracts the text string corresponding to a give span in the original source file.

func (*TokenWriter) WriteTokens

func (p *TokenWriter) WriteTokens(tokens ...lex.Token) error

WriteTokens writes the tokens to the output writer exactly as is. This returns an error if some issue arises whilst writing the string.

Jump to

Keyboard shortcuts

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