Files
lucisv/docs/features/selection-range/README.md
T
lucioandClaude Fable 5 aa303ce9ae
release / build-and-publish (push) Successful in 3m29s
LSP §9a: applyEdit compliance, pull diagnostics, expand selection; v0.8.0
The three top findings of the LSP 3.18 audit (TODO.md §9), one round of
dev (Opus) + QA (Sonnet) + lead review:

- executeCommand now pushes its WorkspaceEdit as workspace/applyEdit and
  reads the client's verdict; the old return-the-edit behavior stays as
  the documented fallback for clients without the capability. This fixes
  the three port commands doing nothing in stock clients — the returned
  edit was dropped by vscode-languageclient and Neovim alike.
  docs/features/apply-edit/README.md
- textDocument/diagnostic + workspace/diagnostic (LSP 3.17), served from
  the same parse+lint pass the push model publishes, with resultId /
  unchanged caching on one generation counter; a pulling client is pushed
  nothing, a pushing client is unchanged. QA's exhaustive input trace
  found no stale-unchanged path. docs/features/pull-diagnostics/README.md
- textDocument/selectionRange: chains from token spans, the tolerant
  parse's item/statement spans and the scope-pair matcher, filtered to
  strict nesting; the invariant swept over all 860 corpus files (6,880
  positions, held everywhere). docs/features/selection-range/README.md

43 tests added across unit/e2e (server 557 -> 594+ unit, 29 -> 32 e2e);
fmt/clippy/test/smoke all clean, re-verified independently by QA and by
the lead.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 11:06:51 -07:00

228 lines
12 KiB
Markdown

