formatter

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Comment rendering model.

Comments are first-class tokens in the stream. A comment renders by one of two rules, decided by line arithmetic — never by attachment:

  • a comment on the same source line as the previous real token renders inline after it (sameLineComment): a space, the comment text, and — for line comments and annotations — a hard line owning its line end;
  • a comment on its own line renders on its own line (ownLineComment): a soft line (collapsing when the output already ended the line), the blank lines before it, the comment text, and a hard line.

The emitter (emitTokens) and the structural sites call the helpers in this file; nothing else inspects comment positions. The same-line run predicates (hasSameLineComments, sameLineEndsLine) and the alignment group checks (commentBreaksGroup, nameOnlyComment) mirror the rendering rules, so a comment's layout effect is always the one it would have in the output.

Package formatter formats parsed Thrift documents and files. Format is the pure formatting core used by callers such as the CLI and LSP; FormatFile owns the filesystem boundary for standalone file formatting.

Layout decisions are width-driven: every construct is a group that stays on one line when it fits and breaks otherwise, with nested groups deciding independently based on the remaining width at their position.

Index

Constants

This section is empty.

Variables

AllConstructs lists every construct, in config order.

Functions

func BuildIR

func BuildIR(d *syntax.Document, o Options) doc.Doc

BuildIR builds the document IR for the given options, from a fresh arena: the IR outlives the call and can be inspected with doc.Dump before printing; the printer mutates groups in place, so dump after PrintIR to see the layout decisions.

func Format

func Format(d *syntax.Document, o Options) (string, error)

Format renders the whole document. The arena is pooled: the returned string is the only thing that outlives the call.

func FormatFile added in v0.2.0

func FormatFile(file string, opts FileOptions) error

FormatFile reads and formats file. It writes formatted output to Output by default, overwrites file when Write is true, and writes a unified diff when Diff is true. Write takes precedence over Diff. File permissions are preserved when overwriting an existing file.

func FormatNode

func FormatNode(d *syntax.Document, n syntax.Node, o Options) (string, error)

FormatNode renders a single node with its comments, for hover previews and similar snippets.

func PrintIR

func PrintIR(ir doc.Doc, o Options) (string, error)

PrintIR prints the document IR.

Types

type AlignMode

type AlignMode uint8

AlignMode controls column alignment of struct-like bodies and enum values.

const (
	// AlignField aligns the id, requiredness, and type columns of fields.
	AlignField AlignMode = iota
	// AlignAssign aligns the '=' sign of fields and enum values that have
	// default values.
	AlignAssign
	// AlignDisable disables alignment.
	AlignDisable
)

type Break added in v0.1.7

type Break = PerConstruct[*bool]

Break configures layouts that are forced multiline per construct. A nil value is unset.

type Construct

type Construct int

Construct identifies one formatting construct that per-construct options apply to: the container bodies (structs, unions, exceptions, enums, arguments, throws) and the collection types (lists, maps, sets).

const (
	ConstructStruct Construct = iota
	ConstructUnion
	ConstructException
	ConstructEnum
	ConstructArguments
	ConstructThrows
	ConstructList
	ConstructMap
	ConstructSet
)

func (Construct) String

func (c Construct) String() string

String returns the config key of the construct.

type FileOptions added in v0.2.0

type FileOptions struct {
	Output   io.Writer
	Write    bool
	Diff     bool
	Base     FormatPatch
	Override FormatPatch
}

FileOptions controls file-level formatting. Output is required unless Write is true. Base is the already-resolved file or project config (empty means defaults); Override is the CLI patch applied on top of it. The caller owns config discovery, so the formatter stays pure I/O plus layout.

type FormatPatch added in v0.1.7

type FormatPatch struct {
	PrintWidth *int        `json:"printWidth"`
	Indent     *Indent     `json:"indent"`
	TabWidth   *int        `json:"tabWidth"`
	Align      *string     `json:"align"`
	Separators *Separators `json:"separators"`
	Break      *Break      `json:"break"`
}

FormatPatch is a partial formatting configuration; nil fields are unset, so layered sources (defaults, config file, CLI flags, workspace settings) override each other field by field.

func DefaultFormatPatch added in v0.1.7

func DefaultFormatPatch() FormatPatch

DefaultFormatPatch returns the default formatting configuration as a fully-set patch.

func (FormatPatch) Apply added in v0.1.7

func (p FormatPatch) Apply(base FormatPatch) FormatPatch

Apply overlays p onto base: every set field of p replaces the corresponding field of base.

func (FormatPatch) Options added in v0.1.7

func (p FormatPatch) Options() (Options, error)

Options converts the patch to formatter options, validating first.

func (FormatPatch) Validate added in v0.1.7

func (p FormatPatch) Validate() error

Validate checks every set field for validity.

type Indent added in v0.1.7

type Indent struct {
	Value string // the indentation string, spaces or tabs
	Width int    // display width of one level
}

Indent is a resolved indentation: the string emitted for one level and its display width. It is set from a literal string of spaces or tabs.

func ParseIndentValue added in v0.1.7

func ParseIndentValue(s string) (Indent, error)

ParseIndentValue resolves a literal indent string:

"  "   literal spaces, used as written
"\t"   literal tabs, used as written

An empty spec yields the default of four spaces.

func (*Indent) UnmarshalJSON added in v0.1.7

func (i *Indent) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a literal string of spaces or tabs.

type Options

type Options struct {
	// PrintWidth is the target line width. Must be positive.
	PrintWidth int
	// Indent is the string emitted for one indentation level.
	Indent string
	// TabWidth is the display width of one indentation level. Must be
	// positive.
	TabWidth int
	// Align controls column alignment (default AlignField).
	Align AlignMode
	// Separator controls trailing separators per construct (default
	// SeparatorPreserve).
	Separator PerConstruct[SeparatorMode]
	// Break forces the multiline layout per construct, even when the body
	// fits on one line.
	Break PerConstruct[bool]
	// NoTrailingNewline suppresses the final newline that is otherwise
	// appended to the formatted output.
	NoTrailingNewline bool
}

Options controls formatting behavior. Zero values mean defaults.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the default formatting options.

type PerConstruct

type PerConstruct[T any] struct {
	Structs    T `json:"structs"`
	Unions     T `json:"unions"`
	Exceptions T `json:"exceptions"`
	Enums      T `json:"enums"`
	Arguments  T `json:"arguments"`
	Throws     T `json:"throws"`
	Lists      T `json:"lists"`
	Maps       T `json:"maps"`
	Sets       T `json:"sets"`
}

PerConstruct holds one option value per construct. The JSON tags make the per-construct option maps config-compatible ("structs", "arguments", ...), so the config layer and the CLI share this single source of truth.

func (PerConstruct[T]) Get

func (p PerConstruct[T]) Get(c Construct) T

Get returns the value for the construct.

func (*PerConstruct[T]) Set

func (p *PerConstruct[T]) Set(c Construct, v T)

Set assigns the value for the construct.

type SeparatorMode

type SeparatorMode uint8

SeparatorMode controls trailing separators after fields, enum values, and function signatures.

const (
	// SeparatorPreserve keeps the original separators as written (',', ';',
	// or none).
	SeparatorPreserve SeparatorMode = iota
	// SeparatorComma adds a trailing comma everywhere.
	SeparatorComma
	// SeparatorSemicolon adds a trailing semicolon everywhere.
	SeparatorSemicolon
	// SeparatorNone removes all trailing separators.
	SeparatorNone
)

type Separators added in v0.1.7

type Separators = PerConstruct[*string]

Separators configures trailing separators per construct. A nil value is unset.

Jump to

Keyboard shortcuts

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