Skip to content

feat(parser,lsp): #1262 phase 5.3 - CST-snap fallback for range formatting - #1298

Merged
robcohen merged 2 commits into
mainfrom
feat/cst-phase-5-3-lsp-range-formatting
Jun 10, 2026
Merged

robcohen merged 2 commits into
mainfrom
feat/cst-phase-5-3-lsp-range-formatting

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Phase 5.3 of #1262. The LSP textDocument/rangeFormatting handler already existed (predates #1262) using a minimal-diff approach: parse → format_source → line-diff → keep only edits inside the user's selection. That path is great on a clean file — sub-line precision, cursor preservation, multi-hunk granularity — but it bailed entirely when the file had ANY parse errors. The asymmetric UX (whole-file formatting falls back to surface_cleanup_edits on parse errors; range formatting just silently no-ops) hurt users editing through a typo elsewhere in the file.

This PR adds a CST-aware second-chance path WITHOUT touching the happy path. Two paths coexist with clearly different trade-offs documented at the module level.

Parser

  • format::format_node_range(node, range) -> Option<(TextRange, String)> in cst/format.rs. Walks node (SOURCE_FILE) and emits the canonical-form text for the smallest set of top-level Directives + standalone-comment tokens whose text_range intersects range. The snap range is the union of the included children's ranges; ERROR_NODE children are skipped (matches format_node's existing policy of dropping error content).
  • Whole-file round-trip property pinned: format_node_range(node, full) == format_node(node) — range formatting is the whole-file formatter restricted to a range, NOT a parallel canonical form (the failure mode that bit [Compat]: Destructive formatting (post-#1142) #1252).
  • range is in the CST byte frame (post-BOM strip); consumers wanting original-source coordinates apply the standard bom_offset shift at the boundary (same convention as ParseResult::syntax_root and selection_range).

11 parser tests: full-range round-trip; trivia-only returns None; single-directive selection; multi-directive selection emits canonical blank separator; cursor-inside-a-directive snap; cursor-at-directive-start boundary; top-level-comment inclusion; ERROR_NODE-only returns None; past-EOF clamp; sub-node selection snaps up to enclosing transaction; selection straddling an ERROR_NODE between two valid directives drops the error content.

LSP

handle_range_formatting now runs two paths in order:

  1. Happy path — format_document + clip-to-range (existing implementation, factored into a clip_edits_to_range helper so the entry point reads cleanly). Returns minimal-diff edits that stay strictly inside the selection. Unchanged behavior on clean files.

  2. Fallback path — if format_document declined AND parse_result.errors is non-empty, the new fallback_cst_snap_edit helper walks parse_result.syntax_node() via format_node_range, bridges the BOM frame, and emits a single TextEdit covering the snapped directive boundaries. The fallback INTENTIONALLY extends past the user's selection (rounded outward to the nearest top-level directive boundaries) — partial-directive canonical form would create a second truth alongside format_source. Same trade-off rust-analyzer and Prettier make for range formatting through broken syntax.

The clean-file-already-canonical case (where format_document returns None because no edits are needed, not because of parse errors) still surfaces as None — the fallback's guard on parse_result.errors.is_empty() prevents it from running over an already-canonical file and dirtying the document.

4 new LSP tests pin the policy:

  • Parse-error file + selection with only ERROR_NODE → None.
  • Parse-error file + selection with a valid directive → single CST-snap edit.
  • BOM-prefixed parse-error file → snapped edit emits LSP positions in the original-source frame (not CST frame).
  • Clean canonical file → still returns None (regression check that the fallback doesn't fire when it shouldn't).

The pre-existing parse_errors_return_none test was replaced; its assertion pinned the OLD policy (bail on any parse error) which is exactly what this PR replaces.

Test plan

  • cargo test -p rustledger-parser -p rustledger-lsp --all-features — 221 LSP lib + 249 parser + integration suites green (range_formatting: 10 → 14; parser format suite: 238 → 249)
  • cargo check --workspace --all-features --all-targets
  • cargo clippy --workspace --all-features --all-targets -- -D warnings
  • RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps
  • Baseline manifest unchanged (no parser-output fields changed)
  • CI green across the workspace

Refs #1262.

🤖 Generated with Claude Code

…tting

Phase 5.3 of #1262. The LSP `textDocument/rangeFormatting`
handler already existed (it predates #1262) using a minimal-diff
approach: parse → `format_source` → line-diff → keep only edits
inside the user's selection. That path is great on a clean file —
sub-line precision, cursor preservation, multi-hunk granularity —
but it bailed entirely when the file had ANY parse errors. The
asymmetric UX (whole-file formatting falls back to
`surface_cleanup_edits` on parse errors; range formatting just
silently no-ops) hurt users editing through a typo elsewhere in
the file.

This PR adds a CST-aware second-chance path WITHOUT touching the
happy path. The two paths coexist with clearly different
trade-offs documented at the module level.

## Parser

`format::format_node_range(node, range) -> Option<(TextRange, String)>`
in `cst/format.rs`. Walks `node` (`SOURCE_FILE`) and emits the
canonical-form text for the smallest set of top-level Directives
+ standalone comment tokens whose `text_range` intersects `range`.
The snap range is the union of the included children's ranges;
`ERROR_NODE` children are skipped (matches `format_node`'s
existing policy of dropping error content). The whole-file
round-trip property — `format_node_range(node, full) ==
format_node(node)` — is pinned by a dedicated test, so range
formatting is the whole-file formatter restricted to a range,
NOT a parallel canonical form (the failure mode that bit #1252).

The function takes `range` in the CST byte frame (post-BOM
strip) — consumers wanting original-source coordinates apply
the standard `bom_offset` shift at the boundary (same
convention as `ParseResult::syntax_root` and `selection_range`).

Eleven parser tests cover: full-range round-trip vs.
`format_node`; trivia-only returns None; single-directive
selection; multi-directive selection emits the canonical blank
separator; cursor-inside-a-directive snap; cursor-at-directive-
start boundary; top-level comment inclusion; ERROR_NODE-only
returns None; past-EOF clamp; sub-node selection (cursor in a
posting) snaps up to the enclosing transaction; selection
straddling an ERROR_NODE between two valid directives drops the
error content (matches `format_source`).

## LSP

`handle_range_formatting` now runs the two paths in order:

1. Happy path: `format_document` + clip-to-range (existing
   implementation, factored into a `clip_edits_to_range` helper
   so the entry point reads cleanly). Returns minimal-diff edits
   that stay strictly inside the selection. Unchanged behavior
   on clean files.

2. Fallback path: if `format_document` declined AND
   `parse_result.errors` is non-empty, the new
   `fallback_cst_snap_edit` helper walks `parse_result.syntax_node()`
   via `format_node_range`, bridges the BOM frame, and emits a
   single `TextEdit` covering the snapped directive boundaries.
   The fallback INTENTIONALLY extends past the user's selection
   (rounded outward to the nearest top-level directive
   boundaries) — partial-directive canonical form would create
   a second truth alongside `format_source`. Same trade-off
   rust-analyzer and Prettier make for range formatting through
   broken syntax.

The clean-file-already-canonical case (where `format_document`
returns None because no edits are needed, not because of parse
errors) still surfaces as None — the fallback's guard on
`parse_result.errors.is_empty()` prevents it from running over
an already-canonical file and emitting a coarse no-op edit
that would dirty the document.

Four new LSP tests pin the policy:
- Parse-error file + selection with only ERROR_NODE → None.
- Parse-error file + selection with a valid directive → single
  CST-snap edit.
- BOM-prefixed parse-error file → snapped edit emits LSP
  positions in the original-source frame (not CST frame).
- Clean canonical file → still returns None (regression check
  that the fallback doesn't fire when it shouldn't).

The pre-existing `parse_errors_return_none` test was replaced;
its assertion pinned the OLD policy (bail on any parse error)
which is exactly what this PR replaces. The new tests pin the
two cases the policy split implies: bail when there's nothing
structural to format; fall back when there is.

## CHANGELOG

`crates/rustledger-parser/CHANGELOG.md` `[Unreleased]` / Features
entry for `format_node_range` documenting the contract and the
CST byte frame.

Verified: cargo test -p rustledger-parser -p rustledger-lsp
--all-features (221 LSP lib + 249 parser + integration suites
green; range_formatting subsuite went from 10 -> 14 tests, parser
format suite went from 238 -> 249 tests), cargo clippy --workspace
--all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings
cargo doc -p rustledger-parser -p rustledger-lsp --no-deps,
cargo check --workspace --all-features --all-targets. Baseline
manifest unchanged (no parser-output fields changed).

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner June 10, 2026 09:10
Copilot AI review requested due to automatic review settings June 10, 2026 09:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a CST-based fallback for LSP textDocument/rangeFormatting so users can still format well-formed directives inside a selection even when the file has parse errors, while preserving the existing minimal-diff “happy path” on clean parses.

Changes:

  • Re-export format_node_range from rustledger-parser’s format module surface.
  • Implement format_node_range in the parser CST formatter (with extensive unit tests) to snap selections to top-level directive/comment boundaries.
  • Update LSP range-formatting handler to try minimal-diff first, then fall back to a single CST-snap TextEdit when parse errors exist (with new regression tests, including BOM frame bridging).

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
crates/rustledger-parser/src/lib.rs Exposes format_node_range via the public formatter module surface.
crates/rustledger-parser/src/cst/format.rs Adds format_node_range implementation + tests for snapped range formatting.
crates/rustledger-parser/CHANGELOG.md Documents the new formatter API and its intended LSP usage.
crates/rustledger-lsp/src/handlers/range_formatting.rs Introduces a two-path rangeFormatting handler with CST-snap fallback on parse errors.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.8ms ± 4.7ms 25.2 MB
beancount 857.8ms ± 6.3ms 50.7 MB
Comparison 24.6x faster 2.0x less

vs main branch (2026-06-10)

Metric main this PR Change
Time 33.6ms 34.8ms +3.6% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

github-actions Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 99%
Total Files 792
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.45799% with 2 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

Addresses 10 deep-review findings + 3 Copilot inline comments on
PR #1298. Same root cause for several: the original CST-snap
fallback inherited `format_node`'s "silently drop ERROR_NODE
content" policy, lost line-ending preservation, and accepted
cursor-only requests where the happy path rejected them.

## Behavior changes

- **ERROR_NODE policy: refuse to format.** `format_node_range`
  now returns None when the computed snap range would cover any
  top-level ERROR_NODE byte. Range formatting must not silently
  delete content the parser couldn't classify - the
  "Format Selection" keybinding has no opt-in to data loss the
  way the CLI / FFI / try_format_source callers do. This is the
  deliberate divergence from format_node's whole-file policy of
  dropping ERROR_NODE children. UX cost: occasional "format-
  selection did nothing" while a parse error sits inside the
  snap. Benefit: no in-progress user content is silently deleted.

- **CRLF preservation in fallback.** The fallback now re-injects
  CRLF on CRLF sources via lf_to_crlf_outside_strings, mirroring
  format_document's preservation. Without this, Windows-authored
  files would get mixed line endings inside the snapped region
  on every parse-error-fallback edit.

- **Empty-range guard.** A cursor-only request (start == end) on
  a parse-error file now returns None, matching the
  empty_range_is_a_noop invariant the happy path enforces.
  Auto-format-on-type clients no longer trigger a full-directive
  reformat on every keystroke through a parse error window.

## BOM bridge policy

`fallback_cst_snap_edit` uses saturating_sub for the BOM offset
shift; selection_range uses checked_sub. The divergence is
deliberate and now documented: range formatting takes a *range*
(selection from byte 0 of original source = "start of file"
naturally maps to byte 0 of CST), while selection_range takes a
*position* (cursor inside BOM is degenerate, bail). Both
handlers document the choice and cite each other.

## Documentation

- `format_node_range` rustdoc updated to reflect the new
  ERROR_NODE policy + the file-wide alignment caveat on
  parse-error files + the SOURCE_FILE precondition (panics
  otherwise).
- `handle_range_formatting` module rustdoc updated: the new
  ERROR_NODE refusal policy, the BOM bridge saturating_sub
  semantics with the selection_range cross-reference, and an
  explicit "CLI parity, intentionally dropped" section
  documenting the deliberate regression from the prior
  "bail on any parse error" contract.
- Copilot's inline note: rustdoc no longer claims the LSP
  handler returns "empty Vec<TextEdit>" on no-intersect; it
  says None (serialized as null per LSP).
- CHANGELOG entry expanded with the four operational caveats
  (ERROR_NODE policy, file-wide alignment, BOM frame,
  SOURCE_FILE precondition).

## Test changes

- Existing `parse_errors_with_valid_directive_in_selection_returns_fallback_edit`
  tightened to pin edit.range.end (not just start + new_text),
  so a pure-insertion regression
  (snap_end_byte = snap_start_byte) is caught. Selection
  narrowed so the snap doesn't cover the line-1 ERROR_NODE
  under the new policy.
- Existing BOM test selection narrowed for the same reason.
- New `parse_errors_with_error_node_in_snap_returns_none` pins
  the ERROR_NODE refusal policy.
- New `parse_errors_with_crlf_source_emits_crlf_replacement`
  pins the CRLF preservation.
- New `parse_errors_with_cursor_only_request_returns_none`
  pins the empty-range guard on parse-error files.
- Parser `format_node_range_drops_error_node_between_directives`
  renamed to `format_node_range_bails_when_snap_covers_error_node`
  and inverted: the snap-covers-ERROR_NODE input now expects
  None.
- New parser `format_node_range_formats_directive_when_snap_does_not_cover_error_node`
  pins that the ERROR_NODE bail is scoped to the snap range,
  not to "file has any ERROR_NODE at all".

Verified: cargo test -p rustledger-parser -p rustledger-lsp
--all-features (224 LSP lib + 250 parser + integration suites
green; range_formatting subsuite 14 -> 17 tests; format suite
249 -> 250 tests), cargo clippy --workspace --all-features
--all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo
doc -p rustledger-parser -p rustledger-lsp --no-deps. Baseline
manifest unchanged.

Refs #1262, #1298.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen

Copy link
Copy Markdown
Member Author

Round-1 review sweep (95e3904)

Addressed 10 deep-review findings + Copilot's 3 inline comments. Same root cause for several: the original fallback inherited format_node's "silently drop ERROR_NODE content" policy from the whole-file path, lost line-ending preservation, and accepted cursor-only requests where the happy path rejected them.

Behavior changes

Finding Fix
CRLF lost in fallback lf_to_crlf_outside_strings re-injection on CRLF sources, mirrors format_document
Empty-range cursor reformats directive on every keystroke if orig_end <= orig_start { return None; } guard at top of fallback, matches clip_edits_to_range
ERROR_NODE silently deleted between two formatted directives format_node_range returns None when snap covers any ERROR_NODE byte — "Format Selection" has no opt-in to data loss
BOM bridge divergence with selection_range saturating_sub kept (intentional: range semantics ≠ position semantics) but the divergence is now explicitly documented in both module rustdocs
Test didn't pin edit.range.end parse_errors_with_valid_directive_in_selection_returns_fallback_edit now pins both ends
Doc said "empty Vec" but handler returns None Rustdoc corrected — None is serialized as null per LSP, not []

Tests

  • Parser: format_node_range_drops_error_node_between_directives → renamed and inverted to format_node_range_bails_when_snap_covers_error_node. New sibling format_node_range_formats_directive_when_snap_does_not_cover_error_node pins that the bail is scoped to the snap range, not "file has any ERROR_NODE at all".
  • LSP: 3 new tests for ERROR_NODE intersection, CRLF preservation, cursor-only request.

Documentation

  • LSP module rustdoc has a new "CLI parity, intentionally dropped" section calling out the deliberate regression from the prior "bail on any parse error" contract.
  • CHANGELOG entry expanded with the four operational caveats: ERROR_NODE policy, file-wide alignment (with the broken-file caveat), BOM frame, SOURCE_FILE precondition.

Verified

cargo test -p rustledger-parser -p rustledger-lsp --all-features (224 LSP lib + 250 parser + integration suites green; range_formatting subsuite 14 → 17 tests). cargo clippy --workspace --all-features --all-targets -- -D warnings clean. RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps clean. Baseline manifest unchanged.

@robcohen
robcohen enabled auto-merge (squash) June 10, 2026 09:38
@robcohen
robcohen merged commit 61b3a43 into main Jun 10, 2026
57 of 58 checks passed
@robcohen
robcohen deleted the feat/cst-phase-5-3-lsp-range-formatting branch June 10, 2026 09:41
robcohen added a commit that referenced this pull request Jun 10, 2026
…es (#1299)

* chore(deps): #1262 unyank aes 0.9.0 -> 0.9.1

cargo deny check surfaced aes 0.9.0 (transitive via zip 8.6.0 -> rustledger-plugin) as a yanked version. cargo update -p aes resolves to 0.9.1, the immediate successor that drops the yank mark. Lockfile-only change, no source diff in the workspace, no semver impact on rustledger-plugin or its consumers.

cargo deny check now reports advisories ok, bans ok, licenses ok, sources ok across the workspace.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(parser,lsp): cache formatter alignment on ParseResult

Pre-compute the formatter's file-wide alignment columns at parse
time and stash them on `ParseResult::alignment`, so hot formatting
paths (notably the LSP `range_formatting` fallback shipped in
#1298) don't re-walk every posting in the file on every call.

## Background

`format_node` and `format_node_range` (in
`rustledger-parser/src/cst/format.rs`) run a pre-pass over every
Transaction's postings to compute file-wide alignment columns:
`number_col` (where the right-justified number field starts) and
`number_width` (max rendered width of any number). The pre-pass is
`O(N_postings_in_file)` per call.

This is fine for the CLI's one-shot `rledger format`, but the LSP
`range_formatting` fallback path can be invoked per-keystroke by
format-on-type clients while the user is editing through a parse
error. A 10k-directive ledger with a typo means we walked 10k
directives' postings on every key press. The PR #1298 review
flagged this as a real concern (deferred at the time as
acceptable).

## What's in this PR

### Parser

- `format::Alignment` is now `pub` + `#[non_exhaustive]` + `Copy`,
  with public `number_col` / `number_width` fields. Construction
  via `Alignment::default()` is supported externally; the
  `#[non_exhaustive]` attribute reserves the right to add fields
  later without breaking downstream `match` arms.
- `format::compute_alignment(&SourceFile) -> Alignment` is now
  `pub` so consumers can pre-compute independently.
- `ParseResult::alignment: Alignment` populated by `parse_via_cst`
  during the existing `walk_descendants_once` pass. Same canonical-
  payload exclusion pattern as `syntax_root`: bound in the
  destructure for compiler-enforced exhaustiveness, discarded from
  the canonical hash. Pinned by `canonical_payload_excludes_alignment`.
- Two new `_with_alignment` variants:
  `format::format_node_with_alignment(node, alignment) -> String`
  and `format::format_node_range_with_alignment(node, range, alignment)`.
  The bare `format_node` / `format_node_range` delegate to them
  after computing alignment internally — no behavior change for
  existing callers, just a new opt-in fast path.
- Equivalence pinned: `format_node_equals_format_node_with_alignment`
  and `format_node_range_matches_format_node_range_with_alignment`
  assert byte-identical output across representative fixtures.
  The cache's freshness vs. a fresh `compute_alignment` call is
  pinned by `parse_result_alignment_cache::*` (6 fixtures
  including empty source, open-only, single transaction,
  multi-transaction with varying widths, arithmetic amounts,
  and a parse-error file).

### LSP

- `fallback_cst_snap_edit` in `range_formatting.rs` now calls
  `format_node_range_with_alignment(&node, cst_range, parse_result.alignment)`
  instead of `format_node_range(&node, cst_range)`. The per-call
  `O(N_postings)` walk is gone; per-fallback cost is now
  `O(N_cst_nodes covered by the user's range)`, independent of
  file size.

### Deps

- `cargo update -p aes` to unyank the transitive dependency `aes
  0.9.0 -> 0.9.1`. Surfaced by `cargo deny check`. Lockfile-only,
  no source diff anywhere in the workspace.

## Why both in one PR

The dependency unyank is a single-line lockfile change that would
otherwise sit in its own trivial PR. Keeping it next to the
substantive change is a closing housekeeping pass; the two
commits are clean (`chore(deps):` + `feat(parser,lsp):`) so they
can be split during review if desired.

## Verified

- `cargo test -p rustledger-parser -p rustledger-lsp
  --all-features` (224 LSP lib + 260 parser lib green; parser
  format module suite went 250 -> 260 with the 10 new tests
  spread across `cst::format::tests`,
  `parse_result_alignment_cache`,
  `canonical_payload_excludes_alignment`).
- `cargo clippy --workspace --all-features --all-targets --
  -D warnings` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p
  rustledger-lsp --no-deps` clean.
- `cargo deny check` now reports `advisories ok, bans ok, licenses
  ok, sources ok`.
- Baseline manifest unchanged (the canonical-payload exclusion
  works as designed; the new test pins it executably).

Refs #1262 (post-completion follow-up flagged in the closing
comment).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore: regenerate cargo-vet exemptions

* fix(parser,lsp,ffi,wasm): #1299 round-1 review findings

Addresses 10 deep-review findings on PR #1299. Same root cause
for the largest one: the original PR optimized only the rare
parse-error LSP fallback path; the much more common Format-on-
Save / FFI format.source / WASM ParsedLedger::format paths still
re-parsed the source and re-walked every posting, leaving the
cache mostly dead code.

## Cache reaches the happy path now

- New public entry `format::format_source_with_parsed(&ParseResult, &str)`
  reuses the cached `syntax_root` AND `alignment`, skipping both
  the duplicate parse and the duplicate alignment walk.
- LSP `handle_formatting` / `format_document` switched to
  `format_source_with_parsed`. The Format-on-Save / format-on-
  type-clean-file paths now pay only the per-call emit cost.
- FFI `format.source` (rustledger-ffi-wasi/src/jsonrpc/router.rs)
  switched: it already produced `parse_result` for the error
  gate; the second parse via `format_source` is gone.
- WASM `ParsedLedger::format` (already-cached `parse_result`
  field) and `api::format_source` (already-produced
  `parse_result`) both switched.
- Byte-identical output pinned by new
  `format_source_with_parsed_matches_format_source` test across
  LF / CRLF / BOM-prefixed fixtures. The two paths produce the
  same canonical text because the canonical form is rebuilt from
  typed values rather than echoing trivia.

## Type rename: Alignment -> PostingAlignment

The public type was just introduced this week (no shipped
consumers); the cheapest moment to rename. `Alignment` is too
generic for `rustledger_parser::format::Alignment` and would
compete with future text-justification or memory-layout helpers.
`PostingAlignment` is qualified by its semantic purpose. Re-
export, struct definition, field type on `ParseResult::alignment`,
all internal `align: Alignment` parameter sites, and the
`canonical_payload_excludes_alignment` test all updated.

## Cast cleanup in _with_alignment fns

`format_node_with_alignment` and `format_node_range_with_alignment`
each replaced their `SourceFile::cast(node.clone()).expect(...)`
+ misleading `let _ = source_file;` precondition with
`assert_eq!(node.kind(), SyntaxKind::SOURCE_FILE)`. Saves the
redundant Arc-bump clone on every hot-path call (the bare
`format_node` delegate already validated the kind) while keeping
the same panic guarantee for direct external callers. The
`format_node_with_alignment` body now uses
`node.children_with_tokens()` directly instead of
`source_file.syntax().children_with_tokens()`.

## Docs

- `compute_alignment` rustdoc grew a `Tree-shape precondition`
  section documenting the must-be-just-parsed contract:
  hand-built partial trees and ERROR_NODE-wrapped transactions
  silently fall back to `PostingAlignment::default()`. Behavior
  pinned by the new
  `parse_result_alignment_cache::mid_transaction_error_node`
  test.
- `ParseResult::alignment` rustdoc grew a `Producer-only cache
  invariant` section explaining what happens if a consumer
  mutates `directives` / `syntax_root` without refreshing the
  cache, and pointing them at `compute_alignment` for the
  manual refresh.
- CHANGELOG entry rewritten to list the three public entry
  points (node, node_range, source), document the
  `PostingAlignment` naming choice, and capture the
  producer-only invariant.

## Tests

- Existing 10 cache-equivalence tests still pass.
- 1 new test pins `format_source_with_parsed` byte-identity
  vs `format_source` across LF / CRLF / BOM fixtures.
- 1 new test pins cache equivalence under mid-transaction
  ERROR_NODE recovery — the scenario the LSP fallback
  actually traverses during format-on-type.

## Verified

- `cargo test -p rustledger-parser -p rustledger-lsp -p
  rustledger-ffi-wasi --all-features` — 224 LSP lib + 262
  parser lib + 58 FFI lib + integration suites green
  (parser: 260 -> 262 with the 2 new tests).
- `cargo clippy --workspace --all-features --all-targets --
  -D warnings` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p
  rustledger-lsp -p rustledger-ffi-wasi -p rustledger-wasm
  --no-deps` clean.
- Baseline manifest unchanged.

Refs #1299.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(parser,lsp,cli): #1299 round-2 review findings + Copilot inline

Addresses 10 deep-review findings + 5 Copilot inline comments
(all converging on the same byte-identity / doc-drift / cache-
reach themes).

## Correctness

- `format_source_with_parsed` now falls back to
  `format_source(source)` when `parse_result.errors` is non-
  empty. Preserves byte-identity for inputs whose CST diverges
  from what `format_source`'s pre-parse normalization would
  produce — concretely, bare-`\r` (classic Mac) line
  terminators that `crlf_to_lf_outside_strings` normalizes but
  `parse_via_cst` does not. Without this fallback, classic-Mac
  sources would emit different text on the cached path vs
  format_source.
- Defensive length-check `debug_assert_eq!` catches the most
  common form of `(parse_result, source)` mismatched pair (different
  documents have different lengths). Released as
  `debug_assert_eq!` so release builds pay no cost; debug
  builds panic on mismatched pair. New test
  `format_source_with_parsed_panics_on_length_mismatch` pins
  the debug-build behavior.

## More cache reach

- CLI `try_format_source` (the entry that backs `rledger format`)
  switched from `format_source(source)` to
  `format_source_with_parsed(&result, source)`. The CLI was the
  one consumer round-1 missed — same shape as the LSP/FFI/WASM
  migrations.
- `rledger doctor roundtrip` switched similarly. On a project
  of 200 included files the doctor pass roughly halves its
  parsing cost.

## Test fixture expansion

Added three new fixtures to
`format_source_with_parsed_matches_format_source`:
- **BOM + CRLF combination** — Windows-authored ledger with a
  UTF-8 BOM.
- **Parse-error file** — exercises the new error-gate fallback.
- **Bare-CR line terminators** — classic-Mac source; exercises
  the fallback (`parse_via_cst` errors out on bare CR).

## Hot-path costs

- `assert_eq!` → `debug_assert_eq!` in
  `format_node_with_alignment` and
  `format_node_range_with_alignment`. The bare `format_node` /
  `format_node_range` delegates already validated kind via
  `SourceFile::cast`, so on the most common call path (bare →
  with_alignment) the assert was a redundant release-build
  cost. External direct callers still get a debug-build panic
  on wrong-kind input.

## Rustdoc fixes (Copilot inline #1 / #3 / #4 / #5)

- Three rustdoc cites pointed at non-existent tests:
  `compute_alignment_matches_parseresult_cache` (lib.rs:309,
  format.rs:858 in `compute_alignment`, convert.rs:272 inline
  comment) and `format_node_range_with_alignment_matches_uncached`
  (format.rs:812). Renamed to point at actual test names
  (`parse_result_alignment_cache::*` and
  `format_node_range_matches_format_node_range_with_alignment`).
- `compute_alignment(node)` doc claim corrected: the function
  takes `&SourceFile`, not `&SyntaxNode`. Updated to
  `compute_alignment(&SourceFile::cast(node).unwrap())` in both
  occurrence sites.
- `syntax_node().cast::<SourceFile>()` invalid turbofish in
  rustdoc fixed to `SourceFile::cast(syntax_node()).unwrap()`.

## Public API path consistency (Copilot inline #2)

`ParseResult::alignment` field type spelled as
`crate::format::PostingAlignment` (via the public re-export
surface) instead of `crate::cst::format::PostingAlignment`
(the internal module path). Matches the documented
"sole import path" convention in
`crate::format` module rustdoc.

## CHANGELOG naming rationale tightened

Cited the live existing `rustledger_core::Alignment` (an
unrelated workspace type used by the legacy typed-Directive
emitter) as the concrete reason for naming the new type
`PostingAlignment` instead of bare `Alignment`. Round-1 only
mentioned hypothetical future collisions.

## Stale rustdoc reference

`Alignment::default()` → `PostingAlignment::default()` in the
`format_node_with_alignment` rustdoc.

## Criterion benchmark

New `bench_format_source_vs_with_parsed` group in
`benches/parser_bench.rs`. Compares `format_source(s)` against
`format_source_with_parsed(&pre_parsed, s)` on 10 / 100 / 1000
transaction synthetic ledgers. Provides an executable
witness for the PR's perf claim.

## Verified

- `cargo test -p rustledger-parser -p rustledger-lsp -p
  rustledger-ffi-wasi -p rustledger --all-features` — 224 LSP
  lib + 263 parser lib + 58 FFI lib + integration suites green
  (parser: 262 -> 263 with the new debug-build panic test).
- `cargo clippy --workspace --all-features --all-targets --
  -D warnings` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p
  rustledger-lsp --no-deps` clean.
- Baseline manifest unchanged.

Refs #1299.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
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.

2 participants