Skip to content

fix(lsp): keep unparsable text inside a directive when range formatting - #2837

Merged
robcohen merged 4 commits into
mainfrom
fix/lsp-range-format-keeps-error-tokens
Nov 3, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/lsp-range-format-keeps-error-tokens

Conversation

@robcohen

@robcohen robcohen commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

What changed

LSP range formatting on a file with parse errors (the CST-snap fallback) rebuilt every directive in the selection from its typed values. Text the parser could not read into one, such as junk after open Assets:A, after a posting amount, or inside a cost, was not part of any value, so it vanished from the edit along with its parse error:

Selection over Before After
2024-01-01 open Assets:A junk 2024-01-01 open Assets:A unchanged, kept as written
Assets:A 1 USD junk in a transaction posting rebuilt without junk transaction kept as written
well-formed 2024-01-02 open Assets:B next to it formatted formatted
  • New format::format_parsed_range(parse_result, range, style) builds the same ErrorRanges the whole-file error-tolerant formatter uses (fix(format): the error-tolerant formatter deletes junk on the same line after a directive #2794) from the parse result's own errors, and copies a directive that overlaps one verbatim. It reuses the cached alignment under the default style and measures it under a grouping style, which is what the LSP handler did by hand before.
  • The per-node emission is now one NodeEmitter shared by the whole-file walk and the range walk, so the two cannot disagree on which directives they rebuild (canonical-function discipline).
  • The range path still declines (returns None) when the snap covers a top-level ERROR_NODE, as before.
  • Doc comments in format.rs and the LSP handler said whole-file formatting "silently drops ERROR_NODE content"; it has copied it verbatim since [Compat]: rledger format deletes org-mode (*) headers and comments grouped with them #1335. Corrected.

Not affected: whole-document LSP formatting (falls back to surface cleanup on parse errors), on-type formatting (its own line-local edits), WASM and the FFI component (no range entry point; their whole-file path is format_source, fixed in #2801). No parse output changes, so no cache bump.

How to test

  • cargo test -p rustledger-parser --test range_format_keeps_error_text: for five broken shapes (junk after a header, after a posting, in a cost, a stray quote, junk at EOF without a newline) range formatting keeps every non-whitespace byte, still formats the neighbors, is idempotent, and over the whole file equals format_source byte for byte (drift guard). With format_parsed_range ignoring the errors, 4 of the 5 fail.
  • cargo test -p rustledger-lsp --lib parse_errors_inside_a_directive_keep_their_text_in_the_fallback_edit: the LSP handler keeps junk in the edit. Without the fix it fails (2024-01-01 open Assets:A instead of 2024-01-01 open Assets:A junk).
  • cargo test -p rustledger-parser -p rustledger-lsp --all-features, clippy -D warnings, rustdoc -Dwarnings, cargo fmt --check all pass.

Closes #2803

Review round 1 (ced349f)

  • Indent: the range walk now tracks a top-level whitespace token before a node, as the whole-file walk does, so "; c\n 2024-01-01 open Assets:A junk\n..." keeps its two-space indent (it used to drop it, and in "; c\n 2024-01-01 open Assets:A\n...junk\n" dropping it also removed the indentation's parse error, so a second pass reformatted). Both inputs are in the whole-file drift-guard test.
  • CRLF after a stray quote: lf_to_crlf_outside_strings (and crlf_to_lf_outside_strings) treated every " as opening a string, so a copied stray quote left all later lines LF in a CRLF edit. They now read a quote as the lexer does: one that no later unescaped quote closes, or that a \ before a line break stops, ends at its own line (fix(parser): end an unterminated quote at its own line #2788). A failed scan is remembered, so many stray quotes stay linear. (Only the LSP range handler re-injects CRLF on a file with parse errors; WASM and FFI return LF.) The lexer-agreement drift guard runs the same step and has two unterminated-quote fixtures. CRLF cases are tested at the helper, range and LSP levels.
  • Two stale comments about whole-file formatting dropping ERROR_NODE content are corrected.
  • With format.rs at the previous commit, 3 of the 7 parser tests and the LSP test fail; all pass now.

Review round 2 (73628ef)

  • cr_outside_strings_present now reads quotes through the same lexer_source_state step as lf_to_crlf_outside_strings and crlf_to_lf_outside_strings, so all line-ending walkers share one quote rule (a stray quote no longer hides the \r after it).
  • A fixture with a later quote ("a\ then a line break, then "x") pins the \-before-line-break rule in the lexer-agreement drift guard and the LF to CRLF helper test; replacing the rule with an unconditional escape now fails both. (In a CRLF file a \ before \r\n escapes the \r, since the lexer's . matches it, so that shape pairs with the later quote there, in the lexer and the helper alike.)
  • A linear-cost guard counts the bytes quote scans step over on one stray quote followed by 20,000 \" lines: within 2x the input with the memo, 400,040,001 bytes for a 60,027-byte input without it.
  • Effect on format_source (the error-tolerant formatter behind the WASM and FFI component format calls): a bare \r (classic-Mac) line ending after a stray quote is now folded into a line break, so the directive after it is read, instead of being kept as if inside a string. Pinned by a test; the CHANGELOG now names exactly these paths.
  • Verification: parser, LSP and CLI test suites (79 result lines, 0 failed), clippy -D warnings, rustdoc -Dwarnings, cargo fmt --check.

🤖 Generated with Claude Code

The LSP range-format fallback (files with parse errors) rebuilt each
directive in the selection from its typed values, so text the parser
could not read into one (`junk` after a header, after a posting amount,
inside a cost) vanished from the edit along with its parse error.

A new `format::format_parsed_range` takes the parse result and builds the
same `ErrorRanges` the whole-file error-tolerant formatter uses (#2794);
a directive overlapping a parse error is copied verbatim. The per-node
emission is now one `NodeEmitter` shared by the whole-file and range
walks, so the two cannot disagree on which directives they rebuild. Also
corrects doc comments that said whole-file formatting drops ERROR_NODE
content (it copies it verbatim since #1335).

Closes #2803

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 2, 2026 12:26
@codecov

codecov Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.34043% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/format.rs 96.73% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 50.8ms ± 0.9ms 701.9ms ± 3.9ms 13.8x 33.5 MB / 51.0 MB
investment 75.7ms ± 1.0ms 2679.7ms ± 7.4ms 35.4x 44.5 MB / 59.0 MB
fifo 72.2ms ± 0.9ms 15329.5ms ± 80.4ms 212.4x 40.6 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.6ms ± 0.6ms 50.8ms ± 0.9ms +0.4% ✅ within noise 34.6 MB → 33.5 MB (-3.1%)
investment 75.3ms ± 0.9ms 75.7ms ± 1.0ms +0.6% ✅ within noise 44.6 MB → 44.5 MB (-0.3%)
fifo 71.4ms ± 0.8ms 72.2ms ± 0.9ms +1.0% ✅ within noise 40.7 MB → 40.6 MB (-0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.5ms, investment 0.6ms, fifo 0.5ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 821
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 3 commits November 2, 2026 06:59
…ay quote

- The range walk now tracks a top-level WHITESPACE token before a node,
  as the whole-file walk does, so a verbatim-copied indented directive
  keeps its indentation (#2786). Dropping it also removed the
  indentation parse error, so a second pass reformatted the line.
- The line-ending helpers (lf_to_crlf_outside_strings and
  crlf_to_lf_outside_strings) read a `"` as the lexer does: one that no
  later unescaped quote closes, or that a `\` before a line break stops,
  is an error token cut at its own line (#2788), not a string. A stray
  quote copied into a CRLF edit left every later line LF. A failed scan
  is remembered so many stray quotes stay linear. The lexer-agreement
  drift guard now runs the same step and has two unterminated-quote
  fixtures.
- Corrects two stale comments that said whole-file formatting drops
  ERROR_NODE content.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- cr_outside_strings_present now reads quotes through lexer_source_state,
  like the two helpers it mirrors, so a stray quote no longer hides the
  `\r` after it.
- A fixture with a later quote (`"a\` + newline, then `"x"`) pins the
  `\`-before-line-break rule in the lexer-agreement drift guard and the
  LF->CRLF helper test; an unconditional escape now fails both.
- A linear-cost guard counts the bytes quote scans step over (one stray
  quote then 20k `\"` lines): without the memo it is 400M bytes for 60k.
- A test pins the error-tolerant formatter folding a bare `\r` after a
  stray quote into a line break.
- CHANGELOG: name the affected paths precisely (LSP range edits;
  format_source behind WASM/FFI for bare `\r`), not WASM/FFI CRLF.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) November 3, 2026 02:15
@robcohen
robcohen merged commit 411064e into main Nov 3, 2026
61 of 62 checks passed
@robcohen
robcohen deleted the fix/lsp-range-format-keeps-error-tokens branch November 3, 2026 02:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(lsp): range formatting drops error tokens inside a directive

1 participant