Repository navigation
fix!: bean-format byte-compat + LSP encoding / parser BOM / FFI v2 - #1244
Merged
Merged
Conversation
rledger format and Python bean-format produced divergent layouts, so a file touched by both tools churned in editors and CI. Rework the formatter into a two-phase, file-wide aligner and default to bean-format's auto-width. - Phase 1 renders each directive to a Vec<FormatLine> (Plain | Aligned); Phase 2 resolves column widths across the whole file and emits. - Default alignment is now Auto (matches bean-format's default); -c <col> selects fixed currency-column mode. A file formatted by either tool is a fixed point of the other. - LSP shares the core path: resolve_alignment fixes file-wide widths once, then per-line TextEdits align to those columns, so editor output matches rledger format byte-for-byte while preserving the per-line edit model. BREAKING CHANGE: default `rledger format` output changes from fixed column-60 to auto-width. Pass `-c 60` to restore the old layout. Tests: golden output, idempotence/fixed-point on a corpus, and live bean-format (beancount 3.2.3) parity via the podman compat image. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs main branch (2026-06-01)
What do these numbers mean?
|
Contributor
There was a problem hiding this comment.
Pull request overview
This PR updates rustledger’s formatting pipeline to match Python bean-format byte-for-byte by switching to file-wide (two-phase) amount alignment and making auto-width alignment the default, with the LSP path sharing the same alignment geometry.
Changes:
- Introduces a two-phase formatter model (
FormatLinerender phase + whole-file alignment/emit phase) to matchbean-format’s document-wide alignment behavior. - Changes CLI default alignment from fixed column to auto-width (with
-c <col>selecting fixed currency-column mode). - Updates LSP formatting to resolve alignment once per document and apply per-line
TextEdits using the resolved widths; adds new CLI/bean-format parity integration tests and fixtures.
Reviewed changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger/tests/format_compat.rs | Adds golden/idempotence and live bean-format fixed-point parity tests. |
| crates/rustledger/tests/fixtures/format/issue_1242_input.beancount | Adds the misformatted repro fixture for #1242. |
| crates/rustledger/tests/fixtures/format/issue_1242_c60.expected | Adds expected output fixture for -c 60 mode. |
| crates/rustledger/tests/fixtures/format/issue_1242_auto.expected | Adds expected output fixture for default auto-width mode. |
| crates/rustledger/src/cmd/format.rs | Switches CLI formatter to render FormatLines and align file-wide; changes -c to optional. |
| crates/rustledger/src/cmd/doctor/roundtrip.rs | Updates doctor roundtrip formatting to use the new default config. |
| crates/rustledger-lsp/src/handlers/utils.rs | Updates LSP formatter config documentation to reflect new alignment model. |
| crates/rustledger-lsp/src/handlers/formatting.rs | Resolves alignment document-wide once, then formats postings using resolved widths. |
| crates/rustledger-lsp/src/handlers/execute_command.rs | Updates align-amounts command docs/tests to assert document-wide alignment behavior. |
| crates/rustledger-core/src/lib.rs | Re-exports the new alignment/rendering surface (Alignment, FormatLine, etc.). |
| crates/rustledger-core/src/format/transaction.rs | Refactors transaction/posting formatting to produce FormatLines for file-wide alignment. |
| crates/rustledger-core/src/format/mod.rs | Updates FormatConfig to use Alignment and adds directive line-render APIs. |
| crates/rustledger-core/src/format/directives.rs | Refactors directive formatters into _lines render phase plus wrappers. |
| crates/rustledger-core/src/format/align.rs | Adds the new whole-file alignment resolver and renderer. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Closes the architectural gap exposed during deep review of PR #1244: only the CLI and LSP were migrated to whole-file two-phase alignment; every other format consumer (WASM, FFI, extract, add, synthetic, roundtrip) was still looping the per-directive self-aligning `format_directive`, which after the default flip from `CurrencyColumn(60)` to `Auto` produced ragged, divergent output. The fix routes every caller through one of two canonical APIs: * `rustledger_core::format::format_directives(&[&Directive], &FormatConfig)` for directive lists with no surrounding source (extract, add, synthetic, doctor/roundtrip, FFI entry/entries). * `rustledger_parser::format_source(source, &ParseResult, &FormatConfig)` for whole-file formatting that preserves comments, blank lines, options/includes/plugins, and trailing newlines (CLI, LSP, WASM, FFI format.source/format.file). The old self-aligning `format_directive` is deleted so no future caller can reintroduce the per-directive footgun. The LSP now delegates to `format_source` and emits a single minimal contiguous line-diff edit; parity with `rledger format` is by construction. FFI `handle_format_source` no longer hand-rolls option/plugin emission, which previously silently dropped comments and includes. Cross-path identity test (`cli_matches_format_source_direct`) pins that the CLI binary bytes equal a direct `format_source` call across the corpus, in both auto and `-c 60` modes. Live bean-format parity (podman) remains green. Drive-by: fix a pre-existing rustdoc unresolved-link in `rustledger-wasm::types::MetaValueTagged` introduced by PR #1241 that was blocking `RUSTDOCFLAGS=-Dwarnings cargo doc`. Verified: workspace clippy -D warnings clean, fmt --check clean, cargo doc -Dwarnings clean, full `cargo test --workspace --all-features` green (zero failures), and all 7 format_compat tests including bean-format parity. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…p dead trim Two Copilot review findings on PR #1244: 1. `format_source` dropped trailing blank lines when the last item was a standalone comment, options, include, or plugin. The lexer's `;[^\n\r]*` regex (and the parser's option/include/plugin spans) exclude the terminating newline, so `source[prev_end..]` held the file's trailing blanks but was never processed. Directives masked the bug because their spans capture trailing newlines and the in-match walk-back already accounted for them. Fix: after the items loop, process `source[prev_end..]` with the same "first newline is the previous item's terminator, extras are blank lines" rule used between items. The directive case stays correct because the in-match walk leaves `prev_end == source.len()` and the trailing slice is empty. 2. The `Comment` arm's `.trim_end_matches('\n')` was dead code (comment spans never contain a newline). Dropped, with the doc comment rewritten to cite the lexer regex. Regression tests pin both behaviors: `preserves_trailing_blank_lines_after_comment` and `preserves_trailing_blank_lines_after_option`. Also regenerates `crates/rustledger-wasm/bindings/{index.schema.json,types.py}` to absorb the `MetaValue` doc-link fix from the previous commit, which the Wire-format bindings freshness CI check requires. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phase 1 — correctness (severe):
1, 2. LSP `minimal_diff_edit` no longer emits malformed `TextEdit` ranges
(range.end < range.start) when the source lacks a trailing newline or
when only the trailing-newline count differs. Rewritten as a byte-based
diff over the longest common UTF-8-safe prefix and suffix, with LSP
positions computed in UTF-16 code units (LSP 3.17 default). Non-ASCII
content now round-trips correctly. Probes that previously yielded
malformed/no-op edits are pinned as regression tests.
3. FFI `handle_format_source` / `handle_format_file` now gate on parse
errors, matching CLI/LSP/WASM. Without the gate, `format_source`
silently dropped unparsable content and FFI callers had no way to
detect it. Returns a `parse_error` RpcError with the first 3 error
messages summarized.
4. `doctor roundtrip` now bails on parse errors instead of running
`format_directives` over the partial parse and reporting SUCCESS on
count equality. Also switched to `format_source` (the path the CLI
uses) so the diagnostic measures what users actually invoke. New
`byte-stable: YES/NO` line and `PARTIAL` outcome when bytes differ
but structure is preserved.
Phase 1 — additional correctness:
8. `format_source` skips `Spanned::synthesized` directives (file_id ==
SYNTHESIZED_FILE_ID, Span::ZERO). Without the filter they sort to the
top of the file regardless of where the caller placed them in the
Vec, since stable-sort on collision-key 0 preserves only insertion
order.
9. `format_source` no longer collapses blank-only files (e.g.
"\n\n\n\n") to a single "\n". The trailing-gap block now runs even
when no items were rendered.
Phase 2 — architecture:
7. `rangeFormatting` now routes through `format_document` (the canonical
`format_source` path) and filters returned edits by line range,
instead of using its own per-line indent heuristics. Parity-by-
construction with the CLI now covers both LSP formatting requests.
10. `format_directives` separator policy is documented explicitly:
no blank line is inserted between adjacent directives; callers
needing inter-directive blanks should compose at the
`format_directive_lines` + `render_lines` level (extract_cmd is the
canonical example).
11. LSP `format_document` no longer returns `None` for files with parse
errors. A `fallback_cleanup_edits` pass emits per-line tab→spaces
and trailing-whitespace edits on lines unaffected by the broken
directive — preserving the pre-PR "format-on-save still does
something useful" behavior.
12. LSP emits per-hunk edits when the changed region has the same line
count on both sides (the common case for indent/alignment changes),
preserving editor cursor and undo granularity around unchanged
regions. Falls back to a single contiguous edit when line counts
differ.
Phase 3 — quality:
13. The #1142 interleaved-metadata regression test grew a positive
assertion that the misaligned posting indent is actually normalized
(currency columns line up across postings), guarding against a
degenerate no-op formatter that would have passed the
metadata-preservation check alone.
14. `format_posting_line` doc-comment is now explicit that it's
self-aligned only and not equivalent to what
`format_directives`/`format_source` write.
15. Replaced the tautological `cli_matches_format_source_direct` test
(which compared the CLI to `format_source` — but the CLI literally
calls `format_source`) with a real cross-aggregator check:
`format_source` (CLI path) must agree with `format_directives`
(core path) on a directives-only corpus where neither aggregator
has anything to disagree about.
All 7 format_compat tests pass including live bean-format parity
(podman); workspace test suite green; clippy -D warnings clean; cargo
doc -Dwarnings clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address the 15-finding second deep review and replace hand-rolled LSP
position math and line-diff with library primitives (ropey, similar) on
review feedback.
LSP correctness:
1, 3. `surface_cleanup_edits` (new) preserves CRLF line endings and only
replaces *leading* tabs. The previous `fallback_cleanup_edits` used
`line.trim_end()` (stripping `\r` as Unicode whitespace) and
`line.replace('\t', " ")` (eating tabs inside string literals).
Tests pin both behaviors.
2, 9. `rangeFormatting` now clips canonical edits to the actual selected
byte range using half-open `[start, end)` semantics — matching what
editors (VS Code, Helix) send. Multi-line canonical edits no longer
spill outside the user's selection.
6, 7, 8. `format_document` is now canonical-only: returns `None` on
parse errors. `handle_formatting` opts into `surface_cleanup_edits`
as a fallback; `handle_align_amounts` and `handle_range_formatting`
deliberately do not — alignment-named commands return a "cannot
align" message on broken parse instead of silently mutating
whitespace under their name.
12. `handle_align_amounts` doc no longer claims delegation to
`format_posting_line` (stale since the canonical refactor).
doctor / multi-file:
4. `doctor roundtrip` walks the include graph via the Loader's
`SourceMap` and runs the canonical `format_source` per file,
classifying each as `[stable]`, `[reflow]`, or `[MISMATCH]`. Multi-
file ledgers are no longer silently treated as single-file.
5. Strips a leading UTF-8 BOM before parsing so editor-added BOMs don't
cause a spurious "round-trip aborted: parse errors" exit.
parser:
10, 11. `format_source` docstring spells out the contract: parse_result
MUST come from `parse(source)`. Synthesized directives
(`SYNTHESIZED_FILE_ID`) are filtered; non-directive items
(options/includes/plugins/comments) carry no `file_id` and are
assumed source-derived. Callers wanting to format a directive list +
synthesized extras should compose at `format_directive_lines` +
`render_lines` level via `rustledger_core::format::format_directives`.
FFI / test quality:
13. `handle_format_source` and `handle_format_file` share a new
internal `format_source_to_response` helper. The JSON re-
serialization round-trip (which contained an `unwrap()` latent
panic across the WASI boundary) is gone.
14. `cli_matches_format_directives_on_directives_only_corpus` now
asserts the filtered input parses to the same directive count as
the original corpus entry — prevents the test passing on a future
filter accident that produces degenerate input.
15. `lsp_position_to_byte` and `byte_to_lsp_position` are now in
`handlers::utils`, used by every test helper and production caller.
No more duplication.
Library swaps (on review feedback that we were hand-rolling too much):
* LSP position ↔ byte offset conversion now uses `ropey` (already a
workspace dep), replacing two hand-rolled UTF-16 walks.
* Line-based diff for `minimal_diff_edits` now uses
`similar::TextDiff::from_lines` (Myers diff), replacing the
hand-rolled byte-prefix/suffix + per-hunk algorithm. `similar` was
already a transitive dep via `insta`; promoted to a direct
dependency.
Verify suite green: workspace clippy `-D warnings`, fmt `--check`,
`RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps`, full
`cargo test --workspace --all-features`.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ard cases
Address all 16 findings from the second deep review. On review feedback
"use best-in-class libraries to solve difficult edge cases", several
hand-rolled subsystems are replaced with established crates.
LSP correctness (severe / buffer-corruption fixes):
1. `minimal_diff_edits` now uses `similar::TextDiff::ops()` (structured
`DiffOp` API with explicit `old_range` / `new_range` byte-indexed
line ranges) instead of a hand-rolled state machine over
`iter_all_changes()`. The state machine corrupted the buffer on any
pure insertion: probe-confirmed `"a\nb\n" → "a\nX\nb\n"` produced
`"X\na\nb\n"` (X went to BOF). Three regression tests pin the fix.
2. `clip_edit_to_range` was replaced with `edit_inside_range`: the LSP
convention "rangeFormatting returns only edits fully inside the
selection" is the only architecturally sound choice — slicing the
reformatter's output by source byte counts produces semantically
wrong content when the canonical formatter changes column positions.
Tests confirm canonical edits straddling the boundary are dropped;
zero-width edits at boundaries are kept.
3. `ropey` is now pinned to `default-features = false, features =
["cr_lines", "simd"]`. With default features ropey treats
NEL/VT/FF/LS/PS as line breaks; `similar::TextDiff::from_lines`
splits on LF/CRLF/bare-CR only. The disagreement caused wrong byte
ranges for any source containing those Unicode line-break chars.
LSP edge cases:
7. Half-open range filter accepts zero-width edits at the selection
boundary (a pure insertion at byte == range_start is semantically
inside the selection). Regression test added.
8. `lsp_position_to_byte` now correctly handles `Position(line ==
line_count, character == 0)` — the LSP-spec end-of-document
position — by returning `rope.len_bytes()` instead of clamping to
the last line's end.
9. `clean_line` normalizes pathological `"...\r\r"` to a single trailing
`\r` via `trim_end_matches('\r')` instead of `strip_suffix` once, so
trailing whitespace before the embedded CR is correctly stripped.
Also switched to `out.trim_end_matches([' ', '\t', '\r']).len()` +
`truncate` (O(n)) replacing the `chars().next_back()` loop (O(n²)
worst case).
10. `handle_execute_command` returns a new `ExecuteCommandResponse`
struct carrying both the JSON response and an optional
`ShowMessageParams` notification. `handle_align_amounts` now
surfaces "Cannot align: source has N parse error(s)" via
`window/showMessage` so VS Code and other clients actually display
it (executeCommand has no spec-defined way to carry textual
errors). main_loop dispatcher sends the notification alongside the
response.
11. `byte_to_lsp_position` and `lsp_position_to_byte` each grew a
rope-accepting variant (`rope_byte_to_lsp_position`,
`rope_lsp_position_to_byte`). Hot callers (`minimal_diff_edits`,
`handle_range_formatting`) build the rope once at the top and
thread it through, eliminating the O(K·N) per-call rope
construction the previous review flagged.
12. The `.expect("Delete has old_index")` is gone — the new `DiffOp`
API exposes byte ranges directly, no Option to unwrap.
doctor / parser:
4, 5, 6, 13. `cmd_roundtrip` rewritten:
* BOM stripping moved to the parser's lexer
(`#[logos(skip r"\u{FEFF}")]`) — the doctor no longer needs a
bespoke strip helper, and the CLI/LSP/FFI/WASM all benefit
transparently (a BOM'd file is now invisible to every consumer).
* `Loader::new().with_path_security(true)` confines the include graph
to the entry file's tree — a malicious ledger with
`include "/etc/passwd"` can no longer make the doctor read outside
the user's selection.
* Errors are split by variant: `LoadError::ParseErrors` aborts;
infrastructure errors (cycles, glob no-match, IO) are advisory and
the per-file round-trip continues on files that did load.
* BOM regression test in the parser pins the new
transparent-skip behavior (replacing the prior
test_bom_produces_invalid_token_error).
14. `cmd_roundtrip` gains 5 regression tests
(`stable_single_file_reports_success`,
`bom_prefixed_file_does_not_abort`,
`multi_file_include_graph_walked`,
`glob_no_match_continues_with_advisory`,
`parse_errors_abort`) covering the rewrite paths.
FFI:
15. `format_source_to_response` returns a single-line message and
attaches the full list of errors as a structured `data: { errors:
[...] }` field on the `RpcError` per JSON-RPC 2.0 — log-friendly
message text, structured access for clients that want
per-error inspection. `RpcError::with_data` builder added.
16. `line_byte_range` is gone — `minimal_diff_edits` constructs a
single rope at the top and threads it through (covered by #11).
Library swaps summary (the "don't reinvent the wheel" theme):
* Line-based diff: hand-rolled state machine → `similar::DiffOp::ops()`
(Myers diff over lines, byte-range-indexed).
* LSP position math: hand-rolled UTF-16 walks → `ropey` (pinned to
cr_lines feature for line-break parity with similar).
* Showing messages from executeCommand: hand-rolled "stuff a message
in JSON" → `lsp_types::ShowMessageParams` notification via main_loop.
* Structured JSON-RPC error data: hand-rolled multi-line message
string → JSON-RPC `data` field with structured payload.
Verify suite green: workspace clippy `-D warnings`, fmt, RUSTDOCFLAGS=
-Dwarnings cargo doc, full cargo test --workspace --all-features.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Severe correctness:
1. Doctor `cmd_roundtrip` now aborts on every LoadError except
GlobNoMatch. Previously Io/PathTraversal/Decryption/IncludeCycle/
GlobError were classified as advisory and the doctor reported
SUCCESS on whatever files DID load — silently hiding format-
instability bugs in unread files. GlobNoMatch alone stays advisory
(intentionally-empty `include "2025/*.bean"` is a real ledger
pattern). New `path_traversal_blocks_diagnosis` regression test.
2. `handle_range_formatting` snaps `range.end` past a trailing `\n`
when the user click+shift-end-selects a line. Editors send
`Position(N, eol_char)` — the byte BEFORE the `\n` — while
canonical line-replacement edits end at the start of line N+1
(one byte past). Without the snap every typical EOL selection
dropped every relevant edit. New
`end_of_line_selection_keeps_line_replace_edit` test.
3. FFI `handle_load_file` opts into `Loader::with_path_security(true)`,
matching the doctor's stance. The FFI is the most security-
sensitive surface (untrusted JSON-RPC callers can pass arbitrary
paths); leaving include resolution unconstrained was inconsistent.
4. `format_source` preserves CRLF line endings AND a leading UTF-8
BOM. `render_lines` always emits LF; format_source now rewrites
the output to match source's line-ending style and re-prepends a
BOM if present, so Windows / Excel exports round-trip
byte-stable through `rledger format`. New regression tests:
`preserves_crlf_line_endings`, `preserves_leading_bom`,
`preserves_bom_and_crlf_together`.
LSP behavior + UX:
7, 11. Sub-line edit precision restored: `narrow_single_line_replace`
strips common UTF-8 prefix/suffix from single-line Replace ops,
so a 1-byte change inside a line emits a 1-byte edit instead of
a full-line replacement. Editor cursors and inline decorations
outside the changed bytes are preserved. Asymmetric-terminator
shapes (pure Insert, pure Delete, tail-of-file) fall through to
line-granular emit so we never invent or drop a terminator.
7 (sort/balance). `handle_sort_transactions` and
`handle_show_account_balance` migrate to `ExecuteCommandResponse`
+ `window/showMessage`, matching what `handle_align_amounts`
already did. The half-migrated convention from the previous
commit is now consistent across all four commands.
9. `clean_line` reverts to `strip_suffix('\r')` (single CR only) and
stops trimming `\r` from the body trailing-whitespace pass.
Surface cleanup must be byte-conservative on parse-error
documents; a paste-in-progress with `...\r\r\n` no longer gets
silently normalized while the user is editing.
12. `handle_range_formatting` reverts the empty-range guard to
`range_end <= range_start → None`. A cursor position (start ==
end) is no longer treated as a selection that could receive a
pure-insertion edit. New `empty_range_is_a_noop` test.
13. Doctor hoists `entry.canonicalize()` above the per-file loop and
threads `entry_parent: Option<&Path>` into `relative_path`. For
N-file include graphs this drops from N canonicalize syscalls to
one.
API contracts and quality:
5. New `show_account_balance_unknown_account_surfaces_show_message`
pins the documented `response=None` + `show_message=Some(...)`
contract for the no-data path.
6, 14. Lexer comment honesty: the `#[logos(skip)]` directive matches
BOM anywhere (not just at start) — the comment now says so. Dead
BOM-error-classification branch in `parser.rs` removed (the lexer
skip means the parser never sees a BOM as an error token).
8. OpenRPC schema documents the new `parse_error` data shape for
`format.source` and `format.file`: `{ errors: string[], total:
number, truncated: boolean }`. Schema-codegen consumers
(TypeScript, Python types) will surface the structured field.
10. FFI parse-error response caps the `errors` array at 100 entries
and exposes `{ errors, total, truncated }` so a pathological
binary fed to `format.file` can't DOS the embedder's transport.
15. New `similar_compact_pass_keeps_replacements_atomic` test pins
that a line replacement emits ONE DiffOp::Replace (not
Delete+Insert). A future similar release that changes the
compact heuristic will surface a clear failure instead of
silently doubling per-hunk edit counts.
Verify suite green: workspace clippy `-D warnings`, fmt,
`RUSTDOCFLAGS=-Dwarnings cargo doc`, full
`cargo test --workspace --all-features`.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Severe correctness:
1. range_formatting EOL snap now handles CRLF. The previous snap only
matched `b'\n'`; on a Windows-encoded ledger the byte at the visual
EOL position is `b'\r'`, not `b'\n'`, so every typical EOL
selection silently dropped its line-replace edit. New
`crlf_end_of_line_selection_keeps_line_replace_edit` test.
2. range_formatting empty-range guard now runs BEFORE the EOL snap.
Cursor on an empty line had `range_end_byte == range_start_byte`
pointing at `\n`; the snap widened it to a 1-byte selection,
bypassing the guard. New `cursor_on_empty_line_does_not_get_widened`
regression test.
3. FFI `format.source` / `format.file` parse errors now use code
-32000 (`BeancountParseError`) — the existing application-level
variant — instead of -32700 (JSON-RPC-reserved "request envelope
was unparsable"). Conflating the two causes JSON-RPC client
libraries to misclassify content errors as transport faults.
New `RpcError::beancount_parse_error` constructor + OpenRPC
schema updated.
API contracts and wire-format:
4. CRLF rewrite in `format_source` first collapses any existing
`\r\n` in the rendered output to `\n` before rewriting every
`\n` to `\r\n`. Defensive: a future renderer or directive Display
impl that emits embedded `\r\n` would otherwise become `\r\r\n`.
The line-ending policy is documented explicitly: CRLF wins on
mixed-ending files; bare-CR (classic Mac) round-trips as LF.
5. FFI `handle_load_file` adds `path_security: bool` parameter
(defaults to `true`). Ledgers that legitimately need cross-tree
includes via `include "../shared/accounts.bean"` can opt out;
default stays safe-by-default. OpenRPC schema declares the new
field.
6. Lexer BOM handling moved from blanket `#[logos(skip)]` to a
`bom_filter` callback that skips only when `lex.span().start ==
0`. Mid-file BOMs (concatenated files, embedded BOM payloads) are
now emitted as `Token::Bom`; the parser's error classifier
surfaces a clear "Invalid token: UTF-8 BOM detected mid-file"
diagnostic so concatenation mistakes don't pass silently. New
`test_mid_file_bom_produces_error` regression test.
Behavior and UX:
9. `handle_sort_transactions` no longer emits a window/showMessage
warning for the `<2 transactions` no-op path. Format-on-save
hooks no longer pop notifications on every save of a single-entry
or empty file.
10. `handle_show_account_balance` argument validation now has tests
pinning the new behavior for missing arg, `null` arg, and
object-shaped arg — all surface a `window/showMessage` warning
so misbehaving clients see the diagnostic.
11. Doctor `cmd_roundtrip` includes a note in the abort output when
`IncludeCycle` is among the blocking errors: "include cycles
now block the doctor (previously advisory). Break the cycle to
enable diagnosis." Explicit hint for users hitting the
behavior change.
Quality:
7, 8. Line-ending policy is fully documented in `format_source`'s
doc-comment (CRLF wins on mixed; bare CR round-trips as LF
because the platform is extinct in practice).
12. `minimal_diff_edits` filters out no-op edits (zero-width range
with empty new_text). similar's compact pass can produce a
Replace whose slices become byte-identical after the
common-prefix/suffix strip; pushing those as TextEdits pollutes
clients that count any returned edit as a dirty-document
signal.
Verify suite green: workspace clippy `-D warnings`, fmt,
`RUSTDOCFLAGS=-Dwarnings cargo doc`, full
`cargo test --workspace --all-features` (zero failures).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Severe correctness bugs (1-3):
1. Parser BOM error classifier uses `error_text.contains('\u{FEFF}')`
instead of `starts_with`. The previous check only fired when the BOM
was at byte 0 of the recovered error span, missing mid-line BOMs
(where `error_text` starts with the directive's date/account). New
`test_mid_line_bom_produces_error` pins the case the previous
classifier silently dropped to "unexpected input". The error
message now mentions "directive body" since the location isn't
necessarily at start.
2. `Token::Bom`'s Display impl emits the visible placeholder `<BOM>`
instead of a literal U+FEFF byte sequence. Any future error-rendering
path that interpolates the token via Display now produces a
human-readable diagnostic instead of three invisible bytes that
silently corrupt copy/paste, GitHub renders, and log aggregation.
3. Mid-file Token::Bom is now layout-transparent in the lexer.
tokenize()'s new explicit `Ok(Token::Bom) =>` arm pushes the token
without resetting at_line_start or last_newline_end. Subsequent
content on the same line keeps its indent classification (so a
concatenated second file's metadata indent isn't swallowed by the
accident-BOM).
API contract clarity (4-5):
4. `format_source_to_response`'s rustdoc updated to match the
implementation: returns `beancount_parse_error` RpcError (-32000,
application-level), NOT `parse_error` (-32700, JSON-RPC reserved
for malformed transport envelope). Doc-vs-code drift introduced in
the previous commit is closed.
5. The lone remaining `Response::parse_error` miscategorization
(jsonrpc/mod.rs's stdin read failure) switched to
`Response::internal_error`. Failing to read from the transport is
a server-side fault (-32603 InternalError), not "I received bytes
that weren't valid JSON" (-32700 ParseError). Per the new docstring
contract, parse_error is now only emitted at sites that genuinely
handle malformed JSON envelope bytes.
UX consistency (6):
6. `handle_sort_transactions`'s "already sorted" path now returns
`ExecuteCommandResponse::none()` to match the silent <2-transactions
path. Format-on-save hooks chained to `rledger.sortTransactions`
no longer pop a notification on every save of a sorted ledger.
Test coverage (7-9):
7. Four new tests pin the sort_transactions silent contract:
`sort_transactions_empty_file_is_silent`,
`sort_transactions_single_transaction_is_silent`,
`sort_transactions_already_sorted_is_silent`, and
`sort_transactions_out_of_order_produces_edit` (positive case).
8. New integration-test crate-level file
`tests/load_file_path_security.rs` (with `tempfile` as a new
dev-dependency) drives `ledger.loadFile` end-to-end through
`process_request`. Three tests pin the
`path_security: bool` parameter's effect:
- default rejects cross-tree includes
- `false` allows them
- explicit `true` matches the default
The polarity-flip bug class (loader's `with_path_security(false)`
semantics silently inverted in a refactor) now surfaces immediately.
9. (covered by the path-security integration tests above, and the
`minimal_diff_edits` no-op-filter has the existing
`similar_compact_pass_keeps_replacements_atomic` test plus the
`sub_line_precision_for_single_byte_change` regression test —
together they exercise the filter on real inputs.)
Type-system invariant (10):
10. `tokenize()` now has an explicit `Ok(Token::Bom) => ...` arm. The
"mid-file BOM emits an error" invariant is enforced at the lexer
layer first (where the token is created and pushed) rather than
purely via parser-side string sniffing on the recovered error
span. A future parser refactor that adds a "skip non-significant
tokens" helper would need to explicitly opt to drop Token::Bom
(visible at the type-system level), not just absorb it
accidentally.
Performance (11):
11. CRLF rewrite in `format_source` short-circuits the defensive
`replace("\r\n", "\n")` pass when `formatted` doesn't contain
`\r`. `render_lines` never emits CR today, so the universal case
drops from O(2N) to O(N). The defensive pass still runs for the
pathological case (a future renderer or directive Display emits
CRLF directly).
Edge case (12):
12. The bare-CR (no trailing LF) rangeFormatting case is documented as
out of scope in `format_source`'s docstring already, so no code
change. The platform is extinct and the LSP layer's silent drop
is consistent with the formatter's silent normalization. Flagged
in the docstring for future readers.
Verify suite green: workspace clippy `-D warnings`, fmt,
`RUSTDOCFLAGS=-Dwarnings cargo doc`, full
`cargo test --workspace --all-features` (zero failures).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
4 tasks done
robcohen
added a commit
that referenced
this pull request
Jun 2, 2026
…rge) Captures the round-18/19/20 deep-review work that was in the working tree of the #1244 PR branch but never committed, so it did not land in the squash-merge. Preserved on its own branch as a starting point for a follow-up PR. Scope (~47 files, +4382/-1084): rustledger-core: - ShiftSpans trait with per-variant binding discipline - HashMap<K, V, S> blanket impl, replacing open-coded shift_metadata rustledger-lsp: - LineIndex with negotiated PositionEncoding (UTF-8/UTF-16) and lazy ropey::Rope (OnceCell, never built under UTF-8) - byte_in_line_to_position helper with strict overshoot rejection - 30+ handlers migrated for encoding-aware positions - DispatchError typed enum replacing prefix-string routing - Duplicate initialize rejection per LSP 3.17 §Lifecycle - BOM CodeAction dedup via BTreeSet<usize> - Currency/account collectors walk parser currency_occurrences index rustledger-parser: - Mid-file BOM tolerated as lexer error preserving following indent - ParseError::every_kind_sample exhaustive via variant_index match rustledger-ffi-wasi: - API_VERSION 1.0 -> 2.0 wire-shape bump (breaking) Verified pre-stash: cargo test --all-features (workspace, zero failures), clippy -D warnings clean, fmt clean, rustdoc clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Jun 2, 2026
…rge) (#1247) Captures the round-18/19/20 deep-review work that was in the working tree of the #1244 PR branch but never committed, so it did not land in the squash-merge. Preserved on its own branch as a starting point for a follow-up PR. Scope (~47 files, +4382/-1084): rustledger-core: - ShiftSpans trait with per-variant binding discipline - HashMap<K, V, S> blanket impl, replacing open-coded shift_metadata rustledger-lsp: - LineIndex with negotiated PositionEncoding (UTF-8/UTF-16) and lazy ropey::Rope (OnceCell, never built under UTF-8) - byte_in_line_to_position helper with strict overshoot rejection - 30+ handlers migrated for encoding-aware positions - DispatchError typed enum replacing prefix-string routing - Duplicate initialize rejection per LSP 3.17 §Lifecycle - BOM CodeAction dedup via BTreeSet<usize> - Currency/account collectors walk parser currency_occurrences index rustledger-parser: - Mid-file BOM tolerated as lexer error preserving following indent - ParseError::every_kind_sample exhaustive via variant_index match rustledger-ffi-wasi: - API_VERSION 1.0 -> 2.0 wire-shape bump (breaking) Verified pre-stash: cargo test --all-features (workspace, zero failures), clippy -D warnings clean, fmt clean, rustdoc clean. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Originally a one-shot fix for
rledger format↔bean-formatbyte divergence (issue #1242). Through 20 rounds of iterative deep review the scope expanded into a broader correctness-and-hardening pass across the formatter, the LSP, the parser, the FFI, and the core span machinery — everything the format-compat work touched, plus everything the reviews kept finding adjacent to it.Changes by area
rledger format— byte-compat with bean-format (the original ask)Vec<FormatLine>(Plain|Aligned{prefix, number, suffix}); Phase 2 resolves column widths across the whole file and emits. The bare number now aligns file-wide, matching howbean-formataligns.Auto(matchesbean-format's default);-c <col>selects the prior fixed-currency-column mode. A file formatted by either tool is a fixed point of the other.resolve_alignmentresolves file-wide widths once into a forced-widthAuto, then per-lineTextEdits align to those columns. Editor output matchesrledger formatbyte-for-byte while preserving the per-line edit model (and [Bug]: Destructive formatting on repeated metadata, LSP-only #1142 metadata preservation).rustledger-lsp— encoding-correct positions across every handlerLineIndexwith negotiatedPositionEncoding— every handler that emits aPosition/Rangenow threads UTF-8/UTF-16 negotiation through a single encoding-aware index (offset_to_position,position_to_offset,byte_in_line_to_position). Lazyropey::Ropefor UTF-16 (never built under UTF-8 negotiation).byte_in_line_to_positionhelper — collapses the recurringline.find(needle) → emit Positionpattern that previously emitted raw byte offsets as columns (wrong under UTF-16 on non-ASCII). Round-20: strictly rejects byte offsets that overshoot the addressed line, instead of silently routing to the next line via the source-len clamp.DispatchErrorenum — request dispatch now routes viaMethodNotFound/DuplicateInitialize/Handlervariants instead of the priormsg.starts_with(...)prefix-string match.initializerejection — per LSP 3.17 §Lifecycle, a secondinitializeis a protocol violation; previously the server silently rebuilt a strippedServerCapabilities(downgrading the session). Now returnsInvalidRequest.CodeActiondedup — multipleBomInDirectiveBodyerrors at the same offset collapse into one quick-fix viaBTreeSet<usize>.currency_occurrencesindex — replaces bespoke string-search that mutated currency-substrings inside payee strings and account names (linked-edit / rename / highlight were corrupting unrelated text as the user typed).rustledger-parser— BOM handling + exhaustivenessParseError::every_kind_sampleexhaustive — gated by a compile-time-exhaustivevariant_indexmatch so new variants can't silently slip out of the sample list.rustledger-ffi-wasi— API v2.0 (breaking)API_VERSIONbumped1.0 → 2.0to mark theParseErrorEntry.error.data.errorswire-shape break. CHANGELOG, README, OpenRPC schema, and tests updated.rustledger-core—ShiftSpanstrait with compile-time disciplineshift_metadatafree function plus ad-hocSelf::X(_) | Self::Y(_) => {}no-op arms with aShiftSpanstrait, per-variant binding patterns (Self::Variant(v) => v.shift_spans(shift)), and aHashMap<K, V, S>blanket impl. A newSpanned<T>field on any variant now compiles only after its impl shifts the span — the discipline is enforced at the type level.Breaking changes
rledger formatdefault changes from fixed column-60 to auto-width. Pass-c 60to restore the previous layout.API_VERSIONbumped to2.0.ParseErrorEntry.error.data.errorsis now an object array; consumers pinned to the1.xstring-array shape must update.How to test
cargo test --all-features— full workspace (~3000 tests, zero failures)cargo test -p rustledger --test format_compat— golden output, idempotence/fixed-point on the corpus, and livebean-format(beancount 3.2.3) parity via the podman compat imagecargo test -p rustledger-lsp --all-features— 192 LSP tests including byte-offset encoding round-trip under both UTF-8 and UTF-16Test plan
cargo test --all-features— workspace-wide passcargo clippy --all-features --all-targets -- -D warnings— cleancargo fmt --all -- --check— cleanRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps --all-features— cleanbean-formatparity confirmed (not skipped)Closes #1242
🤖 Generated with Claude Code