Skip to main content

Crate gdscript_fmt

Crate gdscript_fmt 

Source
Expand description

gdscript-fmt — the GDScript source formatter (Phase-6 Workstream 3).

Internal layer (not a stable API). Depend on gdscript-ide (the public surface); the items here may change between releases.

A pure fn(source, &FmtConfig) -> String: no engine model, no filesystem, wasm32-safe. It re-emits the lexer/pre-pass token stream, normalizing block indentation (to the configured unit), trailing whitespace, and the final newline — every significant token (keywords, identifiers, literals — including multi-line strings, which are single tokens) is emitted verbatim, so meaning cannot change.

It also normalizes intra-line spacing (Phase-4 increment A): one space around binary operators / assignments / -> / :=, after , and : (in type-annotation and dict contexts), hugged brackets (f(x, y), [1, 2]), tight member access (a.b), and tight unary -x. The decision is purely local (previous significant token + innermost bracket), and the genuinely ambiguous contexts — slice colons arr[a:b], and node-path sigils $Node/Path / %Unique (where a stray space around / would silently change meaning without changing the token sequence) — are left verbatim / kept tight by a small node-path state machine.

Safe by construction. In safe_mode (the default) the formatter (a) refuses to touch a file with syntax errors, and (b) re-lexes its own output and falls back to the original if the significant token sequence changed. So it never corrupts code, even input it doesn’t fully understand. The result is idempotent: format(format(x)) == format(x).

It also performs length-driven line reflow (Phase-4 increment C): a single-line statement that exceeds line_width and contains a bracketed group is wrapped flat → compact → exploded via a small Doc-IR, matching gdformat and preserving the token sequence. The remaining gdformat behaviours (magic trailing comma, operator-chain paren injection, quote normalization) are token-mutating and documented in DEVIATIONS.md.

Structs§

FmtConfig
Formatter options. Defaults match the Godot convention (tabs) and keep the safety net on.
RangeEdit
A single whole-line replacement edit produced by format_range.

Functions§

format
Format source, returning the tidied text. In safe_mode (the default) this returns source unchanged rather than risk a meaning-changing edit (a syntax error in the input, or output whose significant tokens differ from the input’s).
format_range
Format only the part of source overlapping the byte range sel (for editor “format selection” / LSP textDocument/rangeFormatting). The whole document is formatted for correct structure and indentation; the result is the minimal changed line-hunk that intersects sel, or None if nothing in the selection’s lines changes. Applying the edit yields the same bytes the whole-file [format] would have produced for that region.