Skip to content

fix(lsp): sweep read-only handlers to use posting.span (refs #1142) - #1157

Merged
robcohen merged 6 commits into
mainfrom
feat/lsp-handlers-readonly
May 19, 2026
Merged

robcohen merged 6 commits into
mainfrom
feat/lsp-handlers-readonly

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Follow-up to #1156. Extends the per-posting-span lookup pattern to the seven remaining LSP handlers that had the same txn_start_line + 1 + posting_idx anti-pattern. These handlers don't corrupt files (#1156 covered those), but they produce wrong line numbers whenever a transaction has posting-level metadata interleaved between postings.

Based on feat/lsp-handlers-posting-span (#1156). Rebases onto main automatically once #1156 lands via auto-merge.

Symptoms per handler, pre-fix

Handler Wrong-line manifestation
document_highlight Account highlight on the second posting landed on its metadata line
references "Find references" range pointed at metadata; jumping scrolled to wrong row
inlay_hints Inferred-amount overlay sat one row too high
selection_range Cursor-expand selected the metadata line as the posting body
symbols Outline-view ranges for postings pointed at metadata
call_hierarchy Incoming/outgoing call ranges pointed at metadata; transaction outer range under-counted lines
document_color Amount color decorations rendered on the wrong row
linked_editing Rename-linked ranges pointed at metadata lines

What changed

  • Each handler iterates &[Spanned<Posting>] and resolves the posting's line from byte_offset_to_position(source, p.span.start) (or LineIndex::offset_to_position where one was already in scope).
  • Plugin-synthesized postings (file_id == SYNTHESIZED_FILE_ID) are skipped — defensive, consistent with the formatters.
  • call_hierarchy's transaction outer range now derives from spanned.span.end instead of the txn_line + postings.len() + 1 heuristic.

Tests

Three new regression tests cover the highest-impact handlers using the canonical effective_date: fixture from #1142:

  • document_highlight::tests::test_highlight_account_with_interleaved_metadata_1142
  • references::tests::test_find_account_references_with_interleaved_metadata_1142
  • inlay_hints::tests::test_inlay_hint_lands_on_correct_line_with_interleaved_metadata_1142

Each asserts both:

  1. No result lands on a metadata line (the [Bug]: Destructive formatting on repeated metadata, LSP-only #1142 contract).
  2. The real posting line IS surfaced (catches a future short-circuit that emits empty results).

The other handlers ride on the same mechanical pattern; tests can be added incrementally if a specific handler regresses.

Out of scope (audit false positives)

  • code_actions.rs — the only grep hit was a window-search heuristic (range.start.line + 10), not posting arithmetic.
  • on_type_formatting.rs / execute_command.rs — matches were is_posting_line() content classifiers, not line indexing.

Test plan

  • cargo check --workspace --all-features --all-targets
  • cargo clippy --workspace --all-features --all-targets -- -D warnings
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps
  • cargo test -p rustledger-lsp --all-features — 134 tests, 0 failures (3 new + 131 pre-existing)
  • cargo fmt --all -- --check

Refs #1142

🤖 Generated with Claude Code

robcohen and others added 4 commits May 19, 2026 16:18
…1142)

The document-formatting and range-formatting handlers computed each
posting's line as `txn_start_line + 1 + posting_idx`. That assumption
breaks the moment a transaction has posting-level metadata interleaved
between postings — e.g., the `effective_date:` plugin convention:

```
2024-01-15 * "Test"
  Assets:Bank  -50.00 USD
    effective_date: 2024-01-20
  Expenses:Food  50.00 USD
    effective_date: 2024-01-21
```

The second posting is on line 3, not line 2 (line 2 is the metadata
line). The handlers emitted a posting-shaped `TextEdit` targeting
line 2, overwriting the metadata. The reporter saw the file silently
mangled every time their editor (e.g., nvim) ran format-on-save.

The fix uses the per-posting source span landed by PR #1151
(`Vec<Spanned<Posting>>`): convert `spanned_posting.span.start` to a
line number directly. The assumption that postings sit on consecutive
lines is gone.

What changed:

- `handlers/formatting.rs` and `handlers/range_formatting.rs` now
  iterate `txn.postings` as `&[Spanned<Posting>]`, look up each
  posting's line via `byte_offset_to_position(source, p.span.start)`,
  and skip plugin-synthesized postings (`file_id ==
  SYNTHESIZED_FILE_ID`) which have no source location to format.

Regression tests pin the contract:

- Both handlers get a `test_*_preserves_interleaved_metadata_1142`
  test that builds the canonical `effective_date:` source, runs the
  handler, and asserts no emitted edit targets a metadata line.
- I verified the test fails against the pre-fix code by applying
  the test alone against the buggy implementation: it caught the bug
  exactly where reported.

Out of scope for this PR (audit-identified follow-ups):

The same `start_line + 1 + i` anti-pattern lives in 11 other LSP
handlers (`call_hierarchy`, `document_highlight`, `selection_range`,
`linked_editing`, `code_actions`, `code_lens`, `inlay_hints`,
`document_color`, `execute_command`, `references`, `on_type_formatting`,
`symbols`). Those handlers are read-only — they produce wrong
highlights, hovers, etc. but cannot corrupt files. They warrant their
own audit + tests + PR rather than a blind sweep here.

Closes #1142

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (130 tests, 0 failures),
cargo fmt --all -- --check.

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

Apply review nits on PR #1156.

Tests

- formatting.rs's `test_*_preserves_interleaved_metadata_1142` gains a
  positive assertion: at least one edit must target a real posting
  line. The previous negative-only assertion would pass for a
  degenerate formatter that emits zero edits, so the regression net
  didn't catch a future short-circuit. The negative assertion (no
  metadata line touched) stays for the #1142 contract itself.

- range_formatting.rs gets a new companion test
  `test_range_formatting_fixes_misindented_posting_without_touching_metadata`
  that feeds a misindented posting interleaved with metadata. The
  fixer should emit an edit at the misindented posting line and
  leave the metadata alone — together with the existing all-correct
  regression test, the pair pin both "don't break #1142" and "still
  do useful work."

- range_formatting.rs's all-correct regression test now explicitly
  documents why it has no positive assertion (the source is already
  well-formatted; an empty edit set is the correct outcome).

Comments

- Both handlers' `SYNTHESIZED_FILE_ID` skip got a more accurate
  comment. The branch is dead code in today's LSP path
  (parse-driven, single-file), but documents the defensive intent
  for future code that might feed loader/plugin output through these
  handlers.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot review on PR #1156 flagged that the new per-posting span
lookups in the two formatting handlers were calling the naive O(n)
`byte_offset_to_position` scanner on every iteration, which can
become quadratic on large files (file_len × postings).

Fix: build a single `LineIndex` at the top of each handler. The
index is O(n) to construct once, then each `offset_to_position`
lookup is O(log lines). Same approach other handlers already use.

Also addressed:

- Doc-comment nit in the regression test: said metadata lines were
  matched "after four-space indent" but the check actually uses
  `trim_start()` which accepts any indent. Comment updated to
  describe the actual behavior and note the canonical form.

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (130 tests, 0 failures,
including all 4 #1142 regression tests still green),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to #1156: extends the per-posting-span lookup pattern from
the formatting handlers to seven read-only handlers that had the same
`txn_start_line + 1 + posting_idx` anti-pattern. These handlers
produced wrong line numbers — but not file corruption — whenever a
transaction had posting-level metadata interleaved between postings
(e.g., the `effective_date:` plugin convention).

Symptom per handler before this PR:

- document_highlight: account highlights for the second posting
  landed on its metadata line instead of the posting line.
- references / find-references: range pointed at the metadata line,
  so jumping to a reference scrolled the editor to the wrong row.
- inlay_hints: inferred-amount overlay sat one row too high.
- selection_range: cursor-expand selected the metadata line as the
  posting body.
- symbols: outline-view ranges for postings pointed at metadata.
- call_hierarchy: incoming/outgoing call ranges pointed at metadata,
  and the transaction's outer range under-counted lines because the
  `txn_line + postings.len() + 1` heuristic ignored metadata rows.
- document_color: amount color decorations rendered on the wrong row.
- linked_editing: rename-linked ranges pointed at metadata lines.

What changed:

- Each handler now iterates `&[Spanned<Posting>]` and looks up the
  posting's line from `byte_offset_to_position(source, p.span.start)`
  or via the pre-built `LineIndex` where one already exists.
- Plugin-synthesized postings (file_id == SYNTHESIZED_FILE_ID) are
  skipped explicitly (defensive — the LSP parses single files in
  practice, but consistent with the formatters).
- call_hierarchy's transaction-range also uses `spanned.span.end`
  instead of the `txn_line + postings.len() + 1` heuristic.

Regression tests pin the contract for the three highest-impact
handlers — `document_highlight`, `references`, `inlay_hints`. Each
runs the canonical `effective_date:` source and asserts no result
lands on a metadata line, plus a positive assertion that the real
posting lines are surfaced. The remaining handlers ride on the same
mechanical pattern; their tests can be added incrementally if a
specific handler regresses.

Out of scope for this PR (genuine false positives in earlier audit):

- `code_actions.rs` — the only matching grep hit was a window-search
  heuristic (`range.start.line + 10`), not posting arithmetic.
- `on_type_formatting.rs` / `execute_command.rs` — matches were for
  `is_posting_line()` content classifiers, not line indexing.

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (134 tests, 0 failures —
including 3 new #1142 regression tests, plus the existing 2 from
#1156), cargo fmt --all -- --check.

Refs #1142

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

github-actions Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 38.1ms ± 1.1ms 25.2 MB
beancount 783.5ms ± 18ms 50.7 MB
Comparison 20.6x faster 2.0x less

vs main branch (2026-05-19)

Metric main this PR Change
Time 35.4ms 38.1ms +7.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

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

This PR updates multiple rustledger-lsp “read-only” handlers to derive posting line locations from each posting’s parsed span rather than txn_start_line + 1 + idx, fixing incorrect LSP ranges when posting-level metadata is interleaved between postings (refs #1142).

Changes:

  • Sweep LSP handlers to resolve posting line numbers via posting spans (and skip SYNTHESIZED_FILE_ID postings).
  • Update formatting / range-formatting and document color logic to use LineIndex for offset→position conversions.
  • Add regression tests covering highlight/references/inlay-hints behavior with interleaved metadata fixtures.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
crates/rustledger-lsp/src/handlers/symbols.rs Use per-posting spans for posting child symbol line resolution; skip synthesized postings.
crates/rustledger-lsp/src/handlers/selection_range.rs Use per-posting spans when deciding whether the cursor is on a posting line.
crates/rustledger-lsp/src/handlers/references.rs Use per-posting spans for account reference ranges; adds regression test.
crates/rustledger-lsp/src/handlers/range_formatting.rs Switch to LineIndex and per-posting spans; adds regression tests for #1142.
crates/rustledger-lsp/src/handlers/linked_editing.rs Use per-posting spans for linked-editing account ranges.
crates/rustledger-lsp/src/handlers/inlay_hints.rs Use per-posting spans for hint placement; adds regression test.
crates/rustledger-lsp/src/handlers/formatting.rs Switch to LineIndex and per-posting spans; adds regression test for #1142.
crates/rustledger-lsp/src/handlers/document_highlight.rs Use per-posting spans for highlight ranges; adds regression test.
crates/rustledger-lsp/src/handlers/document_color.rs Use LineIndex + per-posting spans so amount colors land on the correct posting line.
crates/rustledger-lsp/src/handlers/call_hierarchy.rs Use posting spans for call ranges and derive transaction outer range from directive span.

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

CI's `Check` and `Doctests` jobs run with `RUSTFLAGS=-Dwarnings`,
which promotes `unused_variables` to an error. After PR #1157's
switch from `txn_start_line + 1 + i` arithmetic to per-posting span
lookup, the `start_line` binding in `collect_account_references` was
no longer read — every Transaction case derives its line from the
posting's own span, and the non-Transaction cases use
`spanned.span.start` directly via `find_in_directive`.

Local cargo check passes because the workspace's `.envrc` doesn't
set `RUSTFLAGS=-Dwarnings`; this is the same gap memorialized in
`feedback_check_cargo_doc_locally.md`. The two-file form of pre-push
verification I should be running for these LSP sweeps is:

    cd worktree
    RUSTFLAGS=-Dwarnings cargo build -p rustledger-lsp --all-features
    RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps

Refs #1142

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

github-actions Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 786
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

Apply Copilot review on PR #1157.

Performance (4 handlers): each posting/directive lookup previously
called `byte_offset_to_position` which is an O(n) scan; on a large
file with many transactions this scaled quadratically. Builds a
single `LineIndex` per request and threads it into the collect
helpers so every offset→line conversion is O(log lines):

- `inlay_hints.rs`
- `document_highlight.rs` (account / currency / payee collectors)
- `linked_editing.rs` (account / currency collectors)
- `references.rs` (account / currency / payee collectors + the
  `find_in_directive` helper that was called per-directive)

Correctness:

- `call_hierarchy.rs` transaction range was off-by-one. The previous
  fix used `spanned.span.end → (line, _).saturating_add(1)`, but
  `span.end` is *exclusive* and for newline-terminated transactions
  the resulting line is already the next line. Now: use the end
  line directly when `end_col == 0`, only round up when the span
  ends mid-line. Otherwise the call-hierarchy item range extended
  into the following directive.

Dead-code cleanup:

- Removed `let _ = line;` in `call_hierarchy::handle_outgoing_calls`
  — `line` is used at the enclosing scope's `if line != txn_line`
  check, so the suppression was a misread of the closure's capture
  rules.
- Removed `let _ = dir_range;` in `selection_range` — `dir_range` is
  the match binding and was destined to be used later in the
  hierarchy builder; the suppression hid an inert binding rather
  than silencing a real warning.

Verified: cargo check --workspace --all-features --all-targets,
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (134 tests, 0 failures),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 93a22df into main May 19, 2026
31 checks passed
@robcohen
robcohen deleted the feat/lsp-handlers-readonly branch May 19, 2026 22:52
robcohen added a commit that referenced this pull request May 20, 2026
…1158)

* refactor(lsp): align_amounts command delegates to formatting handler

`execute_command::rledger.alignAmounts` had its own bespoke posting-
alignment pipeline: a regex-style line scanner, an "Assets/Liabilities/
Equity/Income/Expenses" prefix check to identify posting lines, and a
"max-existing-column" alignment heuristic. It produced visibly
different output than the canonical paths:

- `rledger format` (CLI, uses `rustledger_core::format::format_directive`).
- `textDocument/formatting` (LSP, uses `handlers::formatting::handle_formatting`).

It also pre-dates #1142 and #1151 — so it didn't benefit from any of:

- Per-posting source spans (the bespoke line scanner can't see
  posting-level metadata interleaved between postings, just like the
  pre-#1142 formatting handlers).
- The shared `LineIndex` (#1157 perf fix) — every alignment computed
  its own line positions from scratch.

This commit deletes the bespoke pipeline and delegates to
`handle_formatting`. The command now inherits every formatter fix
automatically:

- Per-posting span lookup preserves interleaved metadata (#1142).
- Single `LineIndex` per request → O(log lines) offset lookups.
- Posting-line detection comes from the parsed AST, not a
  hard-coded account-prefix list (custom account roots from
  `option "name_assets" ...` now work).
- Plugin-synthesized postings (`file_id == SYNTHESIZED_FILE_ID`)
  are skipped consistently.

Removed code:

- `handle_align_amounts`'s 80-line scanner.
- `is_posting_line` / `find_amount_position` helpers (dead after
  the scanner was removed; the on_type_formatting handler has its
  own `is_posting_line` copy and is unaffected).
- Their two unit tests, replaced by one delegation smoke test that
  verifies both the misaligned-source and already-aligned shapes.

Verified: cargo check --workspace --all-features --all-targets,
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (133 tests, 0 failures),
cargo fmt --all -- --check.

Refs #1142

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

* refactor(lsp,core): unify LSP and CLI formatters via core::format_posting

Closes the deeper duplication this PR's first round only partially
removed. The LSP's `handle_formatting` had its own bespoke
`format_posting_line` with two latent problems:

1. **Column mismatch.** Hardcoded `AMOUNT_COLUMN = 50` constant in
   the LSP vs `FormatConfig::default().amount_column = 60` in core.
   `rledger format` (CLI, via `format_directive` → `format_posting`)
   wrote amounts to column 60 on disk; the editor's
   `textDocument/formatting` and `rledger.alignAmounts` produced
   column 50. The two never agreed.

2. **Silent data-shape loss.** The LSP's hand-rolled formatter
   handled only the account + units. It did NOT format cost specs
   (`{...}`) or price annotations (`@`/`@@`). For postings that
   carried them, the resulting "formatted" string was a strict
   subset of the source, the surrounding `needs_alignment` heuristic
   correctly refused to emit an edit (the tokenization didn't
   match), and the upshot was that **the LSP formatter silently
   never realigned cost-bearing or priced postings**.

This commit:

- Exports `rustledger_core::format::format_posting` (was
  module-private). It's the same function that `format_directive`
  already uses internally for posting rendering.
- Rewrites the LSP's `format_posting_line` to a thin wrapper around
  `format_posting`: format the posting via the core formatter using
  `FormatConfig::default()`, compare to the source line trimmed of
  trailing whitespace (which a separate pass strips), emit a
  TextEdit if they differ. The bespoke alignment math, the
  `needs_alignment` helper, and the `AMOUNT_COLUMN` constant are
  gone.
- Updates the `rledger.alignAmounts` command's docstring to reflect
  that all three formatting paths (CLI, LSP format, LSP align)
  share one source of truth.

Test:

- `test_align_amounts_produces_canonical_alignment` (replaces the
  earlier shape-only smoke test) applies the emitted edits to the
  source and asserts the amount column matches
  `FormatConfig::default().amount_column`. Pins the contract that
  the three paths agree on alignment.

Verified: cargo check --workspace --all-features --all-targets,
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (133 tests, 0 failures),
cargo fmt --all -- --check.

Refs #1142

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

* docs(lsp): clarify executeCommand can't carry client formatting options

Address Copilot review on PR #1158.

The previous comment claimed the synthesized `DocumentFormattingParams`
would let "future option-driven behavior land automatically", which
isn't true: `workspace/executeCommand` doesn't carry the client's
formatting preferences — those only travel with
`textDocument/formatting`. If `handle_formatting` ever honors
`params.options`, this command will keep using server defaults and
silently diverge.

The honest fix is documenting that, plus a forward-looking note that
the right solution (when this matters) is plumbing a server-wide
`FormatConfig` through both handlers, not mirroring a client value
this command can't actually see.

Refs #1142

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

* fix(lsp,core): preserve trailing comments via shared format_posting_line

The previous commit on this PR unified the LSP formatter with the
core formatter by routing through `format_posting`. That fixed the
column-mismatch and cost/price-drop bugs but introduced a new
data-loss regression: `format_posting` returns just account + amount
+ cost + price, omitting trailing comments. Any posting like

    Assets:Bank  -50.00 USD  ; my comment

now had its source line replaced with a `format_posting` output that
silently dropped `; my comment`. The previous bespoke LSP formatter
accidentally avoided this via its `needs_alignment` heuristic
(whitespace-token compare); my unification removed the heuristic
without restoring an equivalent guard.

Fix: extract `format_posting_line` in core that wraps
`format_posting` and appends the first same-line trailing comment
(matching what `format_transaction` already does inline). Both the
on-disk path (`format_transaction`) and the LSP edit path now call
the same helper. One source of truth for "what does a posting line
look like as one line".

Changes:

- `rustledger_core::format::format_posting_line` (new public fn) —
  wraps `format_posting` + appends `posting.trailing_comments[0]`.
- `format_transaction` in core uses it instead of the inline
  `if let Some(trailing) = ... writeln!(...)` block.
- LSP's `posting_text_edit` (renamed from the colliding
  `format_posting_line`) now calls
  `rustledger_core::format_posting_line`.

Test:

- `test_formatting_preserves_trailing_comment_on_posting` — feeds a
  misindented posting with a same-line `; comment`, asserts the
  resulting `TextEdit`'s `new_text` still contains the comment.
  Verified to FAIL against the bad version (calling `format_posting`
  directly).

Verified: cargo test -p rustledger-lsp -p rustledger-core
--all-features (134 LSP + 305 core, 0 failures);
cargo clippy --workspace --all-features --all-targets -- -D warnings;
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets;
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps;
cargo fmt --all -- --check.

Refs #1142

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

* refactor(lsp): extract format_document with shared FormatConfig helper

Address review item 2 (options divergence between handlers).

The previous shape had `handle_align_amounts` synthesizing a
`DocumentFormattingParams` with `options: Default::default()` and
passing it to `handle_formatting`. That hid the fact that the
executeCommand path has NO client formatting options to honor — it
just inherited whatever interpretation `handle_formatting` placed on
the synthetic default. The moment `handle_formatting` learned to
read `params.options`, the two paths would diverge silently.

Fix:

- Split `handle_formatting` into two functions:
  * `handle_formatting(params, source, parse_result)` — the LSP
    protocol wrapper, takes the client's `DocumentFormattingParams`,
    resolves a `FormatConfig` from `params.options` via
    `document_format_config(Some(...))`.
  * `format_document(source, parse_result, &FormatConfig)` — the
    pure formatting body, takes an already-resolved config.

- New `handlers::utils::document_format_config(opts: Option<&FormattingOptions>) -> FormatConfig`
  is the single place that maps LSP options → `FormatConfig`. Today
  it ignores `opts` and returns `FormatConfig::default()`; when
  server-config plumbing lands, that one function changes. The
  `Some` / `None` distinction is preserved so the helper can fall
  back to server defaults when the executeCommand path provides no
  client value.

- `handle_align_amounts` now calls
  `format_document(source, parse_result, &document_format_config(None))`
  directly — no more fake `DocumentFormattingParams`. The `None`
  literally encodes "no client options here," and the comment
  documents why.

This contains the divergence risk to a single function (the helper)
and a single boolean (`Some`/`None`). When the LSP server gains real
config, both paths benefit automatically.

Verified: cargo test -p rustledger-lsp --all-features (134 tests, 0
failures); cargo clippy --workspace --all-features --all-targets --
-D warnings; RUSTFLAGS=-Dwarnings cargo build --workspace
--all-features --all-targets; RUSTDOCFLAGS=-Dwarnings cargo doc
--workspace --no-deps; cargo fmt --all -- --check.

Refs #1142

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 20, 2026
…) (#1170)

* perf(lsp): finish LineIndex sweep across remaining handlers (refs #1157)

Closes out the per-posting O(n) byte_offset_to_position regression
Copilot flagged on #1157. Earlier follow-ups already converted
references / inlay_hints / linked_editing / document_highlight /
formatting / range_formatting; this finishes the sweep across the
seven handlers that still scanned the source linearly per directive:

- call_hierarchy.rs (8 sites — the one Copilot explicitly flagged)
- type_hierarchy.rs (2 sites + find_account_location helper)
- code_actions.rs (5 sites incl. find_open_directive_position and
  check_unbalanced_transactions, plus the resolve path)
- workspace_symbols.rs (1 site, per-directive in collect loop)
- semantic_tokens.rs (apply_directive_modifiers — per-directive
  scan, hit on every semantic-tokens / delta / range request)
- document_links.rs (per-Document directive)
- execute_command.rs (sortTransactions edit range)

In each case the handler now builds a LineIndex once at the entry
point and passes it through. line_text(source, line) replaces the
remaining source.lines().nth(line) scans for posting/account span
text extraction.

byte_offset_to_position remains in utils.rs as a documented helper
for ad-hoc one-off conversions; no production handler calls it now.

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

* perf(lsp): drop source.lines() collect in is_account_in_range

Addresses Copilot review on #1170: is_account_in_range still did
`source.lines().collect::<Vec<_>>()` per call to scan a small
13-line window around the cursor. Since the function runs once per
undefined account, the per-call full split dominated runtime on
large files.

Use line_index.line_text(source, idx) to fetch only the windowed
lines (no allocation, leverages the request-local LineIndex that
already exists).

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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