# selection-range
## Goal
`textDocument/selectionRange` — expand-selection, the keystroke (⌃⇧→ in VS
Code, `<Plug>(expand_region)` shapes in Vim) that grows the selection one
syntactic step at a time: the identifier, then the statement, then the block,
then the module, then the file. Editors fall back to a word/bracket heuristic
without it, which in Verilog means expanding through `begin`/`end` never
works. Cheap for lucisv: every range the chain needs is already computed for
something else, so this is a new arrangement of existing answers, not new
analysis.
## Assumptions
- **Four sources of ranges, one chain.** For a byte offset the server
collects: the token that covers it (`Document.tokens`), the AST spans that
cover it (items and statements, walked top-down and pruned to the branch
that contains the offset), the matched scope pairs that cover it
(`pairs::analyze`, the rainbow's own matcher), and the whole file. They are
sorted by width and filtered down to what actually nests.
- **No expression step.** The brief allows skipping it, and it is skipped:
`ExprKind` has ~40 variants and walking them is a large, dull function
whose only user would be this. The visible cost is that inside
`a + b * (c - d)` the chain jumps from the token straight to the statement.
The token step covers the common "select the identifier" case, and adding
expressions later is additive — one more source of spans, no change to the
chain machinery. Recorded so nobody thinks it was overlooked.
- **The chain must strictly nest, and is filtered rather than trusted.** Two
ranges that both cover the cursor need not contain one another: a tolerant
parse can leave an item span overlapping a scope pair. LSP requires every
step to contain its child, so a range that does not enclose what was kept
before it is dropped. That filter is also what removes the duplicates the
four sources produce for the same construct (a `module` is an item span
*and* a scope pair).
- **Zero-width ranges are dropped.** A step that selects nothing is not a
step a user can see. The one exception is the degenerate chain in an empty
buffer, where the file range itself is empty.
- **Containment includes the end offset.** A cursor sitting just after a word
is treated as on that word — that is where the keystroke is usually
pressed. The consequence at a boundary between two adjacent constructs is
that both cover the cursor; the nesting filter then keeps whichever is
smaller and drops the other, which is a valid chain either way.
- **Every requested position is answered, in order.** A multi-cursor editor
matches answers to cursors by index, so a skipped position would silently
mis-associate every later one. A position that resolves to nothing else
still gets the one-step file chain.
- **A file that does not lex answers the file range.** `Document::new` leaves
`tokens` empty and the tree an error leaf there, so three of the four
sources give nothing — and the fourth is enough to satisfy the protocol.
- **The walk is per-request and bounded.** It descends only into the node
that covers the offset, so it visits the cursor's ancestors and their
immediate siblings' spans, not the file. Recursion depth is bounded by the
parser's own nesting limit (`docs/features/recursion-limit/README.md`): a
tree this walks is a tree the parser built.
## Handshakes
### `lucisv_server::selection` (new module)
```rust
pub fn selection_ranges(doc: &Document, positions: &[Position]) -> Vec<SelectionRange>;
```
Pure function over one `Document`, in the shape `folding.rs` and `pairs.rs`
already have: no `Workspace`, no client, unit-testable on a string.
### `lucisv_server::main`
`capabilities()` gains `selection_range_provider:
SelectionRangeProviderCapability::Simple(true)`. Nothing is configurable and
every position is answered, so there are no options to send.
### `lucisv_server::server`
One handler on `SelectionRangeRequest::METHOD`, answering `null` for a
document that is not open — the same shape `foldingRange` and
`documentSymbol` already use.
### `vlog_parser::ast`
Consumed read-only: `Item`/`ItemKind`, `Stmt`/`StmtKind`, `GenBlock`,
`GenElse`, `GenIf`, and the `span` fields on all of them. No change requested
of the parser. The walk duplicates the shape of `vlog_linter::visit`, which
is `pub(crate)` there and therefore not reusable; the copy here is ~60 lines
and prunes by offset, which the linter's does not.
### `editors/*`
No change: both VS Code and Neovim bind expand-selection to this request out
of the box.
## Status / TODO
- [x] `crates/lucisv_server/src/selection.rs`: token, AST, scope-pair and
file sources; nesting filter; linked-chain construction
- [x] `selection_range_provider` advertised
- [x] `textDocument/selectionRange` handled, `null` for an unopened buffer
- [x] Tests: 14 unit tests in `selection.rs` (including an exhaustive
"every step strictly contains its child, at every offset of a file"
sweep) and 2 in `server.rs`
- [ ] Not done, deliberately: no expression-level step — see Assumptions.
- [ ] Not done, deliberately: no port/parameter-list step. `AnsiPort` and
`ParamPort` carry spans, so it is a two-line addition when someone
wants it; today the chain inside a header goes token → module.
## Work log
### 2026-08-26 — dev agent, §9a
- **Collect-then-filter, rather than build the chain while walking.** The
walk cannot know whether a scope pair will land between two of its own
spans, and a tolerant parse can produce spans that overlap rather than
nest. Throwing every covering range into one list and keeping what nests is
both shorter and provably correct — the invariant is checked in one place,
and `every_step_strictly_contains_the_one_before_it` sweeps every offset of
a nested file to prove it.
- **Scope pairs are kept even though the AST usually covers the same
constructs.** They are what still works when the parse went wrong, which is
exactly the buffer a user is mid-edit in
(`an_unclosed_scope_still_expands_through_what_did_close`).
- **The AST walk was copied, not shared.** `vlog_linter::visit` is
`pub(crate)`; making it public is a change to another crate for one caller,
which the brief forbids and CLAUDE.md discourages. The copy is smaller than
the original because it prunes on the offset.
- Files touched: `crates/lucisv_server/src/selection.rs` (new),
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/src/server.rs`,
`crates/lucisv_server/tests/e2e.rs`, and the capability table in
`docs/features/lucisv-server/README.md`.
**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings),
`cargo test --workspace`, `node editors/vscode/smoke.js` — all clean. 14 unit
tests in `selection.rs`, 2 in `server.rs`, and one e2e session
(`selection_ranges_round_trip_over_the_wire`) proving the chain survives JSON
encoding as nested `parent` objects.
## QA log
### 2026-08-26 — QA agent, §9a
**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`,
`cargo clippy --all-targets --workspace` (zero warnings), `cargo test
--workspace` (3 full runs, no failures), `node editors/vscode/smoke.js
target/debug/lucisv-server` (exit 0).
**The strictness claim, checked, not just trusted.**
`every_step_strictly_contains_the_one_before_it` (`selection.rs`) does assert
`outer != inner` in addition to containment, at every offset `0..=text.len()`
of a nested fixture — it is a real strictness sweep, not a containment-only
check with a misleading name.
**Invariants from the assignment, checked one by one against existing
tests** (all present, all passing, no gaps found that needed a new test):
- Multi-position order: `several_positions_are_answered_position_for_position`
asks three positions out of source order and checks each answer against
its own position by index.
- Position past EOF: `a_position_past_the_end_of_the_file_clamps_into_it`.
- UTF-16 / surrogate-pair-adjacent columns: `a_multibyte_line_keeps_the_
columns_in_utf16` uses `é` (2-byte UTF-8, 1 UTF-16 unit) **and** `🎉`
(4-byte UTF-8, a UTF-16 *surrogate pair*) on the same line before the
target token — this is the specific case the assignment called out, and
it is already exercised, not just the single-BMP-character case.
- Empty file: `an_empty_file_still_answers_one_degenerate_chain`.
- A file that fails to parse: `a_file_that_does_not_lex_still_answers_the_
file_range` (confirms `doc.tokens.is_empty()` as the premise, then checks
the fallback) and `an_unclosed_scope_still_expands_through_what_did_close`
(a tolerant *partial* parse — checks the scope-pair source still supplies
a step when the AST cannot).
- Capability reading: `selection_range_provider` is `Simple(true)`, no
conditional read of client capabilities at all — nothing to break here.
**Went beyond the assignment's list: a corpus sweep.** Every hand-written
test above uses a handcrafted fixture designed to exercise one specific
construct — none of them can catch a real-world construct the four span
sources disagree about in a way nobody thought to write a test for. Added
`every_step_strictly_nests_over_the_real_corpus` to `selection.rs`: walks
every `.sv`/`.v`/`.svh`/`.vh` file under `corpus/` (skipped gracefully if not
checked out, matching this crate's other corpus tests), samples 8 evenly
spaced offsets per file, and asserts the same strict-nesting-plus-whole-file-
closure invariant the hand-written sweep proves on small fixtures. Result:
**860 files, 6,880 positions, zero panics, invariant held everywhere**,
runtime ~1.6s (fits comfortably in the default `cargo test` budget, not
`#[ignore]`d). This is real coverage of syntax nobody wrote a fixture for —
generate-for loops, deeply nested casex/casez, `ifdef`-gated regions, etc.
— that the four hand-picked test files cannot reach.
**Two positions I could not distinguish as bugs vs. accepted design,
recorded rather than "fixed":**
- `covers()`'s inclusive end (`span.start <= offset && offset <= span.end`)
means a cursor at the exact boundary between two adjacent siblings sees
both as covering it; the nesting filter then keeps whichever is smaller.
This is explicitly called out in the Assumptions as intentional and
provably safe (the filter guarantees strict nesting regardless of which
one wins), so not re-litigated.
- The AST walk in `items`/`statement` is a hand-copy of
`vlog_linter::visit`'s shape rather than a shared function, per the
Assumptions' stated reason (`visit` is `pub(crate)` in another crate).
Confirmed by reading `vlog_linter/src/visit.rs`'s visibility — it is
indeed `pub(crate)`, so the stated constraint is real, not just asserted.
**CLAUDE.md compliance:** `selection.rs`'s only `pub` item
(`selection_ranges`) has a doc comment; no `unwrap()`/`expect()`/`panic!`
outside `#[cfg(test)]` in `selection.rs`, or in the touched parts of
`server.rs`/`main.rs`. README has all seven sections; TODO.md checkbox is
checked with item text unchanged.
**Verdict: no blocking findings.** This is the most heavily self-tested of
the three features already (14 unit tests, an exhaustive small-file sweep);
the corpus sweep added here is a genuine widening of coverage, not a
response to a suspected bug, and it found none.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
clean. `nested()`'s sort-then-keep-what-strictly-contains is the right
five-line answer to the overlapping-sources problem, and the fallback chain
for an empty/unlexable buffer honors the protocol's one-answer-per-position
requirement without a special case in the dispatch. Skipping the expression
step was the correct scope call — the token step already gives "select the
identifier", and forty `ExprKind` arms is a follow-up, not a blocker. QA's
860-file corpus sweep (6,880 positions, invariant held everywhere) is
exactly the kind of evidence this repo's rounds are supposed to produce.
Accepted as shipped.