Documentation
¶
Overview ¶
Package printer renders an ast.File (or an individual ast.DeclAny) back to protobuf source text. It is designed for two distinct uses:
Round-trip fidelity: replay parsed source verbatim, preserving the original whitespace, comments, and structure exactly as written.
Formatting: apply layout decisions and optional AST transforms to produce canonicalized output.
Entry points ¶
PrintFile renders an entire file; this should be the usual entry point. Print renders a single declaration as a snippet with no trailing newline — useful for LSP edit previews or for building output incrementally one decl at a time.
Both entry points take an Options value that configures the printed output:
With Options.Format = false (the zero value, round-trip mode), the file is emitted as-is. Source whitespace and comments are preserved verbatim from the token trivia attached during parsing. Options.Formatting is ignored in this case.
With Options.Format = true (format mode), Options.Formatting drives layout decisions and formats the printed ouptut.
Formatting presets ¶
Format mode is configured via Formatting. Two ready-made presets are provided:
Default is the recommended preset: dynamic layout that respects source intent (e.g. a scope written flat stays flat; width-aware breaking kicks in at 100 columns), and no rewriting of comment text.
Legacy is the set of configurations that conforms to the legacy protobuf formatter.
See the Formatting type for the individual knobs.
Editing the AST ¶
To mutate the AST before rendering (insert, delete, or move declarations), use the companion github.com/trendvidia/protocompile/ast/edit package. Apply edits first, then call PrintFile on the resulting file.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Print ¶
Print renders a single declaration to protobuf source text as a snippet. The result has no trailing newline, leaving the caller to manage spacing between snippets.
When decl is a top-level declaration, the output includes the detached leading trivia at its source position (e.g. a section comment that preceded it). Nested declarations (inside a message body, for example) emit their attached leading trivia only — Print has no broader file context for resolving the surrounding body scope's detached slot.
func PrintFile ¶
PrintFile renders an ast.File to protobuf source text.
Behavior is controlled by Options:
Options.Format = false (round-trip mode): the file is emitted as-is, with source whitespace and comments preserved verbatim from token trivia.
Options.Format = true: AST transforms and layout decisions run. See Formatting for the configurable knobs; Default and Legacy are ready-made presets.
To apply mutations to the AST before rendering, use the companion github.com/trendvidia/protocompile/ast/edit package and pass the resulting file to PrintFile.
Types ¶
type Formatting ¶
type Formatting struct {
// MaxWidth is the column budget for flat-vs-broken layout
// decisions: [dom.Group] breaks a group whose flat width exceeds
// this value. Consulted wherever the printer wraps content in
// [dom.Group]. Zero is treated as unset and replaced by the
// default; set to [math.MaxInt] explicitly to disable width-based
// breaking.
//
// Default: 100.
// Legacy: [math.MaxInt] (the legacy formatter makes no width-based
// layout decisions).
MaxWidth int
// TabstopWidth is the number of spaces in a single indentation
// level, used by [dom.Indent]. Zero is treated as unset and
// replaced by the default.
//
// Default: 2. Legacy: 2.
TabstopWidth int
// BodyLayout selects how decl-bearing body scopes (`{ ... }`)
// decide between flat and broken layout. Applies uniformly to
// message, enum, service, oneof, extend, and RPC-method bodies.
//
// Default: [LayoutDynamic]. Legacy: [LayoutStrict].
BodyLayout LayoutStrategy
// LiteralLayout selects how literal expression scopes decide
// between flat and broken layout. Applies uniformly to compact
// options, array literals, and dict (message) literals.
//
// Default: [LayoutDynamic]. Legacy: [LayoutStrict].
LiteralLayout LayoutStrategy
// CanonicalizeFileOrder applies a canonical multi-tier ordering
// to top-level file declarations:
//
// 1. syntax / edition
// 2. package
// 3. imports (alphabetized; `import option` after regular
// imports per Edition 2024)
// 4. file-level options (plain before extension, alphabetized
// within each subgroup)
// 5. everything else, in source order
//
// Default: true. Legacy: true.
CanonicalizeFileOrder bool
// RewriteTrailingLineCommentsToBlock controls how the printer
// handles trailing `//` line comments in "tight" contexts —
// positions where a `//` would consume a following inline token
// (paths, single-option compact-options values, option values
// before `;`, and the close-bracket of a dict-field-value scope).
//
// When true, trailing `//` comments in those tight contexts are
// rewritten as `/* ... */` (with `*/` in the body escaped to
// `* /` to keep the synthesized block comment sound), as are
// leading `//` comments that render inline after code. Trailing
// `//` comments in safe positions (where the next token is on a
// new line) are left as `//`. Matches the legacy formatter's
// behavior and modifies user comment text as a side effect.
//
// When false, trailing `//` comments are emitted verbatim. If
// the layout would otherwise render a scope flat such that a `//`
// trailing would consume following inline content, the layout
// falls back to broken for that scope instead.
//
// Default: false. Legacy: true.
RewriteTrailingLineCommentsToBlock bool
// NormalizeBlockComments rewrites the interior whitespace of
// multi-line `/* ... */` comments to a canonical form.
//
// When true, the prefix-style normalization algorithm runs on
// every multi-line block comment: if the first interior line
// begins with a non-alphanumeric character (e.g. `*`) and every
// later line begins with the same character, strip per-line
// whitespace and re-emit with one space before the prefix
// character. Otherwise unindent by the minimum shared indent and
// re-indent with three spaces, preserving relative indentation.
// Matches the legacy formatter's behavior and modifies user
// comment text as a side effect.
//
// When false, multi-line block comments are emitted with their
// interior whitespace preserved verbatim from source.
//
// Default: false. Legacy: true.
NormalizeBlockComments bool
// TrailingBlockCommentsOnNewLine controls placement of trailing
// `/* ... */` comments when the surrounding bracket scope is
// rendered multi-line.
//
// When true, trailing block comments are emitted on their own
// line after the value, separated from the value vertically.
// Matches the legacy formatter's behavior; also covers compound-
// string interior block comments.
//
// When false, trailing block comments stay inline with their
// value on the same line.
//
// Default: false. Legacy: true.
TrailingBlockCommentsOnNewLine bool
// PairLeadingBlockComments controls placement of leading
// `/* ... */` comments on elements inside an expanded scope (an
// element of an array or dict literal that has been broken
// multi-line).
//
// When true, a leading block comment is rendered on the same line
// as its element (`/* Before */ {rule: "child"}`). Matches the
// legacy formatter's behavior.
//
// When false, the comment is placed on its own line above the
// element.
//
// Default: false. Legacy: true.
PairLeadingBlockComments bool
}
Formatting groups options that drive formatting behavior. Each field corresponds to a specific decision the printer makes during AST transforms or emission.
Two presets are provided: Default (the recommended modern behavior) and Legacy (byte-for-byte compatibility with the legacy protobuf formatter). Construct a zero value directly only when opting out of every default-true knob is intended; otherwise start from a preset.
func Default ¶
func Default() Formatting
Default returns the recommended Formatting options for new callers:
printer.PrintFile(printer.Options{
Format: true,
Formatting: printer.Default(),
}, file)
Compared to Legacy, Default uses LayoutDynamic for body and literal scopes (preserving source intent for flat-vs- broken decisions) and disables the four comment-rewriting and comment-repositioning knobs that the legacy formatter enabled.
func Legacy ¶
func Legacy() Formatting
Legacy returns Formatting options that reproduce the legacy protobuf formatter (`buf format`) byte-for-byte. Use this preset for drop-in replacement of the legacy formatter:
printer.PrintFile(printer.Options{
Format: true,
Formatting: printer.Legacy(),
}, file)
For new code, prefer Default — see its docstring for the differences.
Where `buf format` (1.74) deletes a comment, Legacy keeps it, so the output can differ there:
- A comment before a message-literal comma that formatting elides, `foo: "goo" /* c */, // t`: buf drops `/* c */`; Legacy prints it on its own line before the next element.
type LayoutStrategy ¶
type LayoutStrategy int
LayoutStrategy controls how a scope (a syntactic construct that can be rendered flat on one line or broken across multiple lines, e.g. a message body, compact-options bracket, array literal, dict literal, or RPC signature) decides between flat and broken layout.
const ( // LayoutDynamic preserves source intent as the baseline and lets // the dom layer enforce the width budget on top: // // - If the source had this scope flat (no newline between open // and close), the printer keeps it flat — unless its flat // width exceeds [Formatting.MaxWidth], in which case dom // breaks it. // // - If the source had this scope broken (any newline between // open and close), the printer keeps it broken regardless of // width. // // Whitespace is tightened within whichever shape applies, but // the flat/broken decision respects what the user wrote. LayoutDynamic LayoutStrategy = iota // LayoutStrict applies hardcoded shape rules per scope type, // regardless of source structure or width. Matches the legacy // protobuf formatter. LayoutStrict )
type Options ¶
type Options struct {
// Formatting controls behavior in format mode. Honored only when
// [Options.Format] is true. Start from a preset such as [Default]
// or [Legacy] and override individual fields as needed.
Formatting Formatting
// Format enables AST transforms and layout decisions driven by
// [Options.Formatting]. When false, [Options.Formatting] is
// ignored and the printer round-trips the AST as-is: source
// whitespace is preserved verbatim from token trivia.
Format bool
}
Options controls the printer's overall behavior.