Compare commits

...
11 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 dbd2f176aa Release 0.9.0 — the §9b performance-model release
release / build-and-publish (push) Successful in 3m28s
Version bump (workspace + extension) and the CHANGELOG section covering
the five §9b rounds: incremental sync, willSaveWaitUntil, semantic
token range/delta, indexing progress, $/cancelRequest. Tagging is the
owner's call — a tag push triggers the full cross release.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 14:11:59 -07:00
lucioandClaude Fable 5 6523c604bb LSP §9b: $/cancelRequest — burst reads, stateless cancellation
run() now reads in bursts: one blocking receive plus everything already
queued behind it, processed strictly in arrival order. A request whose
$/cancelRequest sits in the same burst is answered RequestCancelled
(-32800) without being dispatched; cancels naming anything else — an
already-answered request, one never received, a server-initiated id —
are dropped on the spot, so cancellation holds no state that can leak
or misfire. shutdown is honoured before the cancel set is consulted,
and a didChange queued ahead of a request is still applied first.

The enabling change: lsp-server 0.10's stdio transport uses rendezvous
channels, so a client's backlog never queues on connection.receiver —
it sits invisible in the OS pipe (dev measured 0/5 cancels honoured
under the original drain design). A single forwarder thread moves
messages onto an unbounded queue, stopping at shutdown because
handle_shutdown reads the following exit off the connection itself.
First thread in this server; QA re-derived the hand-off from the
vendored lsp-server source and found no steal or deadlock window.

15 tests added (dev 11 + QA 4), covering the full cancel matrix (both
id types, double cancel, orphan drop with id-reuse proof, malformed
params), the forwarder against a real Connection, and an e2e flood of
20 requests with cancels asserting schedule-independent properties —
green across twelve consecutive runs. Completes TODO.md §9b.

docs/features/cancel-request/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 14:10:59 -07:00
lucioandClaude Fable 5 e165c37a3a LSP §9b: work-done progress on workspace rescans
Every index rescan — the startup build included — now puts up a real
progress bar for clients that advertise window.workDoneProgress:
window/workDoneProgress/create with a fresh lucisv-index-N token, a
Begin titled 'Indexing Verilog workspace' (cancellable: false — nothing
in a single-threaded server can cancel; no percentage — the rescan is
one opaque call and an invented number would be a lie), the scan, then
End naming the indexed file count. The Option<ProgressToken> returned
by begin_indexing IS the capability gate, so an unpaired or uninvited
bar is structurally impossible; create answers ride the existing
ignored-response path with no risk to applyEdit routing (one shared id
counter). The startup build got the bar because initialize_finish
completes before Server::new — the same fact watcher registration
already relied on.

14 tests added (dev 10 + QA 4: watcher-after-bar ordering, both
response-interleaving directions, capability-off on the watcher/config
paths, rootless zero-count startup), all decoding real wire JSON for
the sequence, token type, title, and message.

docs/features/work-done-progress/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 13:30:01 -07:00
lucioandClaude Fable 5 00c03eccf9 LSP §9b: semantic tokens range + full/delta
tokens.rs is now one tokenizer behind three pure steps — absolute()
classifies and splits, within() filters by overlap, encode() delta-
encodes — so textDocument/semanticTokens/range and /full share one
implementation and cannot drift; QA proved the refactor byte-identical
to the old encoder over a 41k-token corpus file against the pre-change
binary. Range answers are self-contained (overlapping tokens kept
whole, re-encoded from the document start) and carry no resultId — a
delta never diffs against a partial view.

/full/delta remembers each open buffer's last answer under a per-answer
id (dropped on didClose; stale or foreign ids answer full) and diffs by
common-prefix/suffix trim to a single edit, the suffix counted over
what the prefix left — the classic overlap trap, deliberately broken by
dev and QA separately and caught by the suite both times. Edit indices
are wire-array u32 positions (5 per token), pinned. No token request
touches the pull-diagnostics generation.

38 tests added (dev 29 + QA 9), including two independently written
edit appliers cross-checked over 200 random pairs and two differently
seeded randomized sweeps through the real tokenizer.

docs/features/semantic-tokens-delta/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 13:03:56 -07:00
lucioandClaude Fable 5 80b9afdfe3 LSP §9b: willSaveWaitUntil — protocol-native format-on-save
textDocument/willSaveWaitUntil is advertised and served, gated on a new
lucisv.formatOnSave setting that defaults to off (a server that formats
uninvited fights the editor's own format-on-save and doubles up); the
decline is one comparison, before any buffer lookup. When on, the hook
is textDocument/formatting with a different trigger: the same engine,
the same all-or-nothing verified-output contract, settings resolved by
the new format::settings_without_editor_options — the ladder minus the
tabSize rung the protocol simply does not carry here, with the honest
consequence (save-format can differ from manual format without a
lucisv.toml) documented in the README, the VS Code setting description
and the nvim README. Every save reason formats; refusals are shown per
save, on purpose.

18 tests added across settings/format/server/e2e, including QA's
executable proofs of the tab-size gap and its lucisv.toml resolution, a
no-reindex/no-generation-bump guard for the new setting, and an
idempotency round-trip through a real didChange. QA also fixed the
stale 'not advertised' feature list in editors/nvim/README.md and
sharpened the config-warning dedup claim to what the code does (once
per buffer state) — reworded in the README, pinned by test.

docs/features/will-save-wait-until/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 12:21:00 -07:00
lucioandClaude Fable 5 c2ea1a11f6 LSP §9b: incremental text sync
textDocument/didChange now applies ranged content changes instead of
requiring the whole buffer per keystroke. New pure sync::apply_changes
applies each change against the document as the previous ones left it
(fresh line table per change), clamping inherited from convert.rs and a
backwards range read as a pure insertion — the one rule that cannot lose
text. One notification stays one reparse / one generation bump / one
publish. Full-sync clients (rangeless changes) keep byte-identical
behavior; save advertises includeText: false and didSave still honours
text when sent.

35 tests added (28 unit incl. a 400-sequence randomized cross-check
against an independent reference model and QA's surrogate/CRLF/final-
newline attacks, 6 server-level, 1 e2e pinning the wire capability
shape). QA's one finding — CRLF split across two same-position inserts
in one batch lands \n\r — is pre-existing convert.rs behavior, pinned
by test, unreachable by real clients; see the feature README.

docs/features/incremental-sync/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 11:49:58 -07:00
lucioandClaude Fable 5 aa303ce9ae LSP §9a: applyEdit compliance, pull diagnostics, expand selection; v0.8.0
release / build-and-publish (push) Successful in 3m29s
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
lucioandClaude Fable 5 d3081d6aaf TODO: LSP 3.18 protocol audit — full gap list as §9, round 1 scoped
Compared lucisv_server against the LSP 3.18 spec. §9a is the round-1
scope (applyEdit compliance, pull diagnostics, selectionRange), §9b/9c
the ranked backlog, §9d the documented skips.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 10:26:03 -07:00
lucioandClaude Fable 5 c556a13857 CI: corpus score is a gate, releases audit their artifacts; v0.7.2
ci / checks (push) Successful in 36s
ci / corpus (push) Successful in 26s
release / build-and-publish (push) Successful in 3m7s
The corpus job scores the pinned-rev corpus (cached at
~/.cache/lucisv-corpus on the runner, fetched once on a miss) on every
push and fails below scripts/corpus-baseline (813) or on any
verification error / crash. The release workflow now runs
tools/audit_artifacts.sh before publishing: musl must be fully static,
linux-gnu's glibc ceiling must stay <= 2.28 (RHEL 8), every file must be
the object format its name claims — verified against the 10 real v0.7.1
release binaries. Linux execution under Docker was considered and
declined: no container runtime on the runner. Version 0.7.2 with a
changelog covering this, the printer column fix and the README truth
pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 02:13:04 -07:00
lucioandClaude Fable 5 b560909a76 README truth pass: releases exist now, and the server reads lucisv.toml
The v0.7.1 release made three claims false: 'there are no prebuilt
downloads' (the releases page now has five platforms + the .vsix per
tag), 'the script builds for the host triple only' (--cross has existed
since 0.7.0's cross-platform release), and the hardcoded
lucisv-0.5.0.vsix example. The bigger correction: the 'server does not
read lucisv.toml yet' caveat has been stale since the config ladder
landed in lucisv_server/src/format.rs -- replaced with the actual
precedence (lucisv.toml > lucisv.* settings > tab size > default). Also
states plainly that Linux/Windows artifacts are audited, not executed.
.DS_Store untracked and gitignored.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 02:10:54 -07:00
lucioandClaude Fable 5 53f226981f printer: multi-line raw text keeps the column honest
Raw text carrying a string literal across a line break, and the #( ... )
of a parameterized type, were emitted as a single Doc::Text with embedded
newlines -- violating that variant's contract and leaving the printer's
column tracker stale, so every later fits() on the line broke
conservatively. Both now emit Doc::Inline, whose printer arm resumes
measuring from the text's own last line. Output bytes are identical
except where the stale column forced a spurious break: one corpus file
(id_queue_tb.sv) improves, pass set unchanged at 813/820, verify.rs
untouched. Found by QA in the directive-split round; pinned by a printer
test and a classes.cases entry.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 02:10:10 -07:00
40 changed files with 8882 additions and 168 deletions

No files matched your search

Vendored
BIN
View File
Binary file not shown.
+21 -4
View File
@@ -1,8 +1,7 @@
# CI: the three checks CLAUDE.md requires before any work is finished,
# enforced on every push. Runs on the self-hosted mac-arm64 runner in host
# mode (no containers), so the toolchain is the same one releases are built
# with. The corpus is not in the repository, so corpus scoring stays a
# local-only check (scripts/score.sh).
# plus the corpus gate, enforced on every push. Runs on the self-hosted
# mac-arm64 runner in host mode (no containers), so the toolchain is the
# same one releases are built with.
name: ci
on:
push:
@@ -20,3 +19,21 @@ jobs:
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --workspace
# The 99.1% headline, enforced: score the 820-file corpus and fail on any
# regression below scripts/corpus-baseline (verification errors and
# crashes fail outright). The corpus is pinned-rev clones (not in the
# repo), cached on the runner host and fetched once on a cache miss.
corpus:
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
- name: Ensure the cached corpus
run: |
corpus="$HOME/.cache/lucisv-corpus"
[ -d "$corpus" ] || tools/corpus_fetch.sh "$corpus"
echo "CORPUS=$corpus" >> "$GITHUB_ENV"
- name: Build the release binary the scorer drives
run: cargo build --release -p lucisv
- name: Score and gate
run: scripts/corpus_gate.sh "$CORPUS"
+2
View File
@@ -21,6 +21,8 @@ jobs:
- uses: actions/checkout@v4
- name: Build release artifacts for every target
run: tools/release.sh --cross
- name: Audit the cross-built artifacts
run: tools/audit_artifacts.sh dist
- name: Check the tag against the crate version
run: |
v=$(target/release/lucisv --version | awk '{print $2}')
+1
View File
@@ -4,3 +4,4 @@
/dist
/.lucisv_cache
/.score-results.tsv
.DS_Store
+135
View File
@@ -4,6 +4,141 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.9.0 — 2026-08-26
The performance-model release: TODO.md §9b, the high-value half of the
LSP 3.18 audit, shipped one feature per dev/QA/review round.
### Incremental text sync
A keystroke now costs one range on the wire, not the whole file. Edits
are applied by one pure function with clamping rules inherited from the
existing position converter — a backwards range becomes a pure
insertion, the only reading that cannot lose text — cross-checked
against an independent reference model over 400 randomized edit
sequences. One notification is still one reparse, one diagnostics
generation, one publish.
### Format on save (willSaveWaitUntil)
The protocol's native format-on-save hook, for editors without one of
their own. Off by default (`lucisv.formatOnSave`) so it never fights an
editor that already formats on save; when on, it is the formatting
request with a different trigger — same engine, same verified-output,
all-or-nothing contract. The one protocol gap (no editor tab size on
this path) is documented rather than papered over.
### Semantic tokens: range and delta
`semanticTokens/range` answers just the lines the editor is showing;
`full/delta` answers edits against the previous result instead of the
whole token set. One tokenizer and one pure encoder serve full, range
and delta, proven byte-identical to the old encoder over a 41k-token
corpus file; the delta's single-edit diff carries the classic
prefix/suffix overlap trap, deliberately broken twice (dev and QA,
independently) to prove the suite catches it.
### A progress bar on indexing
Every workspace rescan — the startup build included — now shows a real
progress bar in clients that support one: what is being indexed, no
invented percentages, and an honest file count when it comes down.
### $/cancelRequest
The server reads its backlog in bursts and answers a request whose
cancel arrived alongside it with RequestCancelled instead of computing
it — completion requests a fast typist already outran no longer cost a
parse each. Cancellation is stateless by construction: a cancel matters
only next to its own request, everything else is dropped on sight, and
no cancel can talk the server out of a shutdown. Enabled by the
server's first thread — a 12-line forwarder that makes the client's
backlog observable at all through lsp-server's rendezvous channels.
## 0.8.0 — 2026-08-26
The protocol-compliance release: the server was audited line-by-line
against the LSP 3.18 specification (the full gap list is TODO.md §9),
and the three findings that matter most shipped in one round.
### Port commands now actually edit (workspace/applyEdit)
`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked
as *commands* did nothing in every stock client: the server returned the
`WorkspaceEdit` as the `executeCommand` result, which the protocol does
not define and which `vscode-languageclient` and Neovim both drop. (The
code-action lightbulb path was never affected — those edits ride inline.)
The server now pushes the edit as a `workspace/applyEdit` request with a
label for the undo stack, answers `null`, and reads the client's verdict:
a refusal becomes an error popup naming the command and the editor's own
reason. A client that never advertised `workspace.applyEdit` keeps the
old return-the-edit behavior — for that one it is the only thing that
could ever work.
### Pull diagnostics (LSP 3.17)
`textDocument/diagnostic` and `workspace/diagnostic` are served, from the
same parse+lint pass the push model publishes — one computation, two
deliveries, proven byte-identical in tests. Reports carry a `resultId`
and answer `unchanged` when nothing that feeds them has moved, so a
client re-pulling on focus changes costs nothing. A client that pulls is
pushed nothing at all — never both models for one client. Clients that
don't advertise the capability keep today's push behavior untouched.
Workspace reports cover the open buffers, which is the only scope this
server has ever diagnosed.
### Expand selection (textDocument/selectionRange)
One keystroke grows the selection from the identifier through the
statement, the enclosing `begin`/`end`, the process, the module, out to
the whole file. Chains are built from what the server already computes —
token spans, the tolerant parse's item/statement spans, and the
rainbow's own scope-pair matcher, which keeps expansion working in the
half-edited files where you actually reach for it. Every step strictly
contains the last; a sweep over all 860 corpus files (6,880 positions)
holds the invariant everywhere.
## 0.7.2 — 2026-08-26
Honest columns, honest docs, and a CI that enforces the headline number.
### Formatter: the printer's column survives multi-line raw text
Raw text that carries a string literal across a line break, and the
`#( ... )` of a parameterized type reference, were emitted as a single
text node with embedded newlines — leaving the printer's column tracker
stale for the rest of the line, so later width checks broke
conservatively. Both now ride the `Doc::Inline` path, which resumes
measuring from the text's own last line. Bytes only change where the
stale column forced a spurious break: across the 813-file passing corpus
exactly one file improves (a `= new;` initializer after a multi-line
`#( ... )` rejoins its line). Found by adversarial QA during 0.7.1's
directive-split round.
### README truth pass
0.7.1's release page made the README wrong in three places, now fixed:
prebuilt downloads exist (five platforms + the `.vsix` per release, with
`SHA256SUMS`), `tools/release.sh` grew `--cross` a while ago, and the
sideload example no longer hardcodes `0.5.0`. One claim was stale in the
other direction: the "server does not read `lucisv.toml` yet" caveat —
the server has read it since the config ladder landed; the README now
states the actual precedence (`lucisv.toml` > `lucisv.*` settings >
editor tab size > defaults). The README also now says plainly that
Linux/Windows artifacts are cross-built and audited, not executed.
`.DS_Store` is untracked and ignored.
### CI: the corpus score is a gate, and releases audit their artifacts
The 99.1% corpus number is now CI-enforced: every push scores the
820-file corpus (pinned-rev cache on the runner) and fails on any drop
below `scripts/corpus-baseline` — and on any verification error or
crash, which are formatter bugs at any count. Release builds audit every
cross-built binary before publishing (`tools/audit_artifacts.sh`): the
musl build must be fully static, the linux-gnu build's glibc ceiling
must stay ≤ 2.28 (RHEL 8), and every file must be the object format its
name claims. Details: `docs/features/ci-release/README.md`.
## 0.7.1 — 2026-08-26
Conditional-split recovery and an automated release.
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.7.1"
version = "0.9.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.7.1"
version = "0.9.0"
[[package]]
name = "lucisv_server"
version = "0.7.1"
version = "0.9.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.7.1"
version = "0.9.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.7.1"
version = "0.9.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.7.1"
version = "0.9.0"
[[package]]
name = "vlog_refactor"
version = "0.7.1"
version = "0.9.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.7.1"
version = "0.9.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.7.1"
version = "0.9.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+31 -17
View File
@@ -610,8 +610,9 @@ go-to-definition, references and document/workspace symbols — the full list,
and what is deliberately *not* advertised yet, is in
`docs/features/lucisv-server/README.md`.
**The binary comes from the same build as the CLI**, and nothing downloads it
for you:
**The binary comes from the same build as the CLI.** Download it from the
[releases page](https://git.luci.ooo/lucio/lucisv/releases) for your
platform, or build it yourself:
```bash
cargo build --release # target/release/lucisv-server (and target/release/lucisv)
@@ -626,11 +627,12 @@ registering the file types and starting the server:
```bash
tools/release.sh # builds dist/lucisv-<version>.vsix
code --install-extension dist/lucisv-0.5.0.vsix
code --install-extension dist/lucisv-<version>.vsix
```
Sideloading that `.vsix` is the supported install; the extension is not on any
marketplace. To package it by hand instead: `cd editors/vscode && npm ci &&
The `.vsix` is also attached to every release on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases). Sideloading it
is the supported install; the extension is not on any marketplace. To package it by hand instead: `cd editors/vscode && npm ci &&
npx @vscode/vsce package`.
Settings are listed in `editors/vscode/README.md`, along with the full steps,
@@ -665,10 +667,13 @@ to the folder walk, so the index is never silently empty.
the handshake and the advertised capabilities are intact — which tells you
whether a failure is the server or your editor config.
One caveat, stated up front: the server does **not** read `lucisv.toml` yet, so
formatting through an editor uses the defaults (100 columns, 2-space indent)
with the editor's tab size overriding the indent. `lucisv` on the command line
does read it.
**Formatting through an editor reads `lucisv.toml` too**, discovered from the
buffer's own path by the CLI's rule, so format-on-save agrees with what
`lucisv --check` does in CI. Precedence, highest first: `lucisv.toml`, then
the editor's `lucisv.lineLength`/`lucisv.indent` settings, then the editor's
tab size (indent only — the protocol carries no line-length), then the
defaults. A broken config never blocks formatting: the buffer is formatted
with the next rung down and the error is surfaced in the editor.
## Contributing / workflow
@@ -687,18 +692,27 @@ expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
## Install and releases
There are no prebuilt downloads: you build the artifacts, or someone builds
them for your platform and hands you the files.
Prebuilt downloads live on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases): every tagged
version carries `lucisv` and `lucisv-server` for Apple Silicon and Intel
macOS, static-musl and RHEL 8-compatible glibc Linux, and Windows, plus the
`.vsix` and a `SHA256SUMS` to verify them with
(`shasum -a 256 -c SHA256SUMS`). Copy the two binaries onto your `PATH` and
sideload the extension with `code --install-extension`. The macOS binaries
are smoke-tested on the build machine; the Linux and Windows ones are
cross-built and audited (file type, dynamic-linkage, glibc-version ceiling),
not executed — there is no Linux or Windows machine in the loop.
To build the same artifact set yourself:
```bash
tools/release.sh # release binaries + the .vsix + SHA256SUMS, into dist/
tools/release.sh # host binaries + the .vsix + SHA256SUMS, into dist/
tools/release.sh --cross # ...plus the four cross-built platforms
```
`dist/` then holds `lucisv-<version>-<host-triple>`,
`lucisv-server-<version>-<host-triple>`, `lucisv-<version>.vsix` and `SHA256SUMS`
(verify with `cd dist && shasum -a 256 -c SHA256SUMS`). Copy the two binaries
onto your `PATH` and sideload the extension with `code --install-extension`.
The script builds for the host triple only and publishes nothing anywhere.
The script itself publishes nothing anywhere; publishing is CI's job —
pushing a `vX.Y.Z` tag builds all of the above on Gitea Actions and attaches
it to a release, with that version's `CHANGELOG.md` section as the notes.
Release notes are in [`CHANGELOG.md`](CHANGELOG.md); the full checklist —
where the version number lives, how the `.vsix` is packaged, and what
+184
View File
@@ -627,3 +627,187 @@ section only tracks the milestones.
CHANGELOG entry covering M7–M14.
- [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion,
organize imports, …) — triaged in the umbrella README after M5.
## 9. LSP 3.18 protocol audit (2026-08-26)
Systematic comparison of `lucisv_server` against the LSP 3.18
specification. What we implement: hover, definition, references,
documentHighlight, documentLink, document/workspace symbols, folding,
semanticTokens/full, inlayHint, completion, inlineCompletion (3.18),
signatureHelp, codeAction + executeCommand, rename + prepare,
callHierarchy, formatting + rangeFormatting, push diagnostics, dynamic
file-watcher registration, configuration push. Below is everything
major that's missing, ordered by priority. The `resolve` endpoints
(completionItem, codeAction, inlayHint, documentLink, workspaceSymbol)
are **deliberately** unadvertised — every item is returned complete —
and are not gaps.
### 9a. Compliance and high-value (round 1)
- [x] **`executeCommand` must deliver its edit via `workspace/applyEdit`.**
Today `ports::execute`'s `WorkspaceEdit` is returned as the request's
*result* (`server.rs`, `ports.rs:79`), which the spec does not define
and standard clients drop on the floor — `vscode-languageclient` does
not apply executeCommand results and `editors/vscode/extension.js`
has no custom handler, so `lucisv.addPort`/`removePort`/`propagate`
invoked as *commands* currently do nothing in every stock client (the
code-action path is unaffected: those carry the edit inline). Fix:
push a `workspace/applyEdit` request, return `null` as the command
result, and read the `ApplyWorkspaceEditResponse` (the one client
response we can no longer ignore wholesale). Gate on the client's
`workspace.applyEdit` capability with the old return-the-edit
behavior as the documented fallback.
→ `docs/features/apply-edit/README.md`; the edit is pushed with a
`lucisv: <command>` label, the result is `null`, and a refusal is shown
as an ERROR naming the command. Watcher-registration answers stay
ignored; `editors/vscode/extension.js` needed no change.
- [x] **Pull diagnostics (3.17): `textDocument/diagnostic` +
`workspace/diagnostic`.** The modern model — client controls timing,
prioritizes visible editors, caches via `resultId`/`unchanged`.
Advertise `DiagnosticOptions` (`inter_file_dependencies: true` — a
save can change other files' diagnostics through the index;
`workspace_diagnostics`), compute from the same parse+lint pass that
feeds `publish`, answer `Unchanged` when the buffer version and index
generation both stand. Keep push for clients that don't send
`text_document.diagnostic` capability; never run both models for the
same client (double diagnostics).
→ `docs/features/pull-diagnostics/README.md`; one generation counter is
the whole `resultId` (bumped by `set_document` and `reindex`), the
push gate sits in `send_diagnostics` so the `didClose` clear is
suppressed too, and `workspace/diagnostic` reports the open buffers —
the honest limit, stated there.
- [x] **`textDocument/selectionRange`** — expand-selection. Cheap for
us: the scope-pair matcher (`pairs.rs`) and AST spans already give
the nesting chain; walk offset → enclosing token → statement → item →
scope → file, one linked chain per input position.
→ `docs/features/selection-range/README.md`
(`crates/lucisv_server/src/selection.rs`); token, AST, scope-pair and
file ranges are collected and filtered down to what strictly nests. No
expression step — deliberate, and recorded there.
### 9b. High-value, next rounds
- [x] **Incremental text sync** (`TextDocumentSyncKind::INCREMENTAL`).
Full-buffer sync on every keystroke scales poorly; apply
range-scoped `contentChanges` in order, with a full-text fallback on
any malformed change. Touches `set_document` and the staleness model
in `docs/features/lucisv-server/README.md`.
→ `docs/features/incremental-sync/README.md`
(`crates/lucisv_server/src/sync.rs`); one pure
`apply_changes(text, changes) -> String` over `convert::Positions`, a
fresh line table per change so each range sees the previous one's
result, rangeless changes still replacing the whole buffer, and every
desynced position clamped (line past EOF, character past line end,
surrogate half rounds forward, `start > end` becomes an insertion).
Still one `set_document` — one reparse, one generation bump, one
publish — per notification. Advertised as `TextDocumentSyncOptions`
with the open/close and `save.includeText: false` values a bare `Kind`
already implied, so no client's save behavior moved.
- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native
format-on-save hook (client-side `editor.formatOnSave` already works;
this serves the editors without it).
→ `docs/features/will-save-wait-until/README.md`; advertised as
`willSaveWaitUntil: true` (the plain `willSave` notification stays
unadvertised — there is nothing for us in it), and gated on a new
`lucisv.formatOnSave` setting that is **off** by default, so a client
with its own format-on-save never formats twice. On, it is
`textDocument/formatting` with a different trigger: same engine, same
all-or-nothing edit, same `[]` for an already-formatted buffer, and the
settings ladder minus its `tabSize` rung because the request carries no
`FormattingOptions`. Every save reason formats; an unopened buffer and
the off state both answer `null`.
- [x] **Semantic tokens `range` + `full/delta`** — we set
`range: None` and no delta, so clients re-request whole-file token
sets on every edit. Delta needs `resultId` bookkeeping per buffer.
→ `docs/features/semantic-tokens-delta/README.md`; `tokens.rs` split
into classification → absolute form → filter → one pure encoder, so
all three requests share a tokenizer. `range: Some(true)` answers the
overlapping tokens whole, **re-encoded from the start of the
document** (a range answer is self-contained, not a slice), carries
no `resultId` and is not what a later delta diffs against; an empty
range answers nothing. `full: Delta { delta: true }` answers one
`SemanticTokensEdit` replacing everything between the common prefix
and the common suffix — **the suffix capped to what the prefix left**,
because identical lines of Verilog encode identically and an uncapped
suffix claims the same tokens twice. `resultId`s are minted per
answer, stored by `full` and `full/delta` alike, dropped on
`didClose`; an id the server does not hold is answered in full. No
token request bumps the diagnostics generation. Not done:
`workspace/semanticTokens/refresh`.
- [x] **Work-done progress** — `reindex()` is a synchronous full
rescan on every save with no `window/workDoneProgress` reporting;
on a big filelist the server just goes quiet.
→ `docs/features/work-done-progress/README.md`; every workspace
rescan — the startup build, a save, a watched file, a changed
`lucisv.exclude`/`filelist` — is wrapped in one
`window/workDoneProgress/create` plus a `$/progress` begin/end pair
on a fresh `lucisv-index-N` token, gated on the client's
`window.workDoneProgress` (a client that did not ask is sent nothing
at all, as the spec requires). `begin` goes out without waiting for
the create's answer, because the rescan blocks the loop the moment
it returns; the create's answer is ignored on the same path the
watcher registrations' is. No percentage and no intermediate report
— the rescan is one opaque call — and the `end` names the indexed
file count, read off the index's own file list. The bar covers the
scan, ending before the scope warnings and the republishes.
- [x] **`$/cancelRequest`** — the loop handles requests sequentially
and ignores cancellation; at minimum answer already-cancelled queued
requests with `RequestCancelled`.
→ `docs/features/cancel-request/README.md`; **completes §9b.** `run()`
now reads in bursts — one blocking receive, then everything already
queued behind it — and handles the burst **in arrival order**, so a
`didChange` ahead of a request is still applied before that request is
answered. A request the same burst also carries a cancel for is
answered `RequestCancelled` (-32800) without being dispatched; the
cancels themselves are consumed there and never reach
`notification()`. A cancel naming no request in its burst is dropped
on the spot — it refers to a request already answered, or to one that
never arrived — so the feature holds no state between bursts, and a
double cancel is harmless. `shutdown` is honoured before the cancelled
set is consulted and so is never cancellable. Numeric and string ids
both read; malformed cancels dropped. The design's one correction:
`lsp-server` 0.10 wires its stdio transport with `bounded(0)`
*rendezvous* channels, so a backlog never sits on
`connection.receiver` at all — the loop forwards messages onto an
unbounded `std::sync::mpsc` queue of its own on one small thread
(std-only, no new dependency), which stops at `shutdown` so
`handle_shutdown` still reads the `exit` that follows. Nothing already
running is cancelled; that needs the worker pool §6 defers.
### 9c. Moderate value, Verilog-shaped
- [ ] **Goto type definition** — from a net/variable use to its
typedef/struct/enum/interface declaration; real value once
`vlog_semantic` tracks declared types of bindings.
- [ ] **Linked editing range** — edit `module m` and its
`endmodule : m` label together (`end : label`, `endfunction : name`,
etc.). A genuinely good fit for SV's closing labels.
- [ ] **Code lens** — "N instantiations" above each module header from
the hierarchy index; `codeLens/resolve` unnecessary (counts are
cheap), `workspace/codeLens/refresh` on reindex.
- [ ] **On-type formatting** — conspicuous absence for a
formatter-first server; candidate trigger: newline (indent the new
line per block nesting), `;` (reformat the finished statement).
- [ ] **Type hierarchy (3.17)** — arguably the semantically correct
home for the module hierarchy (and later interface/class extends
chains); keep callHierarchy as the compatibility surface.
- [ ] **File operations** — `workspace/willRenameFiles`: renaming a
`.sv/.svh` rewrites `` `include`` lines that reference it (the
include graph exists); `didRename/didDelete` as cheaper index nudges
than the watcher round-trip.
- [ ] **`workspace/didChangeWorkspaceFolders`** — roots are read once
at initialize; adding/removing a folder mid-session is ignored.
- [ ] **`workspace/configuration` (server-pull)** — we rely solely on
push `didChangeConfiguration`; clients are moving to the pull model.
- [ ] **3.18 additions:** `textDocument/rangesFormatting` (multi-range,
feeds format-modified-lines), snippet edits in `WorkspaceEdit`
(would improve `addPort` cursor placement), and
`workspace/textDocumentContent` (could serve a read-only "expanded
macro" document).
### 9d. Deliberately skipped (no Verilog use case)
Notebook sync, moniker (LSIF), inline value (debugger), document
color, goto implementation, goto declaration (Verilog has no
declaration/definition split lucisv models). Recorded here so the
audit doesn't repeat.
+39
View File
@@ -60,6 +60,20 @@ pub fn settings_for(
Settings { config: config_from(&file, client, options), problem }
}
/// Resolve the settings governing a buffer for a request that carries no
/// `FormattingOptions`.
///
/// `textDocument/willSaveWaitUntil` has no options field at all — the protocol
/// simply does not carry one there. So the ladder `settings_for` documents
/// runs with rung 3 missing, which is the same thing `indent_width` does for a
/// lint fix: `lucisv.toml` > the pushed `lucisv.*` settings > the built-in
/// default. Spelled as hard tabs and a zero width because `config_from` takes
/// neither, so nothing is guessed on the user's behalf.
pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) -> Settings {
let none = FormattingOptions { tab_size: 0, insert_spaces: false, ..Default::default() };
settings_for(doc, client, &none)
}
/// Format a buffer.
///
/// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an
@@ -495,6 +509,31 @@ mod tests {
assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default");
}
#[test]
fn a_request_without_options_climbs_the_same_ladder_without_rung_3() {
// What `willSaveWaitUntil` resolves to: the protocol sends no
// `FormattingOptions` with it, so the editor's tab size is simply not
// one of the inputs.
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let settings = settings_without_editor_options(doc, &pushed(None, Some(8)));
assert_eq!(settings.config.indent_width, 4, "the config still wins");
assert_eq!(settings.problem, None);
// With no config, the pushed setting is the highest rung there is.
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8)));
assert_eq!(settings.config.indent_width, 8);
assert_eq!(settings.config.max_width, 60);
// And with nothing pushed either, the built-in default — never a
// guess from an option that was not sent.
let settings = settings_without_editor_options(doc, &none());
assert_eq!(settings.config.indent_width, Config::default().indent_width);
assert_eq!(settings.config.max_width, Config::default().max_width);
}
#[test]
fn a_broken_config_leaves_the_pushed_settings_in_charge() {
// Nothing from a broken `lucisv.toml` is used, so the next rung down is
+197 -8
View File
@@ -26,11 +26,13 @@ mod nav;
mod pairs;
mod ports;
mod rename;
mod selection;
mod server;
mod settings;
mod signature;
mod state;
mod symbols;
mod sync;
mod templates;
mod tokens;
mod uri;
@@ -42,11 +44,13 @@ use std::path::PathBuf;
use lsp_server::Connection;
use lsp_types::{
CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability,
CompletionOptions, DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability,
InitializeParams, InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind,
RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions,
CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities, DocumentLinkOptions,
ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, SaveOptions,
SelectionRangeProviderCapability, SemanticTokensFullOptions, SemanticTokensLegend,
SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities,
SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, WorkDoneProgressOptions,
};
use crate::server::{ClientAbilities, Server};
@@ -63,6 +67,9 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
let abilities = ClientAbilities {
snippets: snippet_support(&params),
file_watching: watch::dynamic_registration(&params),
apply_edit: apply_edit_support(&params),
pull_diagnostics: pull_diagnostics_support(&params),
work_done_progress: work_done_progress_support(&params),
};
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
@@ -79,7 +86,28 @@ fn capabilities() -> ServerCapabilities {
// The protocol default, and what the conversion in `convert.rs`
// implements. Stated rather than left implicit.
position_encoding: Some(PositionEncodingKind::UTF16),
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
// Incremental sync: a keystroke costs one range, not the whole file.
// Spelled out as options rather than a bare kind because a bare kind
// says nothing about open/close or save, and clients fill that in
// themselves — this states the same defaults a bare kind resolved to,
// so nothing but `change` moves. `includeText: false` keeps a save
// from re-sending a buffer the server already tracks edit by edit;
// the `didSave` handler still honours text if a client sends it.
text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
open_close: Some(true),
change: Some(TextDocumentSyncKind::INCREMENTAL),
// The plain `willSave` notification carries nothing this server
// can act on, so it is left unadvertised; `willSaveWaitUntil` is
// the format-on-save hook, for the editors that have no
// format-on-save of their own. It answers `null` unless
// `lucisv.formatOnSave` is on — see
// `docs/features/will-save-wait-until/README.md`.
will_save: None,
will_save_wait_until: Some(true),
save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
include_text: Some(false),
})),
})),
document_formatting_provider: Some(OneOf::Left(true)),
document_range_formatting_provider: Some(OneOf::Left(true)),
definition_provider: Some(OneOf::Left(true)),
@@ -172,6 +200,21 @@ fn capabilities() -> ServerCapabilities {
// sends the request after opting into `ProposedFeatures`, so an
// extension older than this server simply never asks.
inline_completion_provider: Some(OneOf::Left(true)),
// Expand-selection. Nothing to configure: the chain is computed from
// the buffer alone, and every position is answered.
selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
// Pull diagnostics (3.17), served from the same parse+lint pass the
// push model publishes. `inter_file_dependencies` because a save
// rebuilds the workspace index and *that* changes what other files
// report; `workspace_diagnostics` because `workspace/diagnostic` is
// answered — over the open buffers, which is the only scope this
// server has ever diagnosed.
diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
identifier: Some(diagnostics::SOURCE.to_string()),
inter_file_dependencies: true,
workspace_diagnostics: true,
work_done_progress_options: WorkDoneProgressOptions::default(),
})),
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
SemanticTokensOptions {
work_done_progress_options: WorkDoneProgressOptions::default(),
@@ -179,8 +222,16 @@ fn capabilities() -> ServerCapabilities {
token_types: tokens::token_types(),
token_modifiers: tokens::token_modifiers(),
},
range: None,
full: Some(SemanticTokensFullOptions::Bool(true)),
// The visible lines, for the first paint of a large file:
// the same tokenizer, filtered, and re-encoded from the
// start of the document so the answer stands on its own.
range: Some(true),
// `delta: true` rather than a bare `full: true`, so a client
// that has an answer already asks what changed instead of
// re-fetching the file's whole token set on every keystroke.
// `full` itself stays served — the enum's `Delta` variant is
// the full capability plus deltas, not a replacement.
full: Some(SemanticTokensFullOptions::Delta { delta: Some(true) }),
},
)),
..Default::default()
@@ -216,6 +267,48 @@ fn snippet_support(params: &InitializeParams) -> bool {
.unwrap_or(false)
}
/// Whether the client applies a `workspace/applyEdit` request.
///
/// A client that did not say so gets a command's edit back as the request
/// result — which is what every client got before this was read, and is the
/// only thing left to try for one that cannot be pushed an edit.
fn apply_edit_support(params: &InitializeParams) -> bool {
params
.capabilities
.workspace
.as_ref()
.and_then(|workspace| workspace.apply_edit)
.unwrap_or(false)
}
/// Whether the client pulls diagnostics (LSP 3.17).
///
/// Sending the capability at all is what says so; its two fields are about
/// dynamic registration and related documents, neither of which this server
/// uses. A client that says nothing keeps the push model unchanged.
fn pull_diagnostics_support(params: &InitializeParams) -> bool {
params
.capabilities
.text_document
.as_ref()
.is_some_and(|text_document| text_document.diagnostic.is_some())
}
/// Whether the client renders server-initiated work-done progress.
///
/// The spec forbids a server from creating progress at all without this, so a
/// client that said nothing is sent no `window/workDoneProgress/create` and no
/// `$/progress` — the workspace rescan is silent for it, exactly as it was
/// before this was read.
fn work_done_progress_support(params: &InitializeParams) -> bool {
params
.capabilities
.window
.as_ref()
.and_then(|window| window.work_done_progress)
.unwrap_or(false)
}
/// The directories to index: the client's workspace folders, or the
/// deprecated single root when that is all it sent.
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
@@ -255,6 +348,102 @@ mod tests {
assert!(caps.inlay_hint_provider.is_some());
assert!(caps.call_hierarchy_provider.is_some());
assert!(caps.inline_completion_provider.is_some());
assert!(caps.selection_range_provider.is_some());
assert!(caps.diagnostic_provider.is_some());
}
#[test]
fn the_semantic_token_capability_asks_for_ranges_and_for_deltas() {
// A client keys entirely off this: it sends `full/delta` only where
// `full.delta` is `true`, and `range` only where `range` is.
let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(options)) =
capabilities().semantic_tokens_provider
else {
panic!("the options form, not a registration");
};
assert_eq!(options.range, Some(true));
assert_eq!(options.full, Some(SemanticTokensFullOptions::Delta { delta: Some(true) }));
assert_eq!(options.legend.token_types.len(), 14, "the legend is unchanged");
}
#[test]
fn the_sync_options_ask_for_the_save_hook_and_not_the_notification() {
let Some(TextDocumentSyncCapability::Options(options)) = capabilities().text_document_sync
else {
panic!("the options form, not a bare kind");
};
assert_eq!(options.change, Some(TextDocumentSyncKind::INCREMENTAL));
assert_eq!(options.will_save_wait_until, Some(true), "the format-on-save hook is answered");
assert_eq!(options.will_save, None, "the plain notification has nothing for us");
}
#[test]
fn the_diagnostic_options_say_what_this_server_actually_does() {
let Some(DiagnosticServerCapabilities::Options(options)) =
capabilities().diagnostic_provider
else {
panic!("plain options, not a dynamic registration");
};
assert_eq!(options.identifier.as_deref(), Some(diagnostics::SOURCE), "same tag as a push");
assert!(options.inter_file_dependencies, "a save changes other files' diagnostics");
assert!(options.workspace_diagnostics, "`workspace/diagnostic` is answered");
}
#[test]
fn apply_edit_support_is_read_from_the_clients_own_capabilities() {
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
assert!(!apply_edit_support(&InitializeParams::default()), "silence means no");
let saying = |apply_edit: Option<bool>| InitializeParams {
capabilities: ClientCapabilities {
workspace: Some(WorkspaceClientCapabilities { apply_edit, ..Default::default() }),
..Default::default()
},
..Default::default()
};
assert!(apply_edit_support(&saying(Some(true))));
assert!(!apply_edit_support(&saying(Some(false))));
assert!(!apply_edit_support(&saying(None)));
}
#[test]
fn work_done_progress_support_is_read_from_the_clients_own_capabilities() {
use lsp_types::{ClientCapabilities, WindowClientCapabilities};
assert!(!work_done_progress_support(&InitializeParams::default()), "silence means no");
let saying = |work_done_progress: Option<bool>| InitializeParams {
capabilities: ClientCapabilities {
window: Some(WindowClientCapabilities { work_done_progress, ..Default::default() }),
..Default::default()
},
..Default::default()
};
assert!(work_done_progress_support(&saying(Some(true))));
assert!(!work_done_progress_support(&saying(Some(false))));
assert!(!work_done_progress_support(&saying(None)));
}
#[test]
fn a_client_that_sent_the_diagnostic_capability_at_all_is_a_pulling_client() {
use lsp_types::{
ClientCapabilities, DiagnosticClientCapabilities, TextDocumentClientCapabilities,
};
assert!(!pull_diagnostics_support(&InitializeParams::default()), "silence means push");
let pulling = InitializeParams {
capabilities: ClientCapabilities {
text_document: Some(TextDocumentClientCapabilities {
// Both fields left unset: sending the capability is the
// whole of the statement, and neither field is about
// whether the client pulls.
diagnostic: Some(DiagnosticClientCapabilities::default()),
..Default::default()
}),
..Default::default()
},
..Default::default()
};
assert!(pull_diagnostics_support(&pulling));
}
#[test]
+4 -3
View File
@@ -75,9 +75,10 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
/// Run one of the three commands, or say why it cannot run.
///
/// The answer is the `WorkspaceEdit` the client is expected to apply (through
/// `workspace/applyEdit`, which the server does not push: an editor that asked
/// for the command owns the edit) plus the engine's warnings.
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
/// it reaches the editor is `server.rs`'s business: it is pushed as a
/// `workspace/applyEdit` request, or — for a client that cannot be pushed one
/// — returned as the command's result (`docs/features/apply-edit/README.md`).
pub fn execute(
ws: &Workspace,
command: &str,
+546
View File
@@ -0,0 +1,546 @@
//! `textDocument/selectionRange` — expand-selection.
//!
//! No new analysis: everything the chain is built from is already computed for
//! something else. The token stream gives the innermost step, the tolerant
//! parse's item and statement spans give the middle ones, and `pairs::analyze`
//! — the rainbow's own matcher — gives the scopes a broken parse would
//! otherwise lose. The four sources are thrown into one list of byte ranges
//! that cover the cursor, and the chain is whatever nests. See
//! `docs/features/selection-range/README.md`.
use lsp_types::{Position, SelectionRange};
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind};
use vlog_parser::TextRange;
use crate::pairs::analyze;
use crate::state::Document;
/// One chain per requested position, in the order they were asked for.
///
/// Each chain runs innermost first, every step strictly containing the one
/// before it and the last one being the whole file. A position that resolves
/// to nothing else — an empty buffer, a file that does not lex — still gets
/// that last step, because the protocol wants exactly one answer per position.
pub fn selection_ranges(doc: &Document, positions: &[Position]) -> Vec<SelectionRange> {
let converter = doc.positions();
positions.iter().map(|position| chain(doc, converter.offset(*position))).collect()
}
/// The chain for one byte offset.
fn chain(doc: &Document, offset: u32) -> SelectionRange {
let positions = doc.positions();
let mut range: Option<SelectionRange> = None;
// Widest first, so each step is built already holding its parent.
for span in nested(enclosing(doc, offset)).into_iter().rev() {
range = Some(SelectionRange { range: positions.range(span), parent: range.map(Box::new) });
}
range.unwrap_or_else(|| SelectionRange { range: positions.whole_document(), parent: None })
}
/// Every byte range this server can name that covers `offset`, from every
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
let mut spans = Vec::new();
if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) {
spans.push(token.span);
}
items(&doc.tree.items, offset, &mut spans);
// The scopes the AST does not model — an unclosed `begin` inside an
// otherwise fine module, a `case` in a file that only half parsed — still
// match over the token stream, and a user expanding a selection there is
// exactly the user whose file is mid-edit.
for pair in analyze(&doc.tokens).pairs {
let span = TextRange::new(pair.open.start, pair.close.end);
if covers(span, offset) {
spans.push(span);
}
}
spans.push(TextRange::new(0, doc.text.len() as u32));
spans
}
/// The subsequence that really nests, smallest first.
///
/// Two ranges that both cover the cursor need not contain one another — an
/// item span and a scope pair can overlap when a parse went wrong — and LSP
/// requires every step to contain its child. So the list is walked smallest
/// first and a range is kept only when it strictly contains what was kept
/// before it; that also drops the duplicates the four sources produce for the
/// same construct.
fn nested(mut spans: Vec<TextRange>) -> Vec<TextRange> {
// A zero-width step selects nothing, which is not a step a user can see.
spans.retain(|span| !span.is_empty());
spans.sort_by_key(|span| (span.len(), span.start));
let mut out: Vec<TextRange> = Vec::new();
for span in spans {
let keep = match out.last() {
Some(inner) => {
span.start <= inner.start && span.end >= inner.end && span.len() > inner.len()
}
None => true,
};
if keep {
out.push(span);
}
}
out
}
/// Whether a span covers an offset. The end is **included**: a cursor sitting
/// just after a word is still on that word, which is where an expand-selection
/// keystroke is most often pressed.
fn covers(span: TextRange, offset: u32) -> bool {
span.start <= offset && offset <= span.end
}
/// The spans of every item that covers `offset`, descending only into the one
/// that does — the walk is per-keystroke, and a whole-file walk would visit
/// thousands of nodes to report a handful.
fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
for item in list {
if !covers(item.span, offset) {
continue;
}
out.push(item.span);
match &item.kind {
ItemKind::Module(module) => items(&module.items, offset, out),
ItemKind::Class(class) => items(&class.items, offset, out),
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
if covers(case_item.span, offset) {
out.push(case_item.span);
gen_block(&case_item.body, offset, out);
}
}
}
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
statement(stmt, offset, out)
}
ItemKind::Function(decl) => statements(&decl.stmts, offset, out),
ItemKind::Task(decl) => statements(&decl.stmts, offset, out),
_ => {}
}
}
}
/// A generate `if`, its `else if` ladder and its final `else`.
fn gen_if_blocks(gen_if: &GenIf, offset: u32, out: &mut Vec<TextRange>) {
gen_block(&gen_if.then, offset, out);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
gen_block(&nested.then, offset, out);
els = nested.els.as_deref();
}
GenElse::Block(block) => {
gen_block(block, offset, out);
els = None;
}
}
}
}
fn gen_block(block: &GenBlock, offset: u32, out: &mut Vec<TextRange>) {
if !covers(block.span, offset) {
return;
}
out.push(block.span);
items(&block.items, offset, out);
}
fn statements(list: &[Stmt], offset: u32, out: &mut Vec<TextRange>) {
for stmt in list {
statement(stmt, offset, out);
}
}
/// The spans of `stmt` and of every statement inside it that covers `offset`.
///
/// The recursion is bounded by the parser's own nesting limit
/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it
/// built.
fn statement(stmt: &Stmt, offset: u32, out: &mut Vec<TextRange>) {
if !covers(stmt.span, offset) {
return;
}
out.push(stmt.span);
match &stmt.kind {
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
statements(stmts, offset, out)
}
StmtKind::If { then, els, .. } => {
statement(then, offset, out);
if let Some(els) = els {
statement(els, offset, out);
}
}
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for case_item in items {
if covers(case_item.span, offset) {
out.push(case_item.span);
statement(&case_item.stmt, offset, out);
}
}
}
StmtKind::Labeled { stmt: inner, .. } => statement(inner, offset, out),
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. } => statement(body, offset, out),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
statement(inner, offset, out)
}
StmtKind::Assert { then, els, .. } => {
if let Some(then) = then {
statement(then, offset, out);
}
if let Some(els) = els {
statement(els, offset, out);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::Range;
use vlog_semantic::WorkspaceIndex;
fn doc_of(text: &str) -> Document {
Document::new(None, text.to_string(), &WorkspaceIndex::default())
}
/// The chain for the first occurrence of `needle`, as the source text of
/// each step, innermost first.
fn steps(text: &str, needle: &str) -> Vec<String> {
let doc = doc_of(text);
let offset = text.find(needle).expect("the needle is in the text") as u32;
let position = doc.positions().position(offset);
let chains = selection_ranges(&doc, &[position]);
assert_eq!(chains.len(), 1, "one chain per position");
let mut out = Vec::new();
let mut step = Some(&chains[0]);
let positions = doc.positions();
while let Some(current) = step {
let start = positions.offset(current.range.start) as usize;
let end = positions.offset(current.range.end) as usize;
out.push(text[start..end].to_string());
step = current.parent.as_deref();
}
out
}
/// Every step of a chain, as `(start, end)` byte offsets.
fn spans(doc: &Document, offset: u32) -> Vec<(u32, u32)> {
let position = doc.positions().position(offset);
let chains = selection_ranges(doc, &[position]);
let positions = doc.positions();
let mut out = Vec::new();
let mut step = chains.first();
while let Some(current) = step {
out.push((positions.offset(current.range.start), positions.offset(current.range.end)));
step = current.parent.as_deref();
}
out
}
#[test]
fn the_chain_runs_from_the_token_out_to_the_whole_file() {
let text = "module m;\n wire a;\nendmodule\n";
let steps = steps(text, "wire");
assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}");
assert_eq!(steps.last().map(String::as_str), Some(text), "the whole file closes it");
assert!(steps.contains(&"wire a;".to_string()), "{steps:?}");
}
#[test]
fn a_statement_expands_through_its_block_and_its_process() {
let text = concat!(
"module m;\n",
" initial begin\n",
" if (a) begin\n",
" x = 1;\n",
" end\n",
" end\n",
"endmodule\n",
);
let steps = steps(text, "x = 1");
assert_eq!(steps.first().map(String::as_str), Some("x"));
assert!(steps.iter().any(|s| s == "x = 1;"), "the statement: {steps:?}");
assert!(steps.iter().any(|s| s.starts_with("if (a) begin")), "the if: {steps:?}");
assert!(steps.iter().any(|s| s.starts_with("initial begin")), "the process: {steps:?}");
assert!(steps.iter().any(|s| s.starts_with("module m;")), "the module: {steps:?}");
assert_eq!(steps.last().map(String::as_str), Some(text));
}
#[test]
fn every_step_strictly_contains_the_one_before_it() {
// The protocol's own requirement, and the thing the four sources of
// ranges could most easily break.
let text = concat!(
"module m;\n",
" always_comb begin\n",
" case (sel)\n",
" 2'd0: y = a;\n",
" default: y = b;\n",
" endcase\n",
" end\n",
"endmodule\n",
);
let doc = doc_of(text);
for offset in 0..=text.len() as u32 {
let spans = spans(&doc, offset);
assert!(!spans.is_empty(), "every position gets a chain, at {offset}");
for pair in spans.windows(2) {
let (inner, outer) = (pair[0], pair[1]);
assert!(
outer.0 <= inner.0 && outer.1 >= inner.1 && outer != inner,
"at {offset}: {outer:?} must strictly contain {inner:?} — {spans:?}"
);
}
assert_eq!(
spans.last(),
Some(&(0, text.len() as u32)),
"the file closes every chain, at {offset}"
);
}
}
#[test]
fn a_case_item_is_a_step_of_its_own() {
let text = concat!(
"module m;\n",
" always_comb begin\n",
" case (sel)\n",
" 2'd0: y = a;\n",
" endcase\n",
" end\n",
"endmodule\n",
);
let steps = steps(text, "y = a");
assert!(steps.iter().any(|s| s == "2'd0: y = a;"), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("case (sel)")), "{steps:?}");
}
#[test]
fn a_generate_block_is_a_step_of_its_own() {
let text = concat!(
"module m;\n",
" generate\n",
" if (A) begin : g\n",
" wire a;\n",
" end\n",
" endgenerate\n",
"endmodule\n",
);
let steps = steps(text, "wire a");
assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("begin : g")), "the block: {steps:?}");
assert!(steps.iter().any(|s| s.starts_with("generate")), "the region: {steps:?}");
}
#[test]
fn several_positions_are_answered_position_for_position() {
let text = "module m;\n wire a;\nendmodule\n";
let doc = doc_of(text);
let positions = doc.positions();
let at = |needle: &str| positions.position(text.find(needle).expect("needle") as u32);
let asked = vec![at("endmodule"), at("wire"), at("module")];
let chains = selection_ranges(&doc, &asked);
assert_eq!(chains.len(), 3);
for (chain, position) in chains.iter().zip(&asked) {
assert!(
chain.range.start <= *position && *position <= chain.range.end,
"each answer is about its own position: {chain:?} vs {position:?}"
);
}
}
#[test]
fn no_positions_asked_means_no_chains_answered() {
let doc = doc_of("module m;\nendmodule\n");
assert!(selection_ranges(&doc, &[]).is_empty());
}
#[test]
fn an_empty_file_still_answers_one_degenerate_chain() {
let doc = doc_of("");
let chains = selection_ranges(&doc, &[Position { line: 0, character: 0 }]);
assert_eq!(chains.len(), 1);
assert_eq!(chains[0].range.start, chains[0].range.end, "there is nothing to select");
assert!(chains[0].parent.is_none(), "and nothing to expand to");
}
#[test]
fn a_file_that_does_not_lex_still_answers_the_file_range() {
// `Document::new` leaves `tokens` empty and the tree an error leaf, so
// this is the path where every source but the last one gives nothing.
let text = "module m;\n wire a; /* unterminated\n";
let doc = doc_of(text);
assert!(doc.tokens.is_empty(), "the premise");
let spans = spans(&doc, 12);
assert_eq!(spans.last(), Some(&(0, text.len() as u32)));
}
#[test]
fn an_unclosed_scope_still_expands_through_what_did_close() {
// The mid-edit shape: the `begin` never closes, so the AST cannot
// offer the statement — the module's own pair still can.
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
let doc = doc_of(text);
let offset = text.find("x = 1").expect("needle") as u32;
let spans = spans(&doc, offset);
assert!(spans.len() >= 2, "at least the token and the file: {spans:?}");
assert_eq!(spans.last(), Some(&(0, text.len() as u32)));
}
#[test]
fn a_position_past_the_end_of_the_file_clamps_into_it() {
let text = "module m;\nendmodule\n";
let doc = doc_of(text);
let chains = selection_ranges(&doc, &[Position { line: 99, character: 99 }]);
assert_eq!(chains.len(), 1);
assert_eq!(chains[0].range.end, doc.positions().whole_document().end);
}
#[test]
fn a_multibyte_line_keeps_the_columns_in_utf16() {
// The chain is computed in bytes and answered in UTF-16 units; an
// off-by-one here would select the wrong text in the editor only.
let text = "module m;\n // é 🎉\n wire a;\nendmodule\n";
let steps = steps(text, "wire");
assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}");
assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}");
}
#[test]
fn nesting_drops_a_range_that_does_not_contain_what_came_before() {
// The guard for the overlapping-sources case: two ranges that both
// cover the cursor but nest in neither direction. The wider-but-not-
// enclosing one must be dropped, never emitted as a parent.
let spans = vec![
TextRange::new(4, 6),
TextRange::new(0, 8),
TextRange::new(5, 20), // covers 5, contains neither of the above
TextRange::new(0, 30),
];
let kept = nested(spans);
assert_eq!(
kept.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(),
vec![(4, 6), (0, 8), (0, 30)]
);
}
/// The strict-nesting invariant, on the real corpus rather than
/// hand-written snippets. `every_step_strictly_contains_the_one_before_it`
/// above proves the invariant on files this crate's author wrote to
/// exercise it; a corpus file was written by nobody thinking about this
/// walk at all, and is exactly what turns up a construct the four
/// sources disagree about. Skipped when `corpus/` is not checked out,
/// like every other corpus test in this crate.
#[test]
fn every_step_strictly_nests_over_the_real_corpus() {
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let extensions = ["sv", "v", "svh", "vh"];
let mut files_checked = 0;
let mut positions_checked = 0;
for entry in walk(&corpus) {
let Some(ext) = entry.extension().and_then(|e| e.to_str()) else { continue };
if !extensions.contains(&ext) {
continue;
}
let Ok(text) = std::fs::read_to_string(&entry) else { continue };
if text.is_empty() {
continue;
}
files_checked += 1;
let doc = Document::new(Some(entry.clone()), text.clone(), &WorkspaceIndex::default());
let converter = doc.positions();
// A handful of evenly spaced offsets per file, not every byte:
// the corpus is 800+ files, and the per-offset invariant is
// already proven exhaustively on small files above. This is
// about *coverage of real syntax*, not exhaustiveness per file.
let len = text.len() as u32;
let stride = (len / 7).max(1);
let mut offset = 0;
while offset <= len {
positions_checked += 1;
let position = converter.position(offset);
let chains = selection_ranges(&doc, &[position]);
assert_eq!(chains.len(), 1, "{}: offset {offset}", entry.display());
let mut step = Some(&chains[0]);
let mut previous: Option<Range> = None;
while let Some(current) = step {
if let Some(inner) = previous {
let widens = current.range.start <= inner.start
&& current.range.end >= inner.end
&& current.range != inner;
assert!(
widens,
"{}: offset {offset}: {:?} does not strictly contain {:?}",
entry.display(),
current.range,
inner
);
}
previous = Some(current.range);
step = current.parent.as_deref();
}
let whole = converter.whole_document();
assert_eq!(
previous,
Some(whole),
"{}: offset {offset}: the file must close every chain",
entry.display()
);
offset += stride;
}
}
assert!(files_checked > 100, "the corpus really is checked out: {files_checked} files");
eprintln!("selection ranges: {files_checked} files, {positions_checked} positions, no panics, every step strictly nested");
}
/// Every regular file under `dir`, recursively — no filtering by anything
/// but extension, which the caller does. Errors reading a directory are
/// treated as "nothing here" rather than failing the whole sweep: a
/// symlink loop or a permission-denied subtree in a third-party corpus
/// checkout should not take the QA test down with it.
fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
let Ok(entries) = std::fs::read_dir(dir) else { return out };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
out.extend(walk(&path));
} else {
out.push(path);
}
}
out
}
#[test]
fn nesting_drops_duplicates_and_empty_ranges() {
let spans = vec![
TextRange::new(3, 3),
TextRange::new(2, 9),
TextRange::new(2, 9),
TextRange::new(0, 9),
];
let kept = nested(spans);
assert_eq!(kept.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(), vec![(2, 9), (0, 9)]);
}
}
File diff suppressed because it is too large. Load diff
+27 -1
View File
@@ -46,6 +46,13 @@ pub struct ClientSettings {
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
pub inline_templates: Option<bool>,
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
/// the buffer. A plain `bool` rather than an `Option`, because unset and
/// off are the same answer here: an editor with a format-on-save of its
/// own already runs `textDocument/formatting` on save, and a server that
/// also formatted would format twice. See
/// `docs/features/will-save-wait-until/README.md`.
pub format_on_save: bool,
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
@@ -70,6 +77,10 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
exclude: strings(lucisv.get("exclude")),
filelist: path(lucisv.get("filelist")),
inline_templates: flag(lucisv.get("inlineTemplates")),
// Anything that is not `true` leaves the hook declining, wrong-typed
// values included: the safe direction for a setting that rewrites the
// user's buffer on every save is the one that does nothing.
format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false),
}
}
@@ -132,7 +143,8 @@ mod tests {
"indent": indent,
"exclude": exclude,
"filelist": "",
"inlineTemplates": true
"inlineTemplates": true,
"formatOnSave": false
}
})
}
@@ -189,6 +201,20 @@ mod tests {
}
}
#[test]
fn format_on_save_is_off_until_a_client_asks_for_it() {
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save);
// Absence is off: the hook runs on every save of every buffer, and a
// server that formatted uninvited would fight the editor's own
// format-on-save.
assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence");
for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] {
let found = settings(json!({ "lucisv": { "formatOnSave": bad } }));
assert!(!found.format_on_save, "formatOnSave {bad} must be ignored");
}
}
#[test]
fn a_populated_payload_is_read_whole() {
let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"])));
+10
View File
@@ -572,6 +572,16 @@ mod tests {
}),
"widths do not move files"
);
// QA (2026-08-26): `format_on_save` is read afresh by
// `will_save_wait_until` exactly as `indent`/`lineLength` are by
// `formatting` — it must not ask for a rescan either, or every
// `lucisv.formatOnSave` toggle would pay for a full re-walk (and, on
// a client that pulls, bump the diagnostics generation along with
// it).
assert!(
!ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }),
"turning the save hook on does not move files either"
);
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not");
assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does");
+432
View File
@@ -0,0 +1,432 @@
//! Applying a `didChange`'s edits to a buffer.
//!
//! With `TextDocumentSyncKind::INCREMENTAL` the client stops sending the whole
//! file on every keystroke and sends the ranges it touched instead. The server
//! is then the only holder of the buffer's text, so this module is the one
//! place a wrong offset silently rewrites what the user is looking at — hence
//! a pure function, a second implementation to cross-check it against, and no
//! slicing that can panic. The exact clamping rules are in
//! `docs/features/incremental-sync/README.md`.
use lsp_types::TextDocumentContentChangeEvent;
use vlog_parser::LineIndex;
use crate::convert::Positions;
/// Apply one `didChange`'s content changes to a buffer, in the order the
/// client sent them, and return the buffer that results.
///
/// A change with no range replaces the whole document — what a full-sync
/// client sends, and what still works if one arrives mid-batch.
pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
let mut text = text.to_string();
for change in changes {
let Some(range) = change.range else {
// The whole document. This also resets the state that the ranges
// after it in the same batch are positioned against.
text.clone_from(&change.text);
continue;
};
// A fresh line table per change: each range is positioned against the
// document as the *previous* changes in this batch left it. That is
// O(changes × file) per notification, which at Verilog file sizes is
// microseconds and buys a function with no incremental state to get
// out of step.
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let start = positions.offset(range.start) as usize;
// A range that runs backwards is a client desync. Reading it as an
// insertion at `start` is the one interpretation that deletes nothing:
// we have no resync mechanism, so the safe direction is to keep text.
let end = (positions.offset(range.end) as usize).max(start);
let (Some(before), Some(after)) = (text.get(..start), text.get(end..)) else {
// Unreachable: `Positions::offset` only ever returns character
// boundaries. Written as a skip rather than a slice because the
// slice would panic, and a panic here takes the buffer with it.
continue;
};
text = format!("{before}{}{after}", change.text);
}
text
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::{Position, Range};
fn pos(line: u32, character: u32) -> Position {
Position { line, character }
}
/// A ranged change, the way a client sends one.
fn edit(
start: (u32, u32),
end: (u32, u32),
text: &str,
) -> lsp_types::TextDocumentContentChangeEvent {
TextDocumentContentChangeEvent {
range: Some(Range { start: pos(start.0, start.1), end: pos(end.0, end.1) }),
range_length: None,
text: text.to_string(),
}
}
/// A rangeless change: the whole buffer, as a full-sync client sends it.
fn whole(text: &str) -> TextDocumentContentChangeEvent {
TextDocumentContentChangeEvent { range: None, range_length: None, text: text.to_string() }
}
#[test]
fn an_insert_lands_where_the_range_is_empty() {
let text = "module m;\n wire a;\nendmodule\n";
let after = apply_changes(text, &[edit((1, 8), (1, 8), "b")]);
assert_eq!(after, "module m;\n wire ab;\nendmodule\n");
}
#[test]
fn a_delete_removes_exactly_the_range() {
let text = "module m;\n wire aaa;\nendmodule\n";
let after = apply_changes(text, &[edit((1, 7), (1, 10), "")]);
assert_eq!(after, "module m;\n wire ;\nendmodule\n");
}
#[test]
fn a_replace_swaps_the_range_for_the_text() {
let text = "module m;\n wire a;\nendmodule\n";
let after = apply_changes(text, &[edit((1, 2), (1, 6), "logic")]);
assert_eq!(after, "module m;\n logic a;\nendmodule\n");
}
#[test]
fn a_multi_line_range_collapses_the_lines_it_spans() {
let text = "a\nb\nc\n";
let after = apply_changes(text, &[edit((0, 1), (2, 0), "X")]);
assert_eq!(after, "aXc\n");
}
#[test]
fn later_changes_see_what_the_earlier_ones_did() {
// The batch a real editor sends for "type `wire w;` on a new line",
// split into three: each range is against the state after the last.
let text = "module m;\nendmodule\n";
let after = apply_changes(
text,
&[
edit((1, 0), (1, 0), "\n"), // open a line
edit((1, 0), (1, 0), " wire "), // the keyword
edit((1, 7), (1, 7), "w;"), // the name
],
);
assert_eq!(after, "module m;\n wire w;\nendmodule\n");
}
#[test]
fn a_later_range_positioned_against_the_original_text_would_be_wrong() {
// The regression this whole module exists to prevent: if the line
// table were built once, the second range below would land on the old
// line 1 and the result would differ.
let text = "aaa\nbbb\n";
let after = apply_changes(text, &[edit((0, 0), (0, 0), "x\n"), edit((1, 1), (1, 2), "Z")]);
assert_eq!(after, "x\naZa\nbbb\n");
}
#[test]
fn a_two_byte_character_is_one_utf16_unit_to_the_edit_too() {
let text = "// é ok\n";
let after = apply_changes(text, &[edit((0, 5), (0, 7), "no")]);
assert_eq!(after, "// é no\n");
}
#[test]
fn an_astral_character_takes_two_units_and_is_never_split() {
// `🎉` is 2 UTF-16 units. A boundary on its low half rounds forward
// past the whole character, so no edit can ever cut it in half.
let text = "// 🎉 ok\n";
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 5), "X")]), "// X ok\n");
// Start inside the pair: the emoji survives, the edit begins after it.
assert_eq!(apply_changes(text, &[edit((0, 4), (0, 6), "X")]), "// 🎉Xok\n");
// End inside the pair: rounds forward, so the emoji goes with it.
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 4), "X")]), "// X ok\n");
for change in [edit((0, 4), (0, 4), "!"), edit((0, 4), (0, 5), "!")] {
let out = apply_changes(text, &[change]);
assert!(out.is_char_boundary(out.len()), "still valid UTF-8: {out:?}");
}
}
#[test]
fn an_edit_after_an_emoji_counts_from_the_right_column() {
let text = "// 🎉 wire a;\n";
// "wire" starts at UTF-16 unit 6: `/`,`/`,` `,🎉(2),` `.
let after = apply_changes(text, &[edit((0, 6), (0, 10), "logic")]);
assert_eq!(after, "// 🎉 logic a;\n");
}
#[test]
fn crlf_line_ends_survive_an_edit_on_the_line() {
let text = "module m;\r\n wire a;\r\nendmodule\r\n";
let after = apply_changes(text, &[edit((1, 7), (1, 8), "bb")]);
assert_eq!(after, "module m;\r\n wire bb;\r\nendmodule\r\n");
}
#[test]
fn a_crlf_line_can_be_joined_to_the_next() {
let text = "ab\r\ncd\r\n";
let after = apply_changes(text, &[edit((0, 2), (1, 0), "")]);
assert_eq!(after, "abcd\r\n", "the whole `\\r\\n` goes");
}
#[test]
fn an_edit_at_the_start_of_the_document() {
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 0), "// ")]), "// wire a;\n");
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 4), "logic")]), "logic a;\n");
}
#[test]
fn an_edit_at_end_of_file() {
// The empty last line a trailing newline opens.
assert_eq!(apply_changes("a\n", &[edit((1, 0), (1, 0), "b\n")]), "a\nb\n");
}
#[test]
fn an_insert_at_the_end_of_a_last_line_with_no_trailing_newline() {
assert_eq!(apply_changes("endmodule", &[edit((0, 9), (0, 9), "\n")]), "endmodule\n");
}
#[test]
fn an_edit_into_an_empty_document() {
assert_eq!(apply_changes("", &[edit((0, 0), (0, 0), "module m;")]), "module m;");
}
#[test]
fn a_rangeless_change_replaces_the_whole_document() {
assert_eq!(apply_changes("old\n", &[whole("new\n")]), "new\n");
}
#[test]
fn the_last_of_several_rangeless_changes_wins() {
// What the full-sync handler did before this feature, unchanged.
assert_eq!(apply_changes("old\n", &[whole("a\n"), whole("b\n"), whole("c\n")]), "c\n");
}
#[test]
fn a_rangeless_change_resets_what_the_next_range_is_against() {
let after = apply_changes("anything\n", &[whole("abc\ndef\n"), edit((1, 1), (1, 2), "X")]);
assert_eq!(after, "abc\ndXf\n");
}
#[test]
fn no_changes_is_the_buffer_unchanged() {
assert_eq!(apply_changes("wire a;\n", &[]), "wire a;\n");
}
#[test]
fn a_line_past_the_end_clamps_to_the_end_of_the_document() {
let text = "a\nb\n";
assert_eq!(apply_changes(text, &[edit((99, 0), (99, 5), "X")]), "a\nb\nX");
// And a range that *starts* in the document and ends past it.
assert_eq!(apply_changes(text, &[edit((1, 0), (99, 0), "X")]), "a\nX");
}
#[test]
fn a_character_past_the_end_of_a_line_clamps_to_its_content() {
assert_eq!(apply_changes("ab\ncd\n", &[edit((0, 99), (0, 99), "!")]), "ab!\ncd\n");
assert_eq!(apply_changes("ab\r\ncd\r\n", &[edit((0, 99), (0, 99), "!")]), "ab!\r\ncd\r\n");
}
#[test]
fn a_range_that_runs_backwards_deletes_nothing() {
// Clamping `end` up to `start` turns a desynced range into a pure
// insertion — the only reading that cannot lose the user's text.
assert_eq!(apply_changes("abcdef\n", &[edit((0, 4), (0, 1), "X")]), "abcdXef\n");
assert_eq!(apply_changes("ab\ncd\n", &[edit((1, 1), (0, 0), "X")]), "ab\ncXd\n");
}
// ------------------------------------------------------------------
// randomized cross-check against a second implementation
// ------------------------------------------------------------------
/// A fixed-seed linear congruential generator — deterministic randomness
/// with no dependency. The constants are Knuth's MMIX.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
self.0 >> 33
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
}
/// The same rules, implemented a second way: a flat `Vec<char>` with the
/// line starts scanned out of it, rather than byte offsets off a
/// `LineIndex`. Sharing no code with `apply_changes` is the point.
fn reference_apply(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
let mut text = text.to_string();
for change in changes {
let Some(range) = change.range else {
text.clone_from(&change.text);
continue;
};
let chars: Vec<char> = text.chars().collect();
let start = reference_index(&chars, range.start);
let end = reference_index(&chars, range.end).max(start);
let mut out: String = chars[..start].iter().collect();
out.push_str(&change.text);
out.extend(chars[end..].iter());
text = out;
}
text
}
/// The index into `chars` that a position names: lines are `\n`-
/// terminated, one `\r` before that terminator is not content, a
/// character past a line's content clamps to it, a line past the last
/// clamps to the end of the text, and a character landing inside a
/// surrogate pair rounds forward past the whole character.
fn reference_index(chars: &[char], position: Position) -> usize {
let mut starts = vec![0usize];
for (i, c) in chars.iter().enumerate() {
if *c == '\n' {
starts.push(i + 1);
}
}
let Some(&start) = starts.get(position.line as usize) else {
return chars.len();
};
// The line's content ends before its `\n`, and before one `\r`.
let mut end = match starts.get(position.line as usize + 1) {
Some(&next) => next - 1,
None => chars.len(),
};
if end > start && chars[end - 1] == '\r' {
end -= 1;
}
let mut units = 0u32;
let mut at = start;
while at < end && units < position.character {
units += chars[at].len_utf16() as u32;
at += 1;
}
at
}
/// A random document over an alphabet that mixes every width and both
/// line endings — including a bare `\r`, which is an ordinary character.
fn random_text(rng: &mut Lcg) -> String {
const ALPHABET: [&str; 8] = ["a", "b", " ", ";", "\n", "\r\n", "é", "🎉"];
let len = rng.below(24);
(0..len).map(|_| ALPHABET[rng.below(8) as usize]).collect()
}
/// A random change: mostly ranged, occasionally a whole-document reset,
/// with positions that are often — but deliberately not always — inside
/// the document.
fn random_change(rng: &mut Lcg, text: &str) -> TextDocumentContentChangeEvent {
if rng.below(10) == 0 {
return whole(&random_text(rng));
}
let lines = text.matches('\n').count() as u32 + 1;
let position = |rng: &mut Lcg| Position {
line: rng.below(u64::from(lines) + 2) as u32,
character: rng.below(12) as u32,
};
let (first, second) = (position(rng), position(rng));
TextDocumentContentChangeEvent {
range: Some(Range { start: first, end: second }),
range_length: None,
text: random_text(rng),
}
}
#[test]
fn random_edit_sequences_agree_with_the_reference_model() {
let mut rng = Lcg(0x5EED_1CE5);
let mut ranged = 0usize;
for case in 0..400 {
let text = random_text(&mut rng);
let mut changes = Vec::new();
let mut running = text.clone();
for _ in 0..rng.below(5) + 1 {
let change = random_change(&mut rng, &running);
ranged += usize::from(change.range.is_some());
// The next range is against the state this one leaves.
running = apply_changes(&running, std::slice::from_ref(&change));
changes.push(change);
}
let ours = apply_changes(&text, &changes);
assert_eq!(ours, reference_apply(&text, &changes), "case {case}, from {text:?}");
assert_eq!(ours, running, "case {case}: one batch equals the changes one at a time");
}
assert!(ranged > 500, "the cases must be mostly ranged edits, got {ranged}");
}
// ------------------------------------------------------------------
// QA additions (2026-08-26) — see docs/features/incremental-sync/README.md
// QA log for the full writeup of each of these.
// ------------------------------------------------------------------
#[test]
fn a_deletion_starting_at_the_low_surrogate_index_preserves_the_character() {
// Character 4 is the low half of `🎉`'s pair (the emoji starts at 3,
// ends at 5). A *start* boundary landing there rounds forward past
// the whole character, so the emoji is excluded from — and survives
// — a deletion that begins mid-pair.
let text = "// 🎉 ok\n";
let after = apply_changes(text, &[edit((0, 4), (0, 6), "")]);
assert_eq!(after, "// 🎉ok\n", "the emoji stays, only the trailing space is deleted");
}
#[test]
fn a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character() {
// Symmetric case: an *end* boundary on the low half also rounds
// forward, but here that means the deletion is widened to swallow
// the whole character rather than stopping short of it.
let text = "// 🎉 ok\n";
let after = apply_changes(text, &[edit((0, 3), (0, 4), "")]);
assert_eq!(after, "// ok\n", "the whole emoji is gone, both flanking spaces remain");
}
#[test]
fn crlf_split_across_two_changes_in_one_batch_reorders_the_bytes() {
// QA finding (docs/features/incremental-sync/README.md QA log,
// 2026-08-26): pinning present, *surprising* behavior rather than
// asserting it is correct. `convert.rs::line_content_end` treats a
// trailing bare `\r` as "not content" whether or not a `\n` will
// follow it, so a second change in the same batch that targets "end
// of line" after a first change appended a lone `\r` lands *before*
// that `\r`, not after it. A client that split one `\r\n` insertion
// into two ranged changes this way would get `\n\r`, not `\r\n`. No
// real editor's diff algorithm is known to do this, and no panic or
// data loss occurs — but if this test's expected string ever needs
// to change to `"ab\r\n"`, that is a deliberate fix to
// `Positions::offset`/`line_content_end`, not an accidental one.
let text = "ab";
let after = apply_changes(text, &[edit((0, 2), (0, 2), "\r"), edit((0, 2), (0, 2), "\n")]);
assert_eq!(after, "ab\n\r", "known edge case: see the comment above");
}
#[test]
fn a_change_covering_the_final_newline_removes_exactly_it() {
let text = "a\nb\n";
let after = apply_changes(text, &[edit((1, 1), (2, 0), "")]);
assert_eq!(after, "a\nb", "the trailing newline is gone, nothing else is");
}
#[test]
fn zero_width_inserts_at_the_same_position_compose_in_batch_order() {
// Not a bug: per protocol, each change is positioned against what the
// previous ones in the batch left, so two inserts naming the same
// literal position land with the *second* one first — a client that
// wants "12" must advance the second insert's position past the
// first's text, exactly as it would need to for a non-zero-width
// range. Pinned so a future refactor cannot silently change the
// batch's ordering semantics.
let text = "x";
let after = apply_changes(text, &[edit((0, 0), (0, 0), "1"), edit((0, 0), (0, 0), "2")]);
assert_eq!(after, "21x");
}
}
+649 -32
View File
@@ -1,10 +1,18 @@
//! `textDocument/semanticTokens/full`.
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
//!
//! Classification comes from the lexer's token stream, refined for plain
//! identifiers by `vlog_semantic`. The full mapping table is in
//! `docs/features/lucisv-server/README.md`.
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
//! `docs/features/semantic-tokens-delta/README.md`.
//!
//! One tokenizer and one encoder serve all three requests: classification
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
//! protocol thinks in), a range answer drops the ones it does not want, and
//! `encode` delta-encodes whatever is left from the start of the document.
use lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens};
use lsp_types::{
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_semantic::{Semantics, SymbolKind};
@@ -68,12 +76,53 @@ struct Piece {
modifiers: u32,
}
/// One classified token in the protocol's own coordinates: a zero-based line,
/// a UTF-16 start column and a UTF-16 length. This is the form the range
/// filter works in, and the only input `encode` has.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Absolute {
line: u32,
start: u32,
length: u32,
ty: u32,
modifiers: u32,
}
impl Absolute {
/// Where this token starts, as the protocol names it.
fn from(&self) -> Position {
Position { line: self.line, character: self.start }
}
/// Where it ends. A token never spans a line break (see `split_lines`), so
/// this is on the same line.
fn to(&self) -> Position {
Position { line: self.line, character: self.start + self.length }
}
}
/// Classify and encode the whole buffer.
///
/// A buffer that does not lex has no tokens, so this is empty — the user sees
/// the editor's own grammar highlighting plus the parse diagnostic, which is
/// the honest answer while the file is unlexable.
pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
pub fn semantic_tokens(doc: &Document) -> Vec<SemanticToken> {
encode(&absolute(doc))
}
/// The tokens a range covers, encoded as a self-contained answer.
///
/// The protocol asks for a whole `SemanticTokens` here, not a slice of the
/// full one: the relative encoding restarts from the start of the document
/// exactly as a full answer's does, and only the tokens outside the range are
/// missing. A token that merely overlaps the range is kept whole — the client
/// asked which tokens to draw, not where to cut them.
pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticToken> {
encode(&within(absolute(doc), range))
}
/// Classify the whole buffer, split at line boundaries, in wire order.
fn absolute(doc: &Document) -> Vec<Absolute> {
let mut pieces = Vec::new();
for token in &doc.tokens {
collect_trivia(token, &mut pieces);
@@ -85,7 +134,21 @@ pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
});
}
}
encode(pieces, doc)
flatten(pieces, doc)
}
/// The tokens overlapping `range`, in the order they came in.
///
/// Overlap, not containment: a client sends the lines it is showing, and a
/// token straddling the first of them is one the user can see. An **empty**
/// range covers no characters, so it overlaps nothing — the containment test
/// below would otherwise answer with every token the collapsed point sits
/// inside.
fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
if range.start >= range.end {
return Vec::new();
}
tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect()
}
/// Comments live as trivia on the token that follows (or, for a trailing
@@ -162,14 +225,15 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
}
}
/// Split every piece at line boundaries, sort, and delta-encode.
/// Split every piece at line boundaries, measure it in UTF-16 units, and
/// sort.
///
/// The spec forbids a token from spanning a line break, and Verilog has three
/// shapes that would: a block comment, a continued `` `define`` and a
/// multi-line macro invocation.
fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
fn flatten(pieces: Vec<Piece>, doc: &Document) -> Vec<Absolute> {
let positions = doc.positions();
let mut flat: Vec<(u32, u32, u32, u32, u32)> = Vec::new();
let mut flat: Vec<Absolute> = Vec::new();
for piece in pieces {
for line_span in split_lines(&doc.text, piece.span) {
let start = positions.position(line_span.start);
@@ -177,33 +241,78 @@ fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
if end.character <= start.character {
continue;
}
flat.push((
start.line,
start.character,
end.character - start.character,
piece.ty as u32,
piece.modifiers,
));
flat.push(Absolute {
line: start.line,
start: start.character,
length: end.character - start.character,
ty: piece.ty as u32,
modifiers: piece.modifiers,
});
}
}
flat.sort_by_key(|&(line, start, ..)| (line, start));
flat.sort_by_key(|t| (t.line, t.start));
flat
}
let mut data = Vec::with_capacity(flat.len());
/// Delta-encode, from the start of the document.
///
/// Pure: the same tokens always encode the same way, whether they are the
/// whole file's or the handful a range kept.
fn encode(tokens: &[Absolute]) -> Vec<SemanticToken> {
let mut data = Vec::with_capacity(tokens.len());
let (mut prev_line, mut prev_start) = (0u32, 0u32);
for (line, start, length, ty, modifiers) in flat {
let delta_line = line - prev_line;
let delta_start = if delta_line == 0 { start - prev_start } else { start };
for token in tokens {
let delta_line = token.line - prev_line;
let delta_start = if delta_line == 0 { token.start - prev_start } else { token.start };
data.push(SemanticToken {
delta_line,
delta_start,
length,
token_type: ty,
token_modifiers_bitset: modifiers,
length: token.length,
token_type: token.ty,
token_modifiers_bitset: token.modifiers,
});
prev_line = line;
prev_start = start;
prev_line = token.line;
prev_start = token.start;
}
SemanticTokens { result_id: None, data }
data
}
/// How many numbers one token is on the wire. An edit's `start` and
/// `deleteCount` index that flat array, not the token list.
const FIELDS: u32 = 5;
/// The edits that turn `old` into `new`: one replacement of everything
/// between the common prefix and the common suffix, or none at all when the
/// two are identical.
///
/// **Minimality beyond the prefix/suffix trim is deliberately not attempted.**
/// A real diff would find the two edits an insertion in the middle of a file
/// really is, but every token after an edit carries a changed `deltaLine`
/// anyway, so the interesting cases — typing at the end of a line, or on a
/// line — trim to almost nothing regardless. rust-analyzer answers the same
/// way, and the invariant that matters is that applying the result
/// reproduces `new` exactly.
pub fn delta(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<SemanticTokensEdit> {
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
// The suffix is counted over what the prefix left, never over the whole
// vectors: two token lists that repeat themselves — which identical lines
// of Verilog produce exactly — would otherwise claim the same tokens as
// both prefix and suffix, and the edit would delete a region it also
// re-inserts (or, with the subtraction underflowing, not be computable at
// all). This overlap is the classic bug in this algorithm.
let (old_rest, new_rest) = (&old[prefix..], &new[prefix..]);
let suffix =
old_rest.iter().rev().zip(new_rest.iter().rev()).take_while(|(a, b)| a == b).count();
let deleted = old_rest.len() - suffix;
let inserted = &new_rest[..new_rest.len() - suffix];
if deleted == 0 && inserted.is_empty() {
return Vec::new();
}
vec![SemanticTokensEdit {
start: prefix as u32 * FIELDS,
delete_count: deleted as u32 * FIELDS,
data: Some(inserted.to_vec()),
}]
}
/// One span per line the span touches, each stopping before the `\n`.
@@ -231,17 +340,30 @@ mod tests {
use crate::state::Workspace;
use lsp_types::Uri;
use std::str::FromStr;
use vlog_semantic::WorkspaceIndex;
/// Decode the delta encoding back to absolute (line, start, len, type).
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
/// Analyze `text` as an open buffer and hand the document to `f`.
fn with_document<T>(text: &str, f: impl FnOnce(&Document) -> T) -> T {
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let tokens = semantic_tokens(ws.document(&uri).expect("open"));
f(ws.document(&uri).expect("open"))
}
/// The whole buffer's tokens, as they go on the wire.
fn tokens_of(text: &str) -> Vec<SemanticToken> {
with_document(text, semantic_tokens)
}
/// The tokens a range answer carries.
fn ranged(text: &str, range: Range) -> Vec<SemanticToken> {
with_document(text, |doc| semantic_tokens_in_range(doc, range))
}
/// Decode the delta encoding back to absolute (line, start, len, type).
fn decode(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
let (mut line, mut start) = (0u32, 0u32);
tokens
.data
.iter()
data.iter()
.map(|t| {
line += t.delta_line;
start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start };
@@ -250,6 +372,18 @@ mod tests {
.collect()
}
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
decode(&tokens_of(text))
}
/// A range, spelled the way a test reads best.
fn range(from: (u32, u32), to: (u32, u32)) -> Range {
Range {
start: Position { line: from.0, character: from.1 },
end: Position { line: to.0, character: to.1 },
}
}
#[test]
fn keywords_numbers_and_strings_are_classified() {
let out = decoded("module m;\n localparam W = 8;\n wire a = \"s\";\nendmodule\n");
@@ -358,4 +492,487 @@ mod tests {
vec![TextRange::new(0, 1), TextRange::new(2, 3)]
);
}
// ------------------------------------------------------------------
// `semanticTokens/range`
// ------------------------------------------------------------------
/// Four lines, every one of them carrying tokens.
const FOUR_LINES: &str =
"module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n// tail\n";
#[test]
fn a_range_covering_everything_is_the_full_answer() {
let full = tokens_of(FOUR_LINES);
assert_eq!(ranged(FOUR_LINES, range((0, 0), (99, 0))), full);
}
#[test]
fn a_range_answer_re_encodes_from_the_start_of_the_document() {
// The whole point of the re-encoding: a range answer is a
// self-contained `SemanticTokens`, so its first token's deltas are
// absolute — a client that pasted the slice out of the full answer
// would draw line 2's tokens on line 0.
let data = ranged(FOUR_LINES, range((2, 0), (3, 0)));
let first = data.first().expect("line 2 has tokens");
assert_eq!(first.delta_line, 2, "absolute from the document start");
assert_eq!(first.delta_start, 2, "the `wire` keyword's own column");
assert_eq!(
decode(&data),
decoded(FOUR_LINES).into_iter().filter(|&(line, ..)| line == 2).collect::<Vec<_>>(),
"the same tokens the full answer puts on that line"
);
}
#[test]
fn an_empty_range_covers_no_characters_and_so_no_tokens() {
// Collapsed on a token, which is the tempting case to get wrong: a
// zero-width range draws nothing, so it must answer nothing.
assert!(ranged(FOUR_LINES, range((0, 3), (0, 3))).is_empty());
assert!(ranged(FOUR_LINES, range((0, 0), (0, 0))).is_empty());
}
#[test]
fn a_range_that_starts_mid_token_keeps_that_token_whole() {
// The client asked which tokens to draw, not where to cut them —
// and a length trimmed to the range would be a lie about the source.
let data = ranged("module m;\nendmodule\n", range((0, 3), (0, 4)));
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
}
#[test]
fn a_range_touching_no_token_is_empty() {
// Wholly inside the whitespace of a line, and wholly past the file.
assert!(ranged("module m;\n\n\nendmodule\n", range((1, 0), (2, 0))).is_empty());
assert!(ranged(FOUR_LINES, range((90, 0), (99, 0))).is_empty());
}
#[test]
fn a_range_answer_never_carries_a_token_from_outside_it() {
let inside = decode(&ranged(FOUR_LINES, range((1, 0), (2, 0))));
assert!(!inside.is_empty(), "premise: line 1 has tokens");
assert!(inside.iter().all(|&(line, ..)| line == 1), "{inside:?}");
}
/// The range/full agreement, on files nobody wrote to exercise it: for a
/// window of whole lines, the range answer must decode to exactly the
/// tokens the full answer puts on those lines. Stated line-wise rather
/// than with the handler's own overlap test, so the two are independent.
/// Skipped when `corpus/` is not checked out, like every other corpus
/// test in this crate.
#[test]
fn a_line_window_answers_exactly_the_full_answers_tokens_on_those_lines() {
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let files =
[corpus.join("picorv32/picorv32.v"), corpus.join("common_cells/src/fifo_v3.sv")];
let mut windows_checked = 0;
for path in files {
let Ok(text) = std::fs::read_to_string(&path) else {
eprintln!("{} not checked out — skipping", path.display());
continue;
};
let doc = Document::new(Some(path.clone()), text, &WorkspaceIndex::default());
let full = decode(&semantic_tokens(&doc));
assert!(!full.is_empty(), "{}: the premise, a file with tokens", path.display());
let last = full.iter().map(|&(line, ..)| line).max().unwrap_or(0);
// Forty-line windows, the size an editor's viewport request is.
let mut from = 0;
while from <= last {
let to = from + 40;
let window = decode(&semantic_tokens_in_range(&doc, range((from, 0), (to, 0))));
let expected: Vec<_> =
full.iter().filter(|&&(line, ..)| line >= from && line < to).copied().collect();
assert_eq!(window, expected, "{}: lines {from}..{to}", path.display());
windows_checked += 1;
from = to;
}
}
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
}
// ------------------------------------------------------------------
// `semanticTokens/full/delta`
// ------------------------------------------------------------------
/// The flat `u32` array the wire actually carries — what an edit's
/// `start` and `deleteCount` index into.
fn flat(tokens: &[SemanticToken]) -> Vec<u32> {
tokens
.iter()
.flat_map(|t| {
[t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset]
})
.collect()
}
/// Apply the edits exactly as a client does: in order, by index, on the
/// flat array. Deliberately shares no code with `delta`.
fn apply_edits(old: &[u32], edits: &[SemanticTokensEdit]) -> Vec<u32> {
let mut data = old.to_vec();
for edit in edits {
let start = edit.start as usize;
let end = start + edit.delete_count as usize;
let inserted = flat(edit.data.as_deref().unwrap_or_default());
data.splice(start..end, inserted);
}
data
}
/// The invariant: applying what the server sent reproduces the new token
/// list exactly. Returns the edits so a test can also say how many.
fn reconstructs(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
let (old, new) = (tokens_of(before), tokens_of(after));
let edits = delta(&old, &new);
assert_eq!(
apply_edits(&flat(&old), &edits),
flat(&new),
"the edits must reconstruct the new data:\n{before:?}\n{after:?}"
);
edits
}
const MODULE: &str = "module m;\n wire a;\nendmodule\n";
#[test]
fn an_unchanged_buffer_produces_no_edits_at_all() {
assert!(reconstructs(MODULE, MODULE).is_empty());
}
#[test]
fn an_append_at_the_end_is_one_edit_that_deletes_nothing() {
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
assert_eq!(edits.len(), 1);
assert_eq!(edits[0].delete_count, 0, "nothing was removed: {edits:?}");
}
#[test]
fn a_deletion_at_the_end_is_one_edit_that_inserts_nothing() {
let edits = reconstructs("module m;\n wire a;\nendmodule\n// gone\n", MODULE);
assert_eq!(edits.len(), 1);
assert_eq!(edits[0].data.as_deref().unwrap_or_default(), &[], "{edits:?}");
}
#[test]
fn a_change_in_the_middle_leaves_the_ends_alone() {
let edits = reconstructs(
"module m;\n wire a;\n wire b;\nendmodule\n",
"module m;\n logic a;\n wire b;\nendmodule\n",
);
assert_eq!(edits.len(), 1);
assert!(edits[0].start > 0, "the first line's tokens are common prefix: {edits:?}");
}
#[test]
fn a_complete_replacement_is_one_edit_over_everything() {
let edits = reconstructs(MODULE, "`define W 8\n");
assert_eq!(edits.len(), 1);
assert_eq!(edits[0].start, 0, "nothing was in common: {edits:?}");
}
#[test]
fn a_buffer_that_stops_lexing_deletes_every_token_and_back() {
// Mid-keystroke reality: an unterminated block comment has no tokens
// at all, and the next keystroke brings them all back.
let broken = "module m;\n wire a; /* unterminated\n";
assert!(tokens_of(broken).is_empty(), "the premise");
reconstructs(MODULE, broken);
reconstructs(broken, MODULE);
}
#[test]
fn an_empty_buffer_is_a_legal_end_of_a_delta_in_both_directions() {
reconstructs(MODULE, "");
reconstructs("", MODULE);
assert!(reconstructs("", "").is_empty());
}
/// A token, for the shapes that are about the algorithm rather than about
/// Verilog.
fn token(delta_line: u32, delta_start: u32, length: u32) -> SemanticToken {
SemanticToken {
delta_line,
delta_start,
length,
token_type: Highlight::Keyword as u32,
token_modifiers_bitset: 0,
}
}
#[test]
fn the_suffix_is_capped_so_it_cannot_overlap_the_prefix() {
// old = [A, B, A], new = [A]. The prefix claims the leading A; a
// suffix counted over the *whole* lists would claim the trailing one
// — the same token twice — and `new[prefix..new.len() - suffix]`
// would then run backwards. Counting the suffix over what the prefix
// left is the cap, and this is the shape that proves it.
let (a, b) = (token(0, 0, 1), token(1, 0, 2));
let old = vec![a, b, a];
let new = vec![a];
let edits = delta(&old, &new);
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
// And the mirror: growing into a repeating list.
let edits = delta(&new, &old);
assert_eq!(apply_edits(&flat(&new), &edits), flat(&old));
// The fully periodic case, where every token equals every other.
let old = vec![a, a, a, a, a];
let new = vec![a, a, a];
let edits = delta(&old, &new);
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
}
#[test]
fn repeated_lines_of_verilog_are_the_same_trap_on_real_tokens() {
// Identical lines encode to identical tokens — the delta encoding is
// relative, so line 2 and line 3 of this buffer are byte-for-byte the
// same five numbers. Deleting one of them is the overlap shape above,
// reached without constructing anything by hand.
let three = "module m;\n wire a;\n wire a;\n wire a;\nendmodule\n";
let one = "module m;\n wire a;\nendmodule\n";
let data = tokens_of(three);
assert_eq!(data[2], data[4], "the premise: the encoding really does repeat");
reconstructs(three, one);
reconstructs(one, three);
}
#[test]
fn an_edits_indices_count_numbers_and_not_tokens() {
// The off-by-five that silently corrupts a client's cache: `start`
// and `deleteCount` index the flat array, so both are five times a
// token index.
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
assert_eq!(edits[0].start % FIELDS, 0, "{edits:?}");
assert_eq!(edits[0].start, tokens_of(MODULE).len() as u32 * FIELDS);
}
// ------------------------------------------------------------------
// randomized sweep
// ------------------------------------------------------------------
/// A fixed-seed linear congruential generator — deterministic randomness
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` uses.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
self.0 >> 33
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
}
/// Lines a module body can be built from — repeats included, because
/// repeats are what make the prefix and suffix fight over a token.
const BODY: [&str; 8] = [
" wire a;",
" wire a;",
" localparam W = 8;",
" // a comment",
" assign a = b & c;",
" always_ff @(posedge clk) q <= d;",
" /* block */",
" wire [W-1:0] bus;",
];
fn buffer(rng: &mut Lcg) -> String {
let mut text = String::from("module m;\n");
for _ in 0..rng.below(9) {
text.push_str(BODY[rng.below(BODY.len() as u64) as usize]);
text.push('\n');
}
text.push_str("endmodule\n");
text
}
#[test]
fn every_pair_of_real_buffers_round_trips_through_its_delta() {
let mut rng = Lcg(0x5eed);
for _ in 0..300 {
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
reconstructs(&before, &after);
reconstructs(&after, &before);
}
}
// ------------------------------------------------------------------
// QA (2026-08-26): independent verification of the delta round-trip
// and the range boundaries, on a code path that shares nothing with
// the dev's own `apply_edits`/`reconstructs` helpers above.
// ------------------------------------------------------------------
/// QA's own applier: unlike `apply_edits`, this never touches the flat
/// `u32` array — it walks `SemanticToken`s and slices by hand instead of
/// calling `Vec::splice`. It also asserts the `FIELDS` division is exact,
/// which is a second, independent check of the "five times a token
/// index" claim (`an_edits_indices_count_numbers_and_not_tokens`).
fn independent_apply(
old: &[SemanticToken],
edits: &[SemanticTokensEdit],
) -> Vec<SemanticToken> {
let mut data = old.to_vec();
for edit in edits {
assert_eq!(edit.start % FIELDS, 0, "start is not a whole token: {edit:?}");
assert_eq!(edit.delete_count % FIELDS, 0, "deleteCount is not a whole token: {edit:?}");
let start = (edit.start / FIELDS) as usize;
let deleted = (edit.delete_count / FIELDS) as usize;
let mut rebuilt = Vec::with_capacity(data.len());
rebuilt.extend_from_slice(&data[..start]);
if let Some(inserted) = &edit.data {
rebuilt.extend_from_slice(inserted);
}
rebuilt.extend_from_slice(&data[start + deleted..]);
data = rebuilt;
}
data
}
/// Same invariant as `reconstructs`, checked with QA's applier instead of
/// the dev's.
fn reconstructs_independently(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
let (old, new) = (tokens_of(before), tokens_of(after));
let edits = delta(&old, &new);
assert_eq!(
independent_apply(&old, &edits),
new,
"QA reconstruction failed:\n{before:?}\n{after:?}"
);
edits
}
#[test]
fn qa_the_two_independently_written_appliers_never_disagree() {
// The dev's applier works on the flat `u32` array; QA's works on
// `SemanticToken`s and never calls `Vec::splice`. Run both over the
// same edits and the same inputs and demand they land on the same
// place — and on the truth.
let mut rng = Lcg(0xC0FFEE);
for _ in 0..200 {
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
let (old, new) = (tokens_of(&before), tokens_of(&after));
let edits = delta(&old, &new);
let via_flat = apply_edits(&flat(&old), &edits);
let via_tokens = flat(&independent_apply(&old, &edits));
assert_eq!(via_flat, via_tokens, "the two appliers disagree:\n{before:?}\n{after:?}");
assert_eq!(via_tokens, flat(&new));
}
}
#[test]
fn qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes() {
let module = "module m;\n wire a;\n wire b;\nendmodule\n";
// Both ends change at once, middle stays: prefix and suffix both
// trim to non-trivial amounts.
reconstructs_independently(
module,
"`define X 1\nmodule m;\n wire a;\n wire b;\nendmodule\n// tail\n",
);
// Middle only.
reconstructs_independently(module, "module m;\n wire a;\n logic b;\nendmodule\n");
// Identical.
reconstructs_independently(module, module);
// Complete replacement: nothing in common.
reconstructs_independently(module, "`define totally different 1\n");
// Old empty, new empty.
reconstructs_independently("", module);
reconstructs_independently(module, "");
assert!(reconstructs_independently("", "").is_empty());
// Single-token file, both directions and against itself.
const SINGLE: &str = "// only one token\n";
assert_eq!(tokens_of(SINGLE).len(), 1, "the premise: exactly one token");
reconstructs_independently(SINGLE, module);
reconstructs_independently(module, SINGLE);
reconstructs_independently(SINGLE, SINGLE);
}
/// A second, unrelated PRNG (xorshift64, not the dev's LCG) with its own
/// seed.
struct Xorshift64(u64);
impl Xorshift64 {
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
}
/// A pool that does not overlap the dev's `BODY`: it adds a block
/// comment that spans lines, a continued `` `define``, and a generate
/// block — pieces whose token *count* changes non-locally, not just
/// whose content does.
const QA_BODY: [&str; 9] = [
" wire a;",
" wire a;",
" localparam W = 4;",
" // a trailing comment",
" assign a = b ^ c;",
" /* a block\n comment spanning lines */",
" `define FF(q, d) \\\n always_ff @(posedge clk) q <= d;",
" generate\n if (W > 1) wire c;\n endgenerate",
" wire [W-1:0] bus;",
];
fn qa_buffer(rng: &mut Xorshift64) -> String {
let mut text = String::from("module m;\n");
for _ in 0..rng.below(9) {
text.push_str(QA_BODY[rng.below(QA_BODY.len() as u64) as usize]);
text.push('\n');
}
text.push_str("endmodule\n");
text
}
#[test]
fn qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips() {
let mut rng = Xorshift64(0xDEAD_BEEF_1234_5678);
for _ in 0..300 {
let (before, after) = (qa_buffer(&mut rng), qa_buffer(&mut rng));
reconstructs_independently(&before, &after);
reconstructs_independently(&after, &before);
}
}
#[test]
fn qa_a_range_ending_mid_token_keeps_that_token_whole() {
// Mirror of `a_range_that_starts_mid_token_keeps_that_token_whole`:
// the overlap guard must be symmetric at the far boundary too.
let data = ranged("module m;\nendmodule\n", range((0, 0), (0, 3)));
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
}
#[test]
fn qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty() {
// Not an empty *line* (already covered by
// `a_range_touching_no_token_is_empty`) — whitespace, plus an
// unemitted `=`, between two real tokens on the same line.
let text = "module m;\n assign a = b;\nendmodule\n";
// "a" is the single character at column 9 (ends at 10); "b" starts
// at column 17. Columns 11..16 are wholly inside that gap.
let data = ranged(text, range((1, 11), (1, 16)));
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
}
#[test]
fn qa_a_reversed_range_is_total_and_answers_nothing() {
// start > end is not a shape any client should send, but `within`'s
// guard (`range.start >= range.end`) is symmetric to it: this must
// not panic, and must answer empty exactly like a zero-width range.
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
}
}
+666
View File
@@ -721,6 +721,73 @@ fn pushed_settings_reach_the_formatter_and_can_change_mid_session() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_save_hook_is_advertised_and_formats_only_when_it_is_asked_to() {
// The one thing a unit test cannot check: that the capability really
// reaches the wire, and that a client's `formatOnSave` push really turns
// the hook on for the requests that follow it.
let dir = temp_dir("willsave");
let file = dir.join("m.sv");
std::fs::write(&file, UNINDENTED).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let will_save = |id: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/willSaveWaitUntil","params":{{"textDocument":{{"uri":"{uri}"}},"reason":1}}}}"#
))
};
let formatted = "module settings_me;\n wire a;\nendmodule\n";
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(UNINDENTED).expect("json")
)),
// Nothing pushed: the hook declines, so a client that never opted in
// saves exactly what it was going to save.
will_save(2),
frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"formatOnSave":true}}}}"#),
will_save(3),
// The client applies the edit and writes; the buffer it now holds is
// what the next save asks about.
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(formatted).expect("json")
)),
will_save(4),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let sync = &initialize["result"]["capabilities"]["textDocumentSync"];
assert_eq!(sync["willSaveWaitUntil"], true, "the hook is advertised: {sync:#?}");
assert!(sync.get("willSave").is_none(), "the notification is not: {sync:#?}");
let declined = messages.iter().find(|m| m["id"] == 2).expect("a response to the first save");
assert!(declined["result"].is_null(), "off by default: {declined:#?}");
assert_eq!(new_text(&messages, 3), formatted, "the push turns it on for the next save");
let again = messages.iter().find(|m| m["id"] == 4).expect("a response to the third save");
assert_eq!(
again["result"].as_array().expect("an array of edits").len(),
0,
"a formatted buffer saves with no edits at all: {again:#?}"
);
assert!(
!messages.iter().any(|m| m["method"] == "window/showMessage"),
"nothing went wrong, so nothing was said: {messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_pushed_exclude_rebuilds_the_index_mid_session() {
// The one link a unit test cannot check: that the notification handler
@@ -2500,3 +2567,602 @@ endmodule
let _ = std::fs::remove_dir_all(&dir);
}
/// A buffer with one parse error and one lint finding, for the diagnostics
/// sessions below.
const DIAGNOSTIC_SOURCE: &str = "module m;\n\twire ;\nendmodule\n";
#[test]
fn a_pulling_client_is_answered_and_never_pushed_over_the_wire() {
// What only an e2e test can check: that a client which advertised
// `textDocument.diagnostic` at `initialize` really is pushed nothing —
// the "never both models" rule is about the wire, not about a handler.
let dir = temp_dir("pull");
let file = dir.join("m.sv");
std::fs::write(&file, DIAGNOSTIC_SOURCE).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"diagnostic":{{}}}}}}}}}}"#
));
let initialize = live.wait_for(|m| m["id"] == 1);
let provider = &initialize["result"]["capabilities"]["diagnosticProvider"];
assert_eq!(provider["identifier"], "lucisv", "{initialize:#?}");
assert_eq!(provider["interFileDependencies"], true, "{initialize:#?}");
assert_eq!(provider["workspaceDiagnostics"], true, "{initialize:#?}");
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(DIAGNOSTIC_SOURCE).expect("json")
));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"#
));
// The next thing the server says is either the answer or a push it must
// never have sent — so this one wait proves both halves.
let full = live.wait_for(|m| m["id"] == 2 || m["method"] == "textDocument/publishDiagnostics");
assert_eq!(full["id"], 2, "a pulling client must not be pushed diagnostics: {full:#?}");
assert_eq!(full["result"]["kind"], "full");
let items = full["result"]["items"].as_array().expect("items");
assert_eq!(items.len(), 2, "the parse error and the lint warning: {full:#?}");
assert!(items.iter().all(|item| item["source"] == "lucisv"), "{items:#?}");
let result_id = full["result"]["resultId"].as_str().expect("a result id").to_string();
// Nothing moved, so the client's cached report still stands.
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{result_id}"}}}}"#
));
let unchanged = live.wait_for(|m| m["id"] == 3);
assert_eq!(unchanged["result"]["kind"], "unchanged", "{unchanged:#?}");
// An edit moves it, and the fixed buffer comes back clean.
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string("module m;\n wire a;\nendmodule\n").expect("json")
));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{result_id}"}}}}"#
));
let after = live.wait_for(|m| m["id"] == 4 || m["method"] == "textDocument/publishDiagnostics");
assert_eq!(after["id"], 4, "still no push: {after:#?}");
assert_eq!(after["result"]["kind"], "full", "{after:#?}");
assert_eq!(after["result"]["items"].as_array().map(Vec::len), Some(0), "{after:#?}");
// And the workspace report names the open buffer.
live.send(
r#"{"jsonrpc":"2.0","id":5,"method":"workspace/diagnostic","params":{"identifier":"lucisv","previousResultIds":[]}}"#,
);
let workspace = live.wait_for(|m| m["id"] == 5);
let items = workspace["result"]["items"].as_array().expect("items");
assert_eq!(items.len(), 1, "one open buffer: {workspace:#?}");
assert_eq!(items[0]["uri"], uri.as_str(), "{workspace:#?}");
assert_eq!(items[0]["kind"], "full", "{workspace:#?}");
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_command_pushes_its_edit_to_a_client_that_can_apply_one() {
// The bug §9a fixes, checked where it actually bit: on the wire, against
// a client that says what `vscode-languageclient` says.
let dir = temp_dir("applyedit");
let sub = dir.join("sub.sv");
std::fs::write(&sub, PORTS_SUB).expect("write");
let top = dir.join("top.sv");
std::fs::write(&top, PORTS_TOP).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"applyEdit":true}}}}}}}}"#
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(PORTS_TOP).expect("json")
));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/executeCommand","params":{{"command":"lucisv.propagatePorts","arguments":["{top_uri}",{{"line":2,"character":6}}]}}}}"#
));
// The push, before the command's own answer.
let push = live.wait_for(|m| m["method"] == "workspace/applyEdit");
assert_eq!(push["params"]["label"], "lucisv: lucisv.propagatePorts", "{push:#?}");
let edits = push["params"]["edit"]["changes"][&top_uri].as_array().expect("edits");
assert_eq!(edits[0]["newText"], ", .rst(rst)", "{push:#?}");
// Answer it the way an editor does, and the command answers `null`.
let id = serde_json::to_string(&push["id"]).expect("json");
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{id},"result":{{"applied":true}}}}"#));
let done = live.wait_for(|m| m["id"] == 2);
assert!(done["result"].is_null(), "the edit is not the result any more: {done:#?}");
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn selection_ranges_round_trip_over_the_wire() {
// What only an e2e test can check: the capability is advertised, and the
// linked chain survives JSON encoding as `parent` objects rather than as
// a flattened list.
let dir = temp_dir("selection");
let file = dir.join("m.sv");
let source = "module m;\n initial begin\n x = 1;\n end\nendmodule\n";
std::fs::write(&file, source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(source).expect("json")
)),
// Two cursors: the `x` of `x = 1;`, and the `endmodule` line.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/selectionRange","params":{{"textDocument":{{"uri":"{uri}"}},"positions":[{{"line":2,"character":4}},{{"line":4,"character":0}}]}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
assert_eq!(
initialize["result"]["capabilities"]["selectionRangeProvider"],
serde_json::json!(true),
"{initialize:#?}"
);
let response = messages.iter().find(|m| m["id"] == 2).expect("selectionRange response");
let chains = response["result"].as_array().expect("one chain per position");
assert_eq!(chains.len(), 2, "{response:#?}");
// The `x`, then its statement, then the block, then the module, then the
// file — each step wider than the last, and the last one whole-file.
let mut step = &chains[0];
let mut widths = Vec::new();
loop {
widths.push((
step["range"]["start"]["line"].as_u64().expect("line"),
step["range"]["end"]["line"].as_u64().expect("line"),
));
match step.get("parent") {
Some(parent) if parent.is_object() => step = parent,
_ => break,
}
}
assert!(widths.len() >= 4, "token, statement, block, module, file: {widths:?}");
assert_eq!(widths[0], (2, 2), "the innermost step is on the cursor's own line");
assert_eq!(widths.last(), Some(&(0, 5)), "and the file closes it: {widths:?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A clean buffer with a multi-byte comment above the line the edits touch:
/// a byte-vs-UTF-16 confusion in the sync path would land them on the wrong
/// columns, and the diagnostics at the end would say so.
const SYNCABLE: &str = "// é ✓ 🎉\nmodule sync_me;\n wire a;\nendmodule\n";
#[test]
fn incremental_changes_are_advertised_and_applied_over_the_wire() {
let dir = temp_dir("incremental");
let file = dir.join("sync_me.sv");
std::fs::write(&file, SYNCABLE).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// Three ranges in one notification, each positioned against what the
// previous one left: delete the `a`, which breaks the buffer; type a `b`
// back in, which fixes it; then open a new, broken declaration below.
// A second notification finishes that declaration, badly spaced, so a
// formatting request can read the composed buffer back off the wire.
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(SYNCABLE).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{}]}}}}"#,
[
r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":8}},"text":""}"#,
r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":7}},"text":"b"}"#,
r#"{"range":{"start":{"line":3,"character":0},"end":{"line":3,"character":0}},"text":" wire ;\n"}"#,
]
.join(",")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":3}},"contentChanges":[{}]}}}}"#,
r#"{"range":{"start":{"line":3,"character":9},"end":{"line":3,"character":9}},"text":"c"}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
// 1. The capability says incremental, and says the rest explicitly.
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let sync = &initialize["result"]["capabilities"]["textDocumentSync"];
assert_eq!(sync["change"], 2, "TextDocumentSyncKind::Incremental: {initialize:#?}");
assert_eq!(sync["openClose"], true, "{sync:#?}");
assert_eq!(sync["save"]["includeText"], false, "a save re-sends nothing: {sync:#?}");
// 2. Each notification published once, and what it published describes
// the composed buffer: the error is on the line the third range
// inserted, and it clears when the fourth range finishes that line.
let published: Vec<_> =
messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect();
assert_eq!(published.len(), 3, "one per notification, not one per range: {published:#?}");
assert!(
published[0]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
"the file opened clean: {published:#?}"
);
let diagnostics = published[1]["params"]["diagnostics"].as_array().expect("an array");
assert_eq!(diagnostics.len(), 1, "{diagnostics:#?}");
assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the inserted line");
assert!(
published[2]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
"and the next range fixed it: {published:#?}"
);
// 3. And the buffer the server holds is exactly the composed text — read
// back through the formatter, which normalizes only the spacing the
// last range left behind.
assert_eq!(
new_text(&messages, 2),
"// é ✓ 🎉\nmodule sync_me;\n wire b;\n wire c;\nendmodule\n",
"the four ranges composed, and the emoji line untouched"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The client's side of a delta: splice each edit into the flat array it
/// holds, by index. Shares nothing with the server's own code.
fn apply_token_edits(previous: &[u64], answer: &serde_json::Value) -> Vec<u64> {
let mut data = previous.to_vec();
let edits = answer["edits"].as_array().unwrap_or_else(|| panic!("edits in {answer:#?}"));
for edit in edits {
let start = edit["start"].as_u64().expect("start") as usize;
let end = start + edit["deleteCount"].as_u64().expect("deleteCount") as usize;
let inserted = edit.get("data").map(token_numbers).unwrap_or_default();
data.splice(start..end, inserted);
}
data
}
/// A semantic-token `data` array as flat numbers.
fn token_numbers(value: &serde_json::Value) -> Vec<u64> {
value
.as_array()
.unwrap_or_else(|| panic!("an array of numbers, got {value:#?}"))
.iter()
.map(|n| n.as_u64().expect("a number"))
.collect()
}
#[test]
fn semantic_tokens_range_and_delta_round_trip_over_the_wire() {
// What a unit test cannot check: that both new capabilities reach the
// wire in the shape a client keys off, and that a real delta — computed
// by one process and applied by another, over the wire's flat number
// array — reconstructs the token set the next full request answers.
let dir = temp_dir("semantictokens");
let file = dir.join("m.sv");
let before = "module tokens_me;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
let after =
"module tokens_me;\n localparam W = 16;\n wire [W-1:0] a;\n // added\nendmodule\n";
std::fs::write(&file, before).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(before).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/semanticTokens/range","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":1,"character":0}},"end":{{"line":2,"character":0}}}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(after).expect("json")
)),
// The ids are minted one per answer from the start of the session, so
// the full answer above is `"1"` — asserted below, so a changed
// scheme fails loudly here rather than silently downgrading every
// delta to a full answer.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/semanticTokens/full/delta","params":{{"textDocument":{{"uri":"{uri}"}},"previousResultId":"1"}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
// 1. Both capabilities on the wire, in the shape a client reads.
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let provider = &initialize["result"]["capabilities"]["semanticTokensProvider"];
assert_eq!(provider["range"], true, "range is advertised: {provider:#?}");
assert_eq!(provider["full"]["delta"], true, "and so are deltas: {provider:#?}");
assert_eq!(
provider["legend"]["tokenTypes"].as_array().expect("the legend").len(),
14,
"the legend is unchanged: {provider:#?}"
);
// 2. The full answer is stamped, and its id is the one the delta named.
let full = messages.iter().find(|m| m["id"] == 2).expect("full response");
assert_eq!(full["result"]["resultId"], "1", "{full:#?}");
let held = token_numbers(&full["result"]["data"]);
assert!(!held.is_empty(), "{full:#?}");
// 3. The range answer stands on its own: no id, absolute first delta.
let ranged = messages.iter().find(|m| m["id"] == 3).expect("range response");
assert!(ranged["result"].get("resultId").is_none(), "nothing to name: {ranged:#?}");
let window = token_numbers(&ranged["result"]["data"]);
assert_eq!(window[0], 1, "deltaLine is absolute from the file start: {ranged:#?}");
assert!(window.len() < held.len(), "and it is only part of the file: {ranged:#?}");
// 4. The delta reconstructs exactly what the next full request answers.
let delta = messages.iter().find(|m| m["id"] == 4).expect("delta response");
assert!(delta["result"].get("edits").is_some(), "a known id gets edits: {delta:#?}");
let truth = messages.iter().find(|m| m["id"] == 5).expect("second full response");
assert_eq!(
apply_token_edits(&held, &delta["result"]),
token_numbers(&truth["result"]["data"]),
"applying the edits must land on the new token set exactly"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn indexing_reports_its_progress_over_the_wire() {
// What only an e2e test can check: the create request and the two
// `$/progress` notifications are framed, ordered, and carry the same
// token — for a client that advertised `window.workDoneProgress`.
let dir = temp_dir("progress");
let file = dir.join("m.sv");
let source = "module m;\nendmodule\n";
std::fs::write(&file, source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(source).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
// Every progress message on the wire, in order, as (step, token).
let steps: Vec<(String, String)> = messages
.iter()
.filter_map(|m| match m["method"].as_str() {
Some("window/workDoneProgress/create") => Some((
"create".to_string(),
m["params"]["token"].as_str().expect("a string token").to_string(),
)),
Some("$/progress") => Some((
m["params"]["value"]["kind"].as_str().expect("a kind").to_string(),
m["params"]["token"].as_str().expect("a string token").to_string(),
)),
_ => None,
})
.collect();
// Two rescans: the startup build, then the save. Each one create, one
// begin, one end, on its own token.
assert_eq!(
steps,
vec![
("create".to_string(), "lucisv-index-0".to_string()),
("begin".to_string(), "lucisv-index-0".to_string()),
("end".to_string(), "lucisv-index-0".to_string()),
("create".to_string(), "lucisv-index-1".to_string()),
("begin".to_string(), "lucisv-index-1".to_string()),
("end".to_string(), "lucisv-index-1".to_string()),
],
"{messages:#?}"
);
// The begin says what it is doing, and offers no cancel button — a rescan
// that has started runs to completion, whatever `$/cancelRequest` can do
// for the requests still queued.
let begin = messages.iter().find(|m| m["params"]["value"]["kind"] == "begin").expect("a begin");
assert_eq!(begin["params"]["value"]["title"], "Indexing Verilog workspace", "{begin:#?}");
assert_eq!(begin["params"]["value"]["cancellable"], false, "{begin:#?}");
assert!(begin["params"]["value"].get("percentage").is_none(), "no fake numbers: {begin:#?}");
let end = messages.iter().find(|m| m["params"]["value"]["kind"] == "end").expect("an end");
assert_eq!(end["params"]["value"]["message"], "1 file indexed", "{end:#?}");
// The create is a request the client may answer or error; leaving it
// unanswered here is exactly what a client that does not care does, and
// the session still shuts down cleanly (asserted inside `talk`).
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() {
let dir = temp_dir("noprogress");
let file = dir.join("m.sv");
let source = "module m;\nendmodule\n";
std::fs::write(&file, source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(source).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
assert!(
messages.iter().all(|m| {
m["method"] != "$/progress" && m["method"] != "window/workDoneProgress/create"
}),
"the spec forbids progress a client never asked for: {messages:#?}"
);
// And it still got its diagnostics, so the save path ran.
assert!(
messages.iter().any(|m| m["method"] == "textDocument/publishDiagnostics"),
"{messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The ids the flood cancels — every second request.
fn is_cancelled(id: u32) -> bool {
id % 2 == 1
}
#[test]
fn a_flood_of_requests_and_cancels_is_answered_exactly_once_each() {
// The one test that runs the real `run()` loop, and so the only one that
// exercises the burst drain over a real pipe. The whole session is written
// in a single `write` before a byte is read back, so every request and the
// cancel behind it are in flight together — which is the only situation a
// one-message-at-a-time server can honour a cancel in at all.
//
// **How many get cancelled is not asserted, and cannot be.** Whether a
// cancel reaches the loop in the same burst as its request is a race with
// the transport's own threads, and the spec's answer to losing it is to
// answer the request normally. So this pins what must hold either way —
// one answer per request, never a wrong one — plus the fact that the
// cancellation path does work over the wire. Twenty formatting requests
// over a three-hundred-line buffer is enough work per message that the
// backlog is real: under a twenty-four-way overload the worst observed
// was two in five honoured, never none.
let dir = temp_dir("cancelflood");
let file = dir.join("m.sv");
let source: String = std::iter::once("module flooded;\n".to_string())
.chain((0..300).map(|i| format!("wire w{i};\n")))
.chain(std::iter::once("endmodule\n".to_string()))
.collect();
std::fs::write(&file, &source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let mut session = vec![
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&source).expect("json")
)),
];
for id in 10..30u32 {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)));
if is_cancelled(id) {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","method":"$/cancelRequest","params":{{"id":{id}}}}}"#
)));
}
}
// A cancel for a request this server was never sent. It names nothing in
// any burst, so it is dropped where it is read.
session.push(frame(r#"{"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":999}}"#));
session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#));
session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#));
let messages = talk(&session.concat());
let mut honoured = 0;
for id in 10..30u32 {
let answers: Vec<&serde_json::Value> = messages.iter().filter(|m| m["id"] == id).collect();
assert_eq!(answers.len(), 1, "id {id} was answered exactly once: {messages:#?}");
let answer = answers[0];
if answer.get("error").is_some() {
assert!(is_cancelled(id), "id {id} was never cancelled: {answer:#?}");
assert_eq!(answer["error"]["code"], -32800, "cancelled, not failed: {answer:#?}");
assert!(answer.get("result").is_none(), "an error carries no result: {answer:#?}");
assert!(
answer["error"]["message"].as_str().is_some_and(|m| !m.is_empty()),
"a cancelled response carries a message: {answer:#?}"
);
honoured += 1;
} else {
// Answered for real: the whole buffer, indented.
let edits = answer["result"].as_array().expect("an array of edits");
assert_eq!(edits.len(), 1, "one whole-document edit: {answer:#?}");
assert!(
edits[0]["newText"]
.as_str()
.expect("newText")
.starts_with("module flooded;\n wire w0;\n"),
"id {id} was formatted: {answer:#?}"
);
}
}
assert!(honoured > 0, "the cancellation path runs over the wire: {messages:#?}");
// The shutdown came through the same flood and was still honoured —
// `talk` asserts the process then exited cleanly.
let shutdown = messages.iter().find(|m| m["id"] == 9).expect("a shutdown response");
assert!(shutdown.get("error").is_none(), "shutdown succeeded: {shutdown:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
+3 -1
View File
@@ -8,7 +8,9 @@ pub enum Doc {
/// Verbatim text. Must not contain newlines (use `HardLine`).
Text(String),
/// Verbatim text spliced into the *middle* of a line, newlines and all:
/// the `{ ... }` of a `randomize() with { ... }` constraint block. It
/// the `{ ... }` of a `randomize() with { ... }` constraint block, the
/// `#( ... )` of a parameterized type reference, or raw text that
/// carries a string literal across a line break. It
/// carries its own indentation, so the printer copies it through
/// untouched and resumes measuring from its last line. Unlike
/// [`Doc::Verbatim`] it does not force enclosing groups to break — the
+10 -6
View File
@@ -219,12 +219,14 @@ impl<'a> Fmt<'a> {
/// A token that carries a string literal across a line break is emitted
/// completely untouched instead: the leading whitespace of such a
/// continuation line is part of the string's *value*, and re-indenting it
/// would rewrite the string. Emitting the text as a single `Doc::Text`
/// means the printer copies the newlines through without adding indent,
/// so nothing changes and the result is a fixed point by construction.
/// would rewrite the string. Emitting the text as a `Doc::Inline` means
/// the printer copies the newlines through without adding indent — so
/// nothing changes and the result is a fixed point by construction —
/// while its column tracking resumes from the text's own last line
/// (`Doc::Text` must not contain newlines).
fn raw_text(&self, raw: &RawText) -> Doc {
if crosses_line_inside_string(&raw.text) {
return text(raw.text.clone());
return Doc::Inline(raw.text.clone());
}
self.raw_lines(&raw.text, raw.col)
}
@@ -236,9 +238,11 @@ impl<'a> Fmt<'a> {
/// `raw_lines`'s dedent-by-column only reaches a fixed point when the text
/// begins its own line — the dedent has to cancel the indent the printer
/// adds back — and this text never does, so re-indenting it would drift.
/// Emitting it unchanged is idempotent by construction.
/// Emitting it unchanged is idempotent by construction. `Doc::Inline`
/// rather than `Doc::Text` so a multi-line `#( ... )` keeps the printer's
/// column honest (`Doc::Text` must not contain newlines).
fn raw_inline(&self, raw: &RawText) -> Doc {
text(raw.text.clone())
Doc::Inline(raw.text.clone())
}
/// The `{ ... }` of a `randomize() with { ... }`: verbatim source spliced
+16
View File
@@ -254,6 +254,22 @@ mod tests {
);
}
/// After a multi-line `Inline` is *printed*, `col` is the width of its
/// last line — so a group that follows it on that line is measured from
/// there, not from an accumulated character count. Raw text that carries
/// a string literal across a line break rides this arm; when it was
/// emitted as `Doc::Text` (whose printer arm never resets `col` on the
/// embedded newlines it is not supposed to contain), the stale column
/// forced every later fit check on the line into a conservative break.
#[test]
fn a_group_after_a_multi_line_inline_measures_from_its_last_line() {
let d = concat(vec![
Doc::Inline("x = \"aaaaaaaaaaaaaaaaaaaaaaaa\nbbb\" ".into()),
group(vec![text("+"), indent(vec![Doc::Line, text("yyyy")]), text(";")]),
]);
assert_eq!(p(20, d), "x = \"aaaaaaaaaaaaaaaaaaaaaaaa\nbbb\" + yyyy;");
}
#[test]
fn hard_line_forces_break() {
let d = group(vec![text("a"), Doc::HardLine, text("b")]);
@@ -560,3 +560,16 @@ class c;
g = 1;
endfunction
endclass
====
# the printer's column stays honest after a multi-line #( ... ): the
# initializer is measured from the raw text's last line, not from an
# accumulated count, so a call that fits the real line stays on it
class c;
uvm_analysis_port #(bit [31:0],
foo_t) p = new("a_fairly_long_component_name", some_parent_handle, extra_argument);
endclass
----
class c;
uvm_analysis_port #(bit [31:0],
foo_t) p = new("a_fairly_long_component_name", some_parent_handle, extra_argument);
endclass
+215
View File
@@ -0,0 +1,215 @@
# apply-edit
## Goal
Make the three port commands actually edit something in a stock editor.
`workspace/executeCommand` used to answer with the `WorkspaceEdit` that
`ports::execute` computed, as the request's *result*. The protocol defines no
such thing: an `executeCommand` result is `any | null`, and a client applies
what a server **pushes** at it with `workspace/applyEdit`.
`vscode-languageclient` (which `editors/vscode/extension.js` uses unmodified)
drops the result on the floor, and so does Neovim's built-in client — so
`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked *as
commands* did nothing at all in every stock client. (The code-action path was
never affected: a code action carries its edit inline.) This round pushes the
edit, answers `null`, and reads the one client response the server can no
longer ignore.
## Assumptions
- **`workspace.applyEdit` is the gate.** A client that advertised it gets the
push and a `null` result. A client that did not gets exactly the old
behavior — the edit as the result — because for that one it is the only
thing that could ever work, and a silent no-op is worse than a
non-standard answer that some caller may yet read. Both VS Code and Neovim
advertise it; `editors/vscode/smoke.js` sends `capabilities: {}` and so
takes the fallback, which is why it still passes untouched.
- **The push goes out before the command's own response.** The loop sends a
request's response when the handler returns, and the handler sends the
`applyEdit` request during it. The protocol allows a server to make a
request at any time, and a client that waited for the command result before
applying the edit would deadlock against any server that does this — VS
Code and Neovim both apply immediately. Stated here because it is the
ordering a reader would otherwise wonder about.
- **A refusal is worth a popup.** `ApplyWorkspaceEditResponse.applied: false`
means the user ran a command, watched nothing happen, and has no other way
to find out why. It is shown as an ERROR naming the command, plus the
client's own `failureReason` when it sent one. Success says nothing.
- **A response that does not parse is a refusal.** Nothing was seen to be
applied, so the honest thing is to say so rather than assume the best.
- **Watcher (un)registration answers stay ignored.** Their ids are never in
the pending map, so they fall straight through the new handler — including
an error response, which is what a client that refuses to watch sends. The
behavior `docs/features/file-watching/README.md` documents is unchanged.
- **No retry, no timeout.** A client that never answers leaves one entry in
the pending map for the life of the session; three port commands per
session is not a leak worth a timer, and the server has no timers by
design.
- **The `report_scope(warnings)` behavior is unchanged** — the engine's
warnings are still surfaced exactly as before, whichever delivery path the
edit takes.
## Handshakes
### `lucisv_server::server`
- `ClientAbilities` gains `apply_edit: bool` and derives `Default`, so a test
can name only the ability it cares about. `main.rs` fills it from
`InitializeParams.capabilities.workspace.apply_edit`.
- `Server` gains `applying: HashMap<RequestId, String>` — the outstanding
`workspace/applyEdit` requests, each remembering the command that asked.
- `Server::send_request` now **returns** the `RequestId` it sent on. The
watcher registration ignores it, exactly as it ignores the answer.
- `run`'s `Message::Response(_) => {}` becomes `self.response(response)`.
- `ExecuteCommand` goes through the new `Server::deliver`.
### `ports`
`ports::execute`'s signature is unchanged; only the doc comment's claim that
"the server does not push `workspace/applyEdit`" is now false, and is
rewritten. No engine behavior changed.
### `editors/vscode`
**No extension change.** `vscode-languageclient` applies `workspace/applyEdit`
requests itself; `extension.js` has no custom `executeCommand` handling and
needs none. Verified by reading, not assumed.
## Status / TODO
- [x] `workspace.applyEdit` read into `ClientAbilities` at initialize
- [x] `Server::deliver`: push the edit with a `label`, answer `null`
- [x] `Server::response`: match answers to outstanding requests, report a
refusal as an ERROR naming the command
- [x] Return-the-edit fallback kept for a client that cannot apply
- [x] Tests: pushed-and-null, fallback-returns-the-edit, refusal reported,
success silent, duplicate/unknown answer ignored, watcher answer still
ignored
- [ ] Not done, deliberately: no `$/progress` or timeout on an unanswered
`applyEdit` — see Assumptions.
- [ ] Not done, deliberately: `WorkspaceEdit` still carries plain `changes`
(no `documentChanges`, no snippet edits). That is TODO §9c's item, and
it would improve `addPort` cursor placement.
## Work log
### 2026-08-26 — dev agent, §9a
- **`deliver` is a method on `Server`, not a free function**, because it has
to both send a request and remember its id; splitting it would have meant
returning a request for the caller to send, which is a shape with one user.
- **`send_request` returning the id** was the smallest change that let the
applyEdit path record it. The two watcher call sites ignore the value; a
`RequestId` is not `#[must_use]`, so this stays silent.
- **The pending map is keyed by `RequestId`, not by command**, so two
commands in flight cannot be confused and a duplicate answer to a spent id
does nothing. Pinned by
`an_edit_the_editor_applied_is_said_nothing_about`'s second half.
- **The `label`** is `lucisv: <command>` — it is what an editor shows on its
undo stack, so it names the thing the user would want to undo.
- Files touched: `crates/lucisv_server/src/server.rs`,
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`, and
`ports.rs`'s stale doc comment (it claimed the server does not push
`workspace/applyEdit`). `editors/vscode/extension.js` was read and
deliberately left alone.
**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings),
`cargo test --workspace`, `node editors/vscode/smoke.js` — all clean. 5 new
unit tests in `server.rs` (plus the watcher-answer guard), 1 in `main.rs`, and
one e2e session (`a_command_pushes_its_edit_to_a_client_that_can_apply_one`)
that pushes the edit at a real binary and answers it as an editor would.
## 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, forced a rebuild by
touching the changed files first so the check was not answered from a stale
cache), `cargo test --workspace` (3 full runs, no failures), `node
editors/vscode/smoke.js target/debug/lucisv-server` (exit 0) — all reproduced
independently.
**Read the diff against the README's claims,** file:line references against
the working tree as it stood before this QA pass:
- `server.rs`'s `ExecuteCommand` handler (around what is now line 304) calls
`self.report_scope(warnings)` unconditionally in the `Ok` arm, before
`self.deliver(...)` branches on the ability — confirmed **both** the push
and the fallback path surface engine warnings identically.
- **RequestId collision, checked and ruled out.** `applying` and the watcher
(un)registration ids are both minted by the same `send_request`, whose
counter (`self.request_ids`) is a single monotonically increasing `u32`
shared across every call site — two ids can never collide, so a watcher
answer can never land in `applying` and vice versa. This is structural,
not incidental: there is exactly one counter to break for a collision to
become possible.
- `ports.rs`'s doc comment rewrite matches the new behavior; no engine
behavior changed there, confirmed by reading `execute`'s body (untouched
except the comment).
**Attacked the response-routing path** (`server.rs::response`, the
`ApplyWorkspaceEditResponse` deserialization). The existing tests covered
`Ok(applied: true)`, `Ok(applied: false, failureReason)`, a duplicate answer,
and a watcher answer — but not the two cases the doc comment explicitly
claims to handle: a response payload that is `Ok` JSON but does not
deserialize as `ApplyWorkspaceEditResponse` at all, and a JSON-RPC-level
`Err` response (a client that rejects the request outright rather than
answering it). Added both as tests in `server.rs`:
- `a_malformed_apply_edit_answer_is_reported_as_a_refusal` — answers with
`{"notApplied": "whatever"}` (no `applied` field, which is required with no
default in `lsp_types::ApplyWorkspaceEditResponse`); asserts one ERROR
naming the command, not a panic and not silence.
- `a_response_with_a_jsonrpc_error_is_reported_too` — uses
`Response::new_err` directly; asserts the `error.message` reaches the
shown text.
Both pass. Confirms the "a response that does not parse is a refusal"
assumption is real code, not just a comment.
**Found and fixed one self-inflicted test bug while adding the above:** the
first draft of `a_malformed_apply_edit_answer_is_reported_as_a_refusal` named
its tree `propagating("malformed", ...)`, which collides with the *existing*
`Tree::new("malformed")` in
`a_malformed_watched_files_notification_is_dropped` — both resolve to the
same `std::env::temp_dir()` path (keyed only by pid + name), so running the
suite in parallel raced the two tests' filesystem setup and made
`ports::execute` fail to find `sub.sv` (`server.rs`, originally around line
1417 in this session's numbering). Not a server bug — a QA-test-authoring
bug. Renamed to `"malformedapplyedit"`; reran the full `lucisv_server` suite
three times back to back with no failures. Worth a general note for future
dev/QA agents: `Tree::new`'s temp path is name-keyed, not test-keyed, so a
tree name must be checked for uniqueness across the whole crate, not just
the tests being added.
**Capability reading:** `apply_edit_support` reads
`params.capabilities.workspace.as_ref().and_then(|w| w.apply_edit)` —
verified this cannot panic on `InitializeParams::default()` or any partial
capability object; already covered by
`apply_edit_support_is_read_from_the_clients_own_capabilities`, re-ran it
directly.
**CLAUDE.md compliance:** grepped the new/changed lines in `server.rs`,
`main.rs`, `ports.rs` for `.unwrap()`, `.expect()`, `panic!` outside
`#[cfg(test)]` — none found. Public items added (`ClientAbilities::apply_edit`)
carry doc comments. README has all seven required sections; TODO.md's
checkbox is checked with the item text unchanged and a `→` pointer added.
**Verdict: no blocking findings.** The two new attack tests and the
tree-name-collision fix are the only changes made to this feature's code.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full
workspace suite/smoke.js myself, all clean. The design is right: the gate is
the client's own `workspace.apply_edit` capability, the fallback is exactly
the old behavior for exactly the clients the old behavior could serve, and
the pending-map keyed by the one shared id counter makes response routing
collision-free by construction (QA verified the same). The `deliver`
doc comment's deadlock note is a good catch worth keeping. The no-timeout
decision is accepted: three commands per session cannot leak meaningfully,
and the server has no timers by design. `ports.rs`'s previously-false doc
comment is now true. Accepted as shipped.
+533
View File
@@ -0,0 +1,533 @@
# cancel-request
## Goal
`$/cancelRequest` is the client's way of saying "drop that one, the user has
moved on" — sent constantly by real editors, which cancel the completion,
hover and inlay-hint requests of the previous keystroke on every new one.
Until now the notification fell through `Server::notification`'s `_ => {}` arm
and the request was computed and answered anyway. This round answers a
cancelled request with the protocol's own `RequestCancelled` (-32800) instead
of computing it, whenever the cancel reaches the loop in time — which, on a
single-threaded server, means *while the request is still queued*. The gain is
not correctness (an ignored cancel is legal) but work not done: on a slow
rescan or a large-file format, the queue behind the busy handler is exactly
where a stale completion request sits, and answering it costs nothing (TODO.md
§9b, the last item of that section).
## What "in time" can mean on a one-message-at-a-time loop
Everything about this feature follows from one fact: **the client sends the
request and its cancel down one ordered channel**, and the server handles one
message at a time. Read strictly one message per iteration, a cancel is always
too late — by the time `C(R)` is dequeued, `R` was dequeued, computed and
answered an iteration ago. Cancellation only becomes reachable when the loop
looks at *more than one message at a time*: while a handler runs, the client
keeps sending, so the backlog waiting behind it can hold `[R1, C(R1), R2]` —
and R1 can be answered `RequestCancelled` for free.
So `run()` now works in bursts:
1. block for the next message, as before;
2. take everything already queued behind it, without blocking, into one FIFO
(the blocked-for message first);
3. scan that whole burst for `$/cancelRequest` notifications and collect the
ids that name a request **in the same burst**;
4. handle the burst strictly in arrival order — a cancelled request answered
`RequestCancelled` without dispatch, every other message exactly as before.
Step 3 is what keeps the cancelled set from being state: it is built per burst
and dropped with it.
### The transport does not queue — so we do
The first attempt used `connection.receiver.try_recv()` for step 2 and
cancelled **nothing** over a real pipe. The reason is worth writing down,
because it is invisible from the API:
> `lsp-server` 0.10's stdio transport wires its reader, writer and dropper
> threads with **`crossbeam_channel::bounded(0)`** — rendezvous channels with
> no capacity at all (`stdio.rs`). Its reader thread parks *inside* `send`
> holding one message until the loop takes it. A client's backlog therefore
> never sits on `connection.receiver`: it sits in the OS pipe, one message
> deep from where we stand, and `try_recv` right after a `recv` loses a
> microsecond-scale race with the reader thread essentially every time.
`Server::queue()` fixes this with the smallest thing that can: one forwarder
thread that blocks on `connection.receiver` and pushes onto an unbounded
`std::sync::mpsc` queue that `run()` owns. The backlog then accumulates where
we can see it, and step 2 is a plain `try_recv` loop. The thread touches no
server state, moves messages and nothing else, and is std-only — no new
dependency.
The forwarder **stops at the `shutdown` request and never reads past it**.
`Connection::handle_shutdown` answers the request and then reads the `exit`
notification off the *connection* itself; a forwarder that kept going would
take that `exit` first, and `handle_shutdown` would block for its full
thirty-second timeout and then return a protocol error. Stopping there also
means nothing after a shutdown is ever queued, which is exactly the protocol's
own rule.
## Assumptions
- **Cancellation is best-effort, and the spec says so.** LSP allows a server
to ignore a cancel it cannot honour; the only hard requirement is that every
request gets exactly one response. Both are held here: a cancel that misses
its window leaves the request answered normally.
- **A cancel arriving in a *later* burst than its request is dropped.** By
then the request has been answered — there is nothing left to cancel, and
remembering the id would be a set that grows for the life of the session.
This is the single rule that keeps this feature stateless.
- **A cancel in the same burst but dequeued *before* its request still
cancels it.** The burst is scanned as a whole before any of it runs, so
ordering within the burst does not matter. (A real client never sends the
cancel first; a transport is free to make it look that way.)
- **A cancel for a request the server never received is dropped** where it is
read, for the same reason.
- **Cancelling one request twice is harmless.** The id is removed from the
cancelled set as it is used, so a second cancel finds nothing — and it could
not touch a later request even if ids were reused, because the set never
outlives its burst.
- **`shutdown` is never cancellable.** `handle_shutdown` runs before the
cancelled set is consulted, so a cancel naming the shutdown id cannot stop
the server from shutting down. The spec's "a server should still answer a
cancelled request" reading is the safe one here: a client that cannot shut
its server down leaks a process.
- **Notifications are never cancelled.** They carry no id and get no
response; `$/cancelRequest` names request ids only. A `didChange` queued
ahead of a cancelled request is still applied — the state a *later* request
is answered against must not depend on which requests were dropped.
- **Order inside a burst is the invariant, not an implementation detail.**
A `didChange` the client sent before a completion request must be in effect
when that completion is answered, exactly as it would be one message at a
time. Pinned by
`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`.
- **Both id forms are read.** `CancelParams.id` is
`NumberOrString`; a numeric id becomes `RequestId::from(i32)` and a string
id `RequestId::from(String)`. The string `"8"` is not the number `8` —
`RequestId` keeps them apart and so does the cancel, which is the only
behaviour that can be right when a client uses both forms.
- **A cancel whose params do not parse is dropped**, on the same reasoning as
every other malformed notification: there is no id to act on and no id to
answer on.
- **The cancelled response carries a message.** `-32800` plus
`"lucisv: request cancelled by the client"`. Clients do not show it — the
code is what they read — but a log with the text in it is easier to read
than a log with a number in it.
- **Nothing already *running* is cancelled.** There is one thread; a format,
a rescan or a rename that has started runs to completion. The work-done
progress bar still advertises `cancellable: false`, which stays true.
- **The queue is unbounded.** Backpressure on the pipe used to be the reader
thread's rendezvous; now a burst is buffered in memory instead. For an LSP
client that is bounded by what an editor sends between two of our handler
calls — kilobytes. A client that floods a server faster than it can read
would grow this queue, and would equally have grown the pipe before.
## Handshakes
### `lucisv_server::server` (this feature's own module)
- `Server::run` no longer receives-and-dispatches inline. It builds the queue,
blocks on it, and hands each burst to `process_batch`. Behaviour for a
client that never cancels is identical, message for message.
- **New private items:** `Server::queue()` (the forwarder),
`Server::process_batch(Vec<Message>) -> Result<bool, …>` (the burst
handler; `true` means the client shut us down), and the free functions
`burst`, `is_shutdown`, `cancelled_in`, `cancelled_id`, `cancelled_response`.
- `Server::request`, `Server::notification` and `Server::response` are
**unchanged**. `$/cancelRequest` never reaches `notification()`; it is
consumed in the burst handler, which is the only place that can act on one.
- No field was added to `Server`. Cancellation state lives for the length of
one burst and no longer.
### `lsp-server`
- Consumed, not changed: `Connection.receiver` is now `clone()`d (crossbeam
receivers are `Clone`), and `handle_shutdown` is called exactly where it was
— the forwarder's stop rule is what keeps its `exit` read working.
- The rendezvous-channel finding above is a property of version `=0.10.0`,
which the workspace pins. A future bump should re-read `stdio.rs`: if the
transport ever queues, `Server::queue` becomes redundant rather than wrong.
### Every other crate, and `editors/vscode`
**Untouched.** No engine crate knows this happened, and no client capability
gates it — `$/cancelRequest` is unconditional in the protocol, advertised by
nobody and sent by everybody. `smoke.js` passes unchanged (run as a gate).
## Status / TODO
- [x] `run()` restructured into blocking receive → burst drain → burst handler
- [x] Forwarder thread so the backlog is observable at all (the rendezvous
finding), stopping at `shutdown` so `handle_shutdown` keeps its `exit`
- [x] Cancelled ids collected per burst, matched against that burst's own
requests, dropped otherwise
- [x] Cancelled requests answered `-32800` without dispatch; the cancels
themselves consumed
- [x] `shutdown` honoured before any cancel is consulted
- [x] Arrival order preserved across the whole burst (notifications included)
- [x] Numeric and string cancel ids; malformed cancels dropped
- [x] Tests: 10 unit in `server.rs` (through the `Session` harness, driving
the real `process_batch`), 1 e2e over the wire
- [x] TODO.md §9b checkbox; loop description in
`docs/features/lucisv-server/README.md`
- [ ] **Not done, deliberately:** no cancellation of work in flight. That
needs a worker pool and cancellation tokens threaded through the engine
— TODO.md §6's explicit non-goal for as long as per-file recompute stays
in the millisecond range.
- [ ] **Not done, deliberately:** no `ContentModified` (-32801) for requests
invalidated by a `didChange` queued behind them. It is the neighbouring
idea and a real option now that the loop can see a burst, but the spec
warns that an answer computed against slightly older text is usually
still useful — and the client, not the server, is the one that knows.
Filed here, not built.
## Work log
### 2026-08-26 — dev agent (§9b, `$/cancelRequest`)
- Read `CLAUDE.md`, `docs/features/lucisv-server/README.md`, TODO.md §9b and
the whole of `server.rs`'s loop before touching anything.
- **Verified the lead's design against the code, and found one thing that
invalidated its second step.** The plan said to drain `connection.receiver`
non-blockingly with `try_iter`/`try_recv`. Written that way, the e2e flood
cancelled **zero** of five requests, reproducibly. `lsp-server` 0.10's
`stdio.rs` uses `bounded(0)` rendezvous channels throughout: there is no
queue on that receiver to drain, ever. The rest of the design — burst FIFO,
batch-wide cancel scan, drop-if-not-in-batch, order preserved, shutdown
never cancellable — is unchanged and implemented as written.
- **Fix: one forwarder thread** (`Server::queue`) onto a `std::sync::mpsc`
queue, so the backlog accumulates somewhere observable. Std-only, no new
dependency, no shared state, ~12 lines. Considered and rejected: a timed
drain window (`recv_timeout(1ms)`), which would tax *every* message with a
millisecond of latency and still be a race; and handling shutdown ourselves
to free the forwarder, which would duplicate `handle_shutdown`'s protocol
for no gain.
- **The forwarder's stop-at-shutdown rule was found by reading
`handle_shutdown`, not by a failing test**: it reads `exit` off the
connection itself, so an eager forwarder would have stolen it and turned
every shutdown into a 30-second timeout followed by a protocol error. The
rule is asserted by `a_shutdown_is_honoured_however_it_is_cancelled` and by
the e2e session, which shuts down through the same flood.
- Tests: 10 unit tests in `server.rs`, driving the real `process_batch`
through a new `Session::batch` helper (the harness otherwise bypasses the
loop entirely), plus `Session::answers()` for reading responses off the
client end. One e2e test running the real binary and the real `run()`.
- **The e2e test asserts what is deterministic, and says why.** Three
iterations were needed to get there: with cheap requests, *how many* cancels
land in the same burst as their request is a scheduling race, and demanding
all five failed roughly one full-suite run in four (the suite runs 38
server processes in parallel). The final shape floods twenty
`textDocument/formatting` requests over a 300-line buffer — enough work per
message that the forwarder is never starved — and asserts the properties
that must hold on any schedule: exactly one response per request, `-32800`
only ever on an id the client actually cancelled, a correct formatted answer
on every other id, at least one honoured cancel (the wire path works), and
a clean shutdown. Measured under a deliberate 24-way overload: worst case
two of five honoured, never zero.
- Also corrected two now-stale comments about cancellation being absent
entirely — the module header of `server.rs`, `begin_indexing`'s note on
`cancellable: false`, and the matching line in the progress e2e test. The
bar's `false` stays correct: what has *started* still runs to completion.
- Gates, all clean: `cargo fmt --all -- --check`, `cargo clippy --all-targets`
(no warnings), `cargo test --workspace` (34 suites green; `lucisv_server`
702 unit + 38 e2e), `cargo build && node editors/vscode/smoke.js
target/debug/lucisv-server` → OK. The e2e suite was re-run ten consecutive
times looking for flake: ten passes.
## QA log
### 2026-08-26 — QA agent (§9b, `$/cancelRequest`)
**Verdict: committable as-is.** No corruption, no protocol violation, no
reproducible flake found. Four gaps in test coverage for the highest-risk
part of the change (the forwarder thread) were found and closed directly;
one theoretical (not reproduced) flake risk in the e2e flood is recorded
below with a reasoned trade-off, not "fixed," because the fixes available
would weaken the property the test exists to prove.
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets`
clean, no warnings. `cargo test --workspace`: every suite green, including
`lucisv_server` at 706 unit (was 702 pre-QA; +4 added below) + 38 e2e.
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` →
OK. `cargo test -p lucisv_server --test e2e` run five more times standalone,
before the QA-added tests and five more times after: **10/10 green**, no
flake observed in the flood test or anywhere else in the suite.
**1. Forwarder shutdown hand-off — verified clean, by reading
`lsp-server` 0.10's actual source, not the dev's summary.**
- Read `~/.cargo/registry/.../lsp-server-0.10.0/src/stdio.rs`,
`src/lib.rs` (`Connection::handle_shutdown`, `Connection::memory`) and
`src/msg.rs` (`Request::is_shutdown`, `Notification::is_exit`,
`Response`'s `#[serde(flatten)]` encoding). Confirms the README's claim:
the stdio reader thread parks inside a `bounded(0)` `send` until taken,
so a client's backlog really does live in the OS pipe and not on
`connection.receiver`.
- (a) **Method-name detection, and the notification case.** `is_shutdown`
(`crates/lucisv_server/src/server.rs:1119`) matches
`Message::Request { method == "shutdown" }` only — the same test
`lsp-server`'s own `Request::is_shutdown` (msg.rs:233) uses. A
**notification** shaped like `{"method":"shutdown"}` fails the match
(wrong enum variant), so the forwarder does not stop for it; it is
forwarded like any other message and falls through `notification()`'s
`_ => {}` arm, doing nothing. This was asserted by nothing before QA —
added `is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`
(server.rs:3574). A malformed shutdown-*request* (e.g. non-null params)
is not a distinct case: neither `is_shutdown` nor `handle_shutdown`
parses params, only the method name, so there is nothing to be
malformed.
- (b) **The stolen-message / deadlock window.** Traced the forwarder
(`Server::queue`, server.rs:209-233): it checks `is_shutdown` on the
message **after** receiving it but **before** issuing its next `recv()`,
and breaks its loop without calling `recv()` again when that check is
true. `handle_shutdown` (lsp-server lib.rs:348) is only reached by
`process_batch` for a request already sitting in the batch Vec — i.e.
after the forwarder that produced it has already returned from its last
`sender.send`. Because the forwarder's own break happens strictly before
any further receive, there is no window where both the forwarder and
`handle_shutdown` are calling `recv`/`recv_timeout` on the same
crossbeam channel at once — no steal, no deadlock. Added
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`
(server.rs:3632), which sends a real shutdown request + exit notification
through a `Connection::memory()` pair, calls the real `Server::queue()`,
and asserts (i) the shutdown is the last thing the forwarder ever
forwards even after 50ms of extra opportunity to misbehave, and (ii) the
`exit` is still sitting, unread, directly on `connection.receiver` —
exactly where `handle_shutdown` looks for it. This is the one test in
the whole suite that exercises the real `queue()` method without going
through a subprocess.
- (c) **Messages already forwarded ahead of a shutdown in the same
batch.** Because the forwarder always stops immediately after
forwarding the message it detects as shutdown, shutdown is provably
always the *last* message that forwarder instance ever produces — there
is no way for a message to be forwarded *after* shutdown by the same
producer, and there is only ever one producer (next point). So the
scenario "a request forwarded after shutdown gets silently dropped" is
not reachable through this code path. Nothing found here; the design
note in the feature README (lines 63-69) undersells this a little by
only mentioning the *thirty-second timeout* consequence of an eager
forwarder — the actual structural guarantee (shutdown is always last)
is worth knowing but the doc isn't wrong, just less complete than it
could be. Not fixed (doc-only, not a code finding, and rewriting
someone else's README section is not QA's job per CLAUDE.md).
**2. Message loss/reordering — verified clean.**
- Exactly one producer: `Server::queue` is called exactly once, from
`Server::run` (server.rs:185), which is itself called exactly once, from
`main.rs:76`. No respawn path exists.
- Single channel used throughout: `run`'s blocking head-of-burst read and
`burst`'s non-blocking drain (server.rs:1126) both operate on the same
`std::sync::mpsc::Receiver` returned by `queue()` — never a mix of the
mpsc and `connection.receiver` on the consuming side. (`connection.receiver`
itself is only ever touched by the forwarder's `source` handle and by
`handle_shutdown`, never by `run`/`burst`/`process_batch`.)
- Exactly-once processing: `burst` pushes the blocking-received `first`
plus everything `try_recv` drains, with no filtering or dedup step in
between — the FIFO in equals the FIFO out. Added
`burst_collects_everything_already_queued_in_arrival_order`
(server.rs:3602) directly against a fresh
`std::sync::mpsc` channel (no `Server` involved), pinning arrival order
for `[first, second, third]`. Previously `burst` had zero direct test
coverage — every existing cancel test drives `process_batch` through
`Session::batch`, bypassing `burst` entirely, so this was a real gap in
a change the assignment calls "the highest-risk this repo's server has
taken."
**3. `exit` handling / zombie-thread check — verified clean.**
- `talk()` (e2e.rs:66-79) and the progress-e2e session's own `finish()`
(e2e.rs:1978-1985) both call `child.wait()` and assert
`status.success()` — a hung forwarder or a process that doesn't
terminate would hang or fail these, and none did across 10 e2e runs.
This is a real check, not a rubber stamp: `child.wait()` blocks until
the OS reports the process gone, so a genuinely undead forwarder thread
(blocked on stdin, holding the process open) would show up as a test
timeout, not a silent pass.
- The forwarder thread is detached (`let _ = ... .spawn(...)`), never
joined. This is fine for process exit: after `shutdown`+`exit`, the
forwarder has *already* stopped itself (point 1b) well before `run()`
returns, so by the time `main()` returns there is no thread left
blocked on I/O that could hold the process open. In the one edge case
where a client disconnects without ever sending `shutdown` (broken
pipe), the forwarder's own `source.recv()` errors, it drops its `sender`
and exits, closing the mpsc and unblocking `run()`'s own `recv()` the
same way `self.connection.receiver.recv()` used to unblock pre-diff —
behaviorally identical to the old direct-receive loop for that case.
Not a new finding; equivalent to prior behavior.
**4. Cancellation semantics matrix — re-verified independently, assertions
read (not just names), all pass; one gap closed.**
Read every assertion, not just the test name, for: same-burst
cancel-after (`a_request_cancelled_in_the_same_burst_is_answered_cancelled`),
cancel-before (`a_cancel_dequeued_before_its_request_still_cancels_it`),
partial-batch cancel (`a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone`),
orphan/late drop with the id-reuse proof
(`a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot`),
notification-ordering
(`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`),
notifications-uncancellable (`a_cancel_never_cancels_a_notification`),
shutdown-uncancellable (`a_shutdown_is_honoured_however_it_is_cancelled`),
double cancel (`cancelling_one_request_twice_answers_it_once`), int-vs-string
ids including the `"8"` vs `8` case (`a_cancel_id_may_be_a_number_or_a_string`),
and malformed params (`a_malformed_cancel_is_dropped_rather_than_guessed_at`).
Every one asserts what its name claims; none was a false-positive
(no-op) test. All pass, independently re-run.
**Gap found and closed:** no test covered a cancel naming a
**server-initiated** id (the `lucisv-0`/`lucisv-index-N`/`lucisv-watched-files-N`
namespace from `Server::send_request`, server.rs:949). Traced it: `cancelled_in`
(server.rs:1141) only ever matches a cancel against ids of `Message::Request`
entries *received in the same batch* — a server-initiated id only ever
appears on the wire as a `Message::Response` coming back from the client,
a different match arm in `process_batch` entirely, never consulted against
`cancelled`. So interference is not possible by construction. Added
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
(server.rs:3682) to pin this rather than leave it as an inference:
it calls the real `send_request`, gets back `lucisv-0`, sends a cancel
naming it alongside an ordinary client request, asserts the client request
is untouched, and then answers the server-initiated request successfully
to prove routing was never disturbed.
**5. `-32800` on the wire — verified, one assertion added.**
`cancelled_response` (server.rs:1171) uses
`lsp_server::ErrorCode::RequestCanceled as i32`, which is `-32800` in
`msg.rs:128` — matches spec. `Response`'s `#[serde(flatten, with =
"ResponseResult")]` (lsp-server msg.rs:87-98) serializes to exactly one of
`result`/`error`, never both — confirmed by reading the encoding, and by
the e2e flood's existing `answer.get("result").is_none()` on a real wire
response (e2e.rs:3141). Id-type preservation (int in → int in response) is
implicitly covered by the flood test's own matching: it filters
`messages.iter().filter(|m| m["id"] == id)` against a Rust `u32`, which
would find nothing if the id had round-tripped as a string, and the test
asserts exactly one match per id. **Gap found and closed:** nothing
asserted that the error carried a non-empty `message` string, only that
`code` was right and `result` was absent. Added that assertion in-line at
e2e.rs (next to the `result`-absence check in
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each`).
**6. The e2e flood's honesty — one theoretical, unreproduced flake risk,
documented rather than "fixed."**
Read the whole test (e2e.rs:3079-3168). The `honoured > 0` assertion
(e2e.rs:3160) is the one the
task flagged as suspicious, correctly. Reasoning:
- The forwarder thread and the main loop's request handling run
concurrently on real OS threads. While the main thread is inside a
synchronous `self.request(...)` call (formatting), the forwarder can
keep draining the reader thread's rendezvous handoffs into the mpsc
queue in parallel — this concurrency, not any timer, is what makes a
multi-message burst likely.
- It is **not mathematically impossible** for every burst to end up size
1: a scheduler that always preempts the forwarder thread and lets the
main thread fully drain-and-reblock before the next message is
forwarded would produce zero cancellations, every time, for any finite
request count. No such interleaving was produced in 10 standalone e2e
runs plus one full `cargo test --workspace` run (which itself runs the
e2e binary), so it is not a *practical* risk today, but "never observed"
is exactly the "≠ impossible" the task named.
- **Why not fixed:** the two available code fixes both make the test
worse. Relaxing `honoured > 0` to `honoured >= 0` (i.e., deleting the
assertion) would stop the test from ever proving the cancellation path
works over the real wire at all — the one thing this e2e test exists to
check per its own doc comment. Adding a synchronization point (e.g. a
test-only delay hook) to force a burst would add production-code
surface *purely for a test's benefit*, which the "simplicity first"
section of `CLAUDE.md` weighs against, for a risk that is theoretical
and has a fallback: a failure here is a flake in one non-gating-by-flake
test, not a correctness bug (the request would still be answered
correctly once instead of cancelled — see point 4's stateless-drop
behavior — so no invariant breaks, only the "never zero" assertion
would).
- **Recommendation:** accept the residual risk as-is. If it is ever
observed to flake in CI, the fix is almost certainly to widen the
buffer/request count further (the dev already tuned this once, from a
~1-in-4 flake rate with cheap requests down to zero observed in 10+ runs
with 300 lines / 20 requests) rather than to touch the assertion itself.
**7. CLAUDE.md compliance — verified clean.**
- No bare `std::thread::spawn` (which panics on OS resource exhaustion).
The forwarder uses `std::thread::Builder::new().spawn(...)`
(server.rs:215), which returns `io::Result`, and the error is
deliberately discarded with `let _ =` plus a comment explaining the
fallback (the mpsc sender is dropped, so `run()`'s `recv()` fails and
the loop ends cleanly instead of hanging) — no panic path introduced.
This is in `main`-path server setup, which CLAUDE.md's "Tests and
`main.rs` argument handling may use them" carve-out does not literally
name, but the *effect* is a `Result`-returning call whose error is
handled without panicking or unwrapping — no rule is broken; there is
no `unwrap`/`expect`/`panic!` in this path at all.
- All `.expect(...)`/`.unwrap()` calls introduced by the diff (checked
with `git diff | grep`) are inside `mod tests` (`Session::batch`,
`symbol_names`, `outcomes`, and the shutdown test's `sender.send(...)`)
— allowed.
- New free functions and the new `Server` methods all carry one-line-plus
doc comments explaining what/why, consistent with the surrounding file's
density; none of the new items are `pub`, so the strict "public items"
rule doesn't even apply, but the dev exceeded it anyway.
- `docs/features/cancel-request/README.md`: each of the seven required
sections (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log,
Review) appears **exactly once** (checked with `grep -n "^## "`); one
extra explanatory section between Goal and Assumptions is additional,
not a duplicate, and the template doesn't forbid it.
- `TODO.md`: the §9b item's original text
("**`$/cancelRequest`** — the loop handles requests sequentially and
ignores cancellation; at minimum answer already-cancelled queued
requests with `RequestCancelled`.") is byte-for-byte intact; only the
checkbox flipped and a `→`-prefixed summary line was appended below it,
which is the same pattern used by the 9 other completed items already
in the file (`grep -c` confirms 10 occurrences total including this
one) — not a one-off deviation.
- `docs/features/lucisv-server/README.md` was also touched by this
change. That file is the umbrella index every feature registers itself
in (the method-dispatch table and the Status/TODO checklist both list
every other feature the same way), so this is the expected cross-file
touch the Handshakes section describes, not scope creep.
**Tests added this round (4 unit + 1 e2e assertion, all in the files
already under review, no new files):**
`is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`,
`burst_collects_everything_already_queued_in_arrival_order`,
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`,
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
(all in `crates/lucisv_server/src/server.rs`), plus a `message`-field
assertion added to
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each` in
`crates/lucisv_server/tests/e2e.rs`. `lucisv_server` unit count moved from
702 to 706; e2e stayed at 38 (one test grew an assertion, none added).
**Fixes made:** none beyond the test additions above — no corruption, no
mishandled message, no dropped request found anywhere in the diff.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
plus two extra e2e passes (flood test green in every run I and QA made —
twelve consecutive between us), clean. The dev's deviation from my brief
was the right kind: my burst-drain design assumed a queue that lsp-server's
rendezvous channels do not provide, the dev proved that over a real pipe
(0/5 honoured) before changing anything, and the forwarder it added is
the minimal honest fix — one thread, no shared state, stopping at
shutdown for a reason it can cite from lsp-server's own source. QA then
re-derived the shutdown hand-off from the vendored code rather than the
work log, which is exactly the adversarial re-check this workflow exists
for, and closed the four real gaps (the shutdown-shaped notification,
bare `burst` coverage, the forwarder hand-off under a real Connection,
and the server-id-namespace cancel).
The stateless cancelled-set design — a cancel matters only beside its
request in one burst, everything else dropped on sight — is the reason
this feature cannot leak or misfire across sessions, and shutdown
sitting before the cancel check closes the one hole a hostile client
could poke. On the flood test's `honoured > 0` assertion: QA is right
that a pathological scheduler could in principle defeat it and right not
to weaken it; the property is the point of the test, the risk is
unreproduced in twelve runs, and if CI ever trips it the QA log already
contains the analysis. This completes §9b. Accepted as shipped.
+20 -2
View File
@@ -25,8 +25,10 @@ green checks, matching versions, and written notes.
- One runner, capacity 1: CI and release jobs queue rather than race. A
release build and a local `cargo build` can still contend for the
machine; acceptable on a solo project.
- The corpus is not in the repository, so CI does not score it;
`scripts/score.sh` stays a local check.
- The corpus is not in the repository; CI scores it from a pinned-rev
cache on the runner host (`~/.cache/lucisv-corpus`, fetched once by
`tools/corpus_fetch.sh` on a miss) and gates on
`scripts/corpus-baseline` via `scripts/corpus_gate.sh`.
- `secrets.GITHUB_TOKEN` is auto-provided by Gitea Actions with rights to
create releases and attach assets on this repo.
- Release notes are written by hand (by the lead/Claude, specific to the
@@ -58,6 +60,14 @@ green checks, matching versions, and written notes.
- [x] `tools/release_notes.sh` (+ missing-section failure path tested),
`tools/publish_release.sh` (get-or-create, skip-attached re-run safety).
- [x] End-to-end verification with a real tag (v0.7.1).
- [x] Corpus score as a CI gate (`corpus` job: cached corpus +
`scripts/corpus_gate.sh` against `scripts/corpus-baseline`; regression,
verification error or crash fails the push).
- [x] Release-time artifact audit (`tools/audit_artifacts.sh`: musl
static-ness, linux-gnu glibc ceiling <= 2.28, PE/Mach-O file types) —
automates what RELEASING.md documented as manual; Linux/Windows binaries
remain audited, never executed (no such machine in the loop, and no
container runtime on the runner).
- [ ] A second runner on a non-macOS host, if native-built (rather than
cross-built) Linux artifacts are ever wanted.
@@ -74,6 +84,14 @@ green checks, matching versions, and written notes.
than a fallback body. Version bumped to 0.7.1 and released end-to-end as
the verification.
- 2026-08-26 — lead (round 2, after external review). Added the corpus
gate job and the release artifact audit; both tested before landing (the
gate against the local corpus at exactly the 813 baseline, the audit
against the 10 downloaded v0.7.1 release binaries — all pass). Docker
was considered for executing the musl build's tests on Linux and
rejected: no container runtime exists on the runner Mac, and installing
a VM stack is an owner decision, not a CI increment.
## QA log
_(no QA round — infrastructure, verified by the live v0.7.1 run; see work log)_
+415
View File
@@ -0,0 +1,415 @@
# incremental-sync
## Goal
Move the server from `TextDocumentSyncKind::FULL` to
`TextDocumentSyncKind::INCREMENTAL`: a `didChange` now carries the ranges the
user touched rather than the whole buffer, and the server applies them to the
text it already holds. Full-buffer sync re-serializes, re-transfers and
re-allocates the entire file on every keystroke, which is the wrong cost curve
for a server that wants to answer per-keystroke (completion, signature help,
inlay hints) — and for the editor side of a large `.sv` it is the one place
lucisv was measurably ruder than ruff. The price of the move is that the server
becomes the *only* holder of the buffer's text: a wrong offset here silently
rewrites what the user is looking at, with no full-text resend to correct it.
That is why the whole edit application is one pure function
(`sync::apply_changes`), unit-tested against a second implementation, with no
slice that can panic.
## Assumptions
- **Positions are UTF-16, as `capabilities()` says.** Every conversion goes
through `convert::Positions::offset`, the same function every other request
handler uses. There is no second offset arithmetic in this feature — that is
the point.
- **Clamping, exactly.** A client desync (or an editor rounding a position) must
never panic and never corrupt. The rules, all of them inherited from
`Positions::offset` and pinned by tests in `sync.rs`:
- a **line past the end** of the document clamps to the end of the document;
- a **character past the end of a line's content** clamps to that content's
end — before the line's `\n`, and before one `\r` preceding it, so an edit
positioned past the visible end of a CRLF line cannot land between the
`\r` and the `\n`;
- a **character landing inside a surrogate pair** (the low half of an astral
character such as `🎉`) **rounds forward** past the whole character. So a
range boundary can never split a `char`, the output is always valid UTF-8,
and an emoji is either wholly inside the replaced range or wholly outside
it;
- **`start > end` after conversion** clamps `end` up to `start`, which turns
the change into a pure insertion at `start`. There is no resync mechanism
in LSP short of the client closing and reopening the buffer, so the safe
direction is the one that deletes nothing: a user can undo an unexpected
insertion, but cannot recover text the server threw away.
- **Each change is positioned against the document the previous changes in the
same notification left.** This is what the protocol says, and it is why the
line table is rebuilt per change rather than once per notification.
- **A change with no `range` replaces the whole document**, mid-batch included,
and resets the state the ranges after it are positioned against. A batch of
rangeless changes therefore still ends at the last one — the pre-existing
full-sync behavior, kept for a client that ignores the new capability.
- **An empty `contentChanges` array is not a change**: nothing is reparsed and
the generation counter does not move, exactly as before (the old handler's
`next_back()` on an empty list did nothing).
- **A `didChange` for a buffer that was never opened** is out of protocol, but
is still taken rather than dropped: the base text is `""`, so a full-text
change lands exactly as it did before this feature, and a ranged change
clamps to an insertion at the start. No special case, no error path.
- **`O(changes × file)` per notification, honestly.** Every ranged change
builds a fresh `LineIndex` over the current text and allocates a new `String`.
For the batch sizes editors actually send (1–5 ranges) over Verilog files
this is microseconds, and it buys a function with no incremental state that
can fall out of step with the text. A rope or an incrementally-patched line
table is the optimization to reach for if a profile ever asks; TODO.md §6
already defers that whole class of work.
## Handshakes
- **Consumes `convert::Positions::offset`** (`crates/lucisv_server/src/convert.rs`)
for every position→byte conversion, and `vlog_parser::LineIndex` to build it.
Nothing was changed in either — the clamping this feature depends on is the
clamping those already documented and tested.
- **Promises `Server::set_document` is still called exactly once per
`didChange` notification.** `set_document` bumps `self.generation`, which is
the whole `resultId` of `docs/features/pull-diagnostics/README.md`; a bump
per *range* would make one keystroke look like several to a pulling client,
and no bump would let a changed buffer answer "unchanged". One notification =
one reparse = one stamp = one `publish`. Pinned by
`one_notification_is_one_generation_bump_however_many_ranges`.
- **Changes what the client is told at `initialize`.**
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
`save` values are not new behavior: they are what a bare `Kind` already
resolved to client-side (`vscode-languageclient` expands a numeric
`textDocumentSync` to exactly `{ openClose: true, change: <kind>, save: {
includeText: false } }`), written out because the options form has no
"unspecified" that means the same thing. `didSave` therefore carries no text,
which is what it carried before — and the `DidSaveTextDocument` handler still
adopts `params.text` if some client sends it anyway, so nothing regresses for
a client that behaves differently.
- **No other crate is touched.** No new dependency; the randomized test's
generator is a five-line LCG rather than `rand`.
## Status / TODO
- [x] Advertise `TextDocumentSyncOptions` with `change: INCREMENTAL`,
preserving the open/close and save semantics a bare `Kind` implied.
- [x] `sync::apply_changes(text, changes) -> String` — pure, total, no
panicking slice.
- [x] All changes applied in order, each against the previous one's result.
- [x] Rangeless change = whole-document replace, mid-batch included.
- [x] Clamping rules (line past EOF, character past line end, surrogate half,
`start > end`) defined above and tested.
- [x] One `set_document` — one reparse, one generation bump, one publish — per
notification.
- [x] Unit tests: insert/delete/replace, dependent batches, multi-byte and
astral characters, CRLF, (0,0), EOF, no trailing newline, rangeless
mixed into a batch, every clamping rule.
- [x] Randomized cross-check against a second implementation built on
`char`s and lines, fixed seed, 400 cases.
- [x] Server-level tests: incremental batch == one full change, generation
bumps once, full-sync batch still ends at the last change, publishes
reflect the composed text.
- [x] e2e test driving the real binary with four ranges over two
notifications.
- [x] `docs/features/lucisv-server/README.md` sync/staleness text updated.
- [x] TODO.md §9b item checked off.
## Work log
**2026-08-26 — dev.** Implemented the whole feature in one round.
- New module `crates/lucisv_server/src/sync.rs` (declared in `main.rs`), one
public function `apply_changes(&str, &[TextDocumentContentChangeEvent]) ->
String`. Chosen over putting it in `convert.rs`: `convert.rs` is the
byte↔position primitive every handler shares, and this is a protocol-level
policy (ordering, rangeless resets, desync clamping) built *on* it. Keeping
them apart means the safety-critical policy has its own test module and its
own reference implementation to be checked against.
- The function is deliberately dumb: `String` in, `String` out, a fresh
`LineIndex` per ranged change. No incremental line table, no rope, no
reusable "document buffer" abstraction for a second user that does not
exist. The cost is written down under Assumptions rather than optimized away.
- **No panicking slice.** `start`/`end` come from `Positions::offset`, which
only ever returns character boundaries, so `text[..start]` would be provably
safe — but "provably" leans on another module's invariant, and the failure
mode is a panic that takes the user's buffer with it. The splice uses
`text.get(..start)` / `text.get(end..)` and skips the change if either is
`None` (unreachable), so the function is total by construction.
- **Clamping decisions.** Line/character clamping is inherited from
`Positions::offset` rather than re-decided here — a second clamping rule
would be a second set of off-by-ones. The one genuinely new decision is
`start > end`: `end` clamps *up* to `start`, making the change an insertion.
Rejected alternatives: dropping the change (leaves the server's text and the
client's silently different, with no way back), and swapping the two (invents
a deletion the client never asked for). Insertion is the only reading that
cannot lose text.
- **Capability.** Moved to the options form. Establishing what a bare `Kind`
meant for save was the fiddly part: the spec leaves it to the client, and
`vscode-languageclient` fills in `{ openClose: true, change, save: {
includeText: false } }`. Writing those two out keeps every client on the
behavior it had, and `includeText: false` is also the right answer on its own
terms now — the server tracks the buffer edit by edit, so a save re-sending
the file would be pure waste. The `didSave` handler was left alone: it still
adopts `params.text` when present, so a client that sends text anyway is
handled exactly as before.
- **Handler.** `DidChangeTextDocument` reads the base text out of the workspace
(`""` if the buffer is unknown), calls `apply_changes` once, and goes through
the existing `set_document` + `publish` path unchanged — so the
pull-diagnostics generation model, the `lucisv.toml` warning re-arm, and the
push/pull gate all behave as they did.
- **Tests: 23 unit (`sync.rs`) + 6 server-level (`server.rs`) + 1 e2e.** The
randomized cross-check (`random_edit_sequences_agree_with_the_reference_model`)
runs 400 sequences of 1–5 changes over random texts drawn from
`{a, b, space, ;, \n, \r\n, é, 🎉}` — every character width, both line
endings, and bare `\r`s — with positions deliberately allowed out of range so
the clamping rules are exercised too. It compares against `reference_apply`,
a flat `Vec<char>` implementation that scans its own line starts and shares
no code with `apply_changes`, and additionally asserts that applying the
batch in one call equals applying the changes one at a time. Seed is fixed
(`0x5EED_1CE5`), no dependency added.
- Deviations from the plan: none. Nothing outside `lucisv_server` was touched
in code. Two documentation files outside this feature were annotated rather
than rewritten, because both stated something this round made false:
`docs/features/lucisv-server/README.md` (the "full-text sync only"
assumption, the recompute table, and one sentence of an old QA log that read
`textDocumentSync: 1` off the capabilities JSON) and one parenthetical in
`docs/features/pull-diagnostics/README.md` that justified the single
generation counter by "full-text sync ignores versions" — the conclusion
still holds, the reason needed rewording. No QA log or Review section was
otherwise touched.
## QA log
**2026-08-26 — QA.** Re-ran every gate, then attacked the six surfaces the
lead flagged plus a few of my own. Verdict: **committable as-is**. No
corruption, no panic, no divergence from a well-behaved client found; one
pre-existing (not introduced by this feature) latent edge case documented
and pinned rather than fixed, since fixing it means changing a shared
primitive (`convert.rs`) outside this feature's scope.
**Gates re-run, all clean:**
- `cargo fmt --all -- --check` — clean.
- `cargo clippy --all-targets` — clean (touched the three changed files and
re-ran to defeat the cache; still clean).
- `cargo test --workspace` — every crate green, 0 failed. `lucisv_server`'s
own run: 628 lib tests (23 in `sync.rs` as claimed, plus 5 I added), 33
e2e, 3 grammar. `cargo test -p vlog_formatter` also re-run per CLAUDE.md's
formatter-change rule (this isn't a formatter change, but confirmed green
anyway): 114 passed.
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` —
`smoke: OK`.
**1. Surrogate rounding — verified clean, direction confirmed by reading
`convert.rs`.** `Positions::offset` (`crates/lucisv_server/src/convert.rs:39`)
walks the line's `char`s accumulating UTF-16 units and only ever returns an
offset it has actually reached by consuming whole `char`s (`offset += ch.
len_utf8()` happens only together with `units += ch.len_utf16()`), so the
returned byte offset is always the smallest character boundary whose
cumulative UTF-16 unit count is `>= pos.character` — i.e. it always rounds
up/forward, unconditionally, for every position (start or end). What
"forward" *means* differs by role: for a start boundary it means the
character is excluded (the insertion/deletion point moves past it, so the
character survives); for an end boundary it means the character is included
(the deletion widens to swallow it). Both are the same mechanical rule.
Added two direct tests pinning the exact resulting string, as asked:
`crates/lucisv_server/src/sync.rs`
`a_deletion_starting_at_the_low_surrogate_index_preserves_the_character`
(`edit((0,4),(0,6),"")` on `"// 🎉 ok\n"` → `"// 🎉ok\n"`, emoji survives) and
`a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character`
(`edit((0,3),(0,4),"")` on the same text → `"// ok\n"`, emoji consumed).
Both pass. The dev's own two existing tests in
`an_astral_character_takes_two_units_and_is_never_split` already hit this
exact case (`edit((0,4),(0,6),"X")` and `edit((0,3),(0,4),"X")`) but as
replacements, not pure deletions — the two I added close that gap with an
empty `text`. Cross-checked against the LSP spec: positions are UTF-16
code-unit offsets and a spec-compliant client never legitimately sends a
mid-pair boundary, so any total, non-panicking rule is acceptable — the
README's description ("rounds forward past the whole character") is
accurate to the actual code, not just to the reference model.
**2. Divergence-from-editor risk — one real (low-severity, pre-existing)
finding, everything else clean.**
- **Fresh-`LineIndex`-per-change is not hoisted.** `crates/lucisv_server/src/
sync.rs:35`, `let index = LineIndex::new(&text);`, is inside the `for
change in changes` loop, rebuilt from the current `text` every iteration —
confirmed by reading the code (not just trusting the comment), and then by
actually breaking it: I temporarily hoisted the `LineIndex::new` call above
the loop (reusing one stale index for every change) and reran `cargo test
--bin lucisv-server sync::tests::`. Three tests failed against the stale
index: `a_later_range_positioned_against_the_original_text_would_be_wrong`
(panics — its own doc comment names exactly this regression),
`a_rangeless_change_resets_what_the_next_range_is_against`, and
`random_edit_sequences_agree_with_the_reference_model` (400/400 cases
depend on this). `later_changes_see_what_the_earlier_ones_did` did *not*
fail under hoisting — its three edits happen to stay valid against the
stale index anyway, so it does not by itself pin this — but the three that
did fail are sufficient. Reverted the hoist immediately after (confirmed
back to 28/28 passing); no new test needed, the existing ones already pin
this correctly.
- **A change whose range covers the final newline** — clean. Added
`a_change_covering_the_final_newline_removes_exactly_it`:
`edit((1,1),(2,0),"")` on `"a\nb\n"` → `"a\nb"`. Removes exactly the
trailing `\n`, nothing else.
- **Adjacent zero-width ranges at the same position in one batch** — not a
bug, and pinned as such. Added
`zero_width_inserts_at_the_same_position_compose_in_batch_order`: two
inserts both naming `(0,0)` on `"x"` with texts `"1"` then `"2"` produce
`"21x"`, because each change's position is (correctly, per protocol)
resolved against the text the previous change left — the second insert's
literal position `0` is now *before* the first insert's text. A client
that wants `"12"` must advance the second position past the first's
length, same as it would for a non-zero-width range. This matches "each
change is positioned against the document the previous changes in the
same notification left" exactly.
- **`\r\n` split across two changes in one batch — finding.**
`crlf_split_across_two_changes_in_one_batch_reorders_the_bytes`
(`crates/lucisv_server/src/sync.rs`): `apply_changes("ab", &[edit((0,2),
(0,2), "\r"), edit((0,2),(0,2), "\n")])` produces `"ab\n\r"`, not
`"ab\r\n"`. Root cause: `convert.rs::line_content_end`
(`crates/lucisv_server/src/convert.rs:96`) treats a trailing bare `\r` as
"not content" unconditionally — whether or not a `\n` will ever follow it
— so once change 1 leaves the buffer ending in a lone `\r`, "end of line"
for change 2 clamps to *before* that `\r`, and the `\n` lands ahead of it
instead of after. This is **not introduced by this feature**: the rule
lives in `convert.rs`, which predates incremental sync and is shared by
every position-converting handler. What incremental sync newly does is
give this quirk a path to actually rewrite the *persisted buffer* rather
than just a hover/diagnostic range — before this feature, the server never
computed byte offsets to build a document to save, it just accepted the
client's already-composed text verbatim. In practice this needs a client
to split one `\r\n` insertion into two separate ranged edits inside a
single `didChange` batch, positioned at the exact same coordinates for
both; no known editor's diff algorithm does this (VS Code/Neovim send
`\r\n` as one atomic edit). No panic, no data loss (both bytes survive,
just reordered), so it does not violate the "never corrupt" invariant in
the "produces wrong output" sense used elsewhere in this repo (no crash,
no truncation) but it is a genuine silent-divergence risk if a
pathological client ever does this. Recorded and pinned rather than fixed:
fixing it means deciding whether `line_content_end` should special-case "a
bare trailing `\r` with nothing after it, at the very end of the buffer or
the very end of a change-in-progress" — a `convert.rs` decision that
affects every handler, out of this feature's stated scope
(`sync.rs`/`main.rs`/`server.rs` only). Filed as a follow-up rather than
redesigned here.
- Multi-byte/astral columns (`a_ranged_change_over_multi_byte_text_edits_the_
right_columns`, server.rs) and CRLF-on-one-line edits (`crlf_line_ends_
survive_an_edit_on_the_line`, sync.rs) — re-verified by hand-tracing
`Positions::offset`, both clean, no off-by-one.
**3. Full-sync regression — verified clean.** Diffed the old handler
(`git show aa303ce:crates/lucisv_server/src/server.rs`, the `next_back()`
form) against the new path:
- *Multiple rangeless changes*: old took only the literal last element via
`next_back()` (O(1), never touched the earlier ones); new applies all of
them via `apply_changes`, but each rangeless change fully replaces `text`
and continues, so the net result is identical — last one wins either way.
Confirmed by the dev's `the_last_of_several_rangeless_changes_wins`
(sync.rs) and `a_full_sync_clients_batch_still_lets_the_last_change_win`
(server.rs). The new path is `O(changes)` string clones instead of `O(1)`
for this specific case — a real but tiny and already-documented cost, not
a correctness regression.
- *Empty `contentChanges`*: old — `next_back()` on empty returns `None`, no
`set_document`/no `publish`. New — explicit `if p.content_changes.
is_empty() { return; }` before touching anything. Identical observable
behavior; confirmed by `one_notification_is_one_generation_bump_however_
many_ranges`'s second half (server.rs) which checks the generation counter
does not move.
- *Unknown/never-opened uri*: old — `set_document(uri, change.text)`
unconditionally, no existence check. New — `self.workspace.document(&uri).
map_or("", ...)` then `apply_changes`; for a rangeless change this reduces
to the same `set_document(uri, change.text)`. Confirmed by `a_change_
naming_a_buffer_that_was_never_opened_is_taken_as_written` (server.rs,
rangeless case). I did not find a server-level test of a *ranged* change
against a never-opened buffer, but it is exercised at the unit level
(`an_edit_into_an_empty_document` in sync.rs, since `apply_changes` is
handed `""` either way) and the handler code between the two cases is the
same three lines — low-severity gap, noting rather than adding a
redundant test.
**4. Capability shape — verified clean, confirmed on the actual wire, not
just by reading the struct.** Ran the built binary directly through a
minimal `initialize` and inspected the raw JSON response (not just the
e2e/smoke assertions): `textDocumentSync` serialized as exactly
`{"change":2,"openClose":true,"save":{"includeText":false}}` — no
`willSave`/`willSaveWaitUntil` keys at all (`lsp_types::
TextDocumentSyncOptions` marks both `#[serde(skip_serializing_if = "Option::
is_none")]`, so `None` means genuinely absent from the wire, not `null`).
This is exactly what `vscode-languageclient` and Neovim's builtin client
parse as `{openClose: true, change: Incremental, save: {includeText:
false}}`, with the will-save fields correctly unadvertised for a future
round. `incremental_changes_are_advertised_and_applied_over_the_wire`
(e2e.rs) asserts `sync["change"] == 2`, `sync["openClose"] == true`,
`sync["save"]["includeText"] == false` — confirmed this really does pin the
shape, it isn't a no-op assertion.
**5. Performance honesty — verified clean.** `Server::set_document`
(`crates/lucisv_server/src/state.rs:175`, called from the `DidChangeTextDocument`
arm exactly once per notification per the diff at `server.rs`) is the only
place a `Document::new` (full reparse/tokens/`Semantics`) happens. Inside
`sync::apply_changes`, only a `LineIndex::new` (a single linear scan for
`\n` bytes, not a parse) and a `String` allocation happen per *ranged*
change — that's the honest `O(changes × file)`, not `O(changes × file²)`
and not a hidden per-change reparse. Confirmed by reading `state.rs:175-179`
and by the fact that `self.generation` (bumped only inside `set_document`)
moves exactly once per notification regardless of range count, per
`one_notification_is_one_generation_bump_however_many_ranges`.
**6. CLAUDE.md compliance — clean.** No `unwrap`/`expect`/`panic!` in
library code paths in `sync.rs` or the `server.rs` handler diff (`grep`
confirms the only `expect()`s introduced are inside `#[cfg(test)]` code in
`server.rs`, which CLAUDE.md permits). No new `#[allow]`. `sync.rs` has a
module doc comment and `apply_changes` has a doc comment. Feature README has
all six required sections. `TODO.md`'s §9b item text is unchanged aside from
the checkbox and an appended implementation-summary paragraph (allowed — the
rule is "leave the item text intact", not "add nothing"). The two annotation
edits to `docs/features/lucisv-server/README.md` and `docs/features/
pull-diagnostics/README.md` are both dated 2026-08-26, self-identifying
("*(That last sentence records the state at the time of this QA pass
only...)*", "*(Still true after incremental sync, 2026-08-26: ...)*"), and
factual against the diff — neither rewrites the original text, both append.
One minor nit: the original (pre-existing) `TODO.md` §9b bullet's plan text
says "with a full-text fallback on any malformed change", but the shipped
implementation uses clamping instead of a full-text fallback for a malformed
change — a better and thoroughly-justified design choice (see the README's
Assumptions and Work log), but the Work log's "Deviations from the plan:
none" doesn't call out that the *originally-planned* mechanism changed
between the TODO's wording and the implementation. Cosmetic — the actual
behavior is fully and correctly documented elsewhere in the same README —
not asking for a fix, just noting it for the record.
**Tests added this round** (all in `crates/lucisv_server/src/sync.rs`,
all passing): `a_deletion_starting_at_the_low_surrogate_index_preserves_
the_character`, `a_deletion_ending_at_the_low_surrogate_index_consumes_
the_whole_character`, `crlf_split_across_two_changes_in_one_batch_
reorders_the_bytes`, `a_change_covering_the_final_newline_removes_exactly_
it`, `zero_width_inserts_at_the_same_position_compose_in_batch_order`.
**Verdict: committable as-is.** No dev follow-up required to ship; the
`\r\n`-split-across-changes behavior is worth a future look if `convert.rs`
is ever revisited, but it is pre-existing, unreachable by any known real
client, and now pinned by a test rather than silently latent.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full
workspace suite/smoke.js myself, all clean. `apply_changes` is the right
shape: pure, total, no panicking slice, and the fresh-line-table-per-change
decision buys correctness with microseconds — the honest O(changes × file)
note is exactly how this repo trades. Inheriting the clamping rules from
`Positions::offset` instead of inventing a second set was the correct call,
and the `start > end` → pure-insertion rule is the only reading that cannot
lose the user's text.
On QA's finding (a `\r` + `\n` split across two same-position inserts in
one batch lands as `\n\r`): accepted as pinned, not fixed. The root cause
is `convert.rs`'s pre-existing treatment of a trailing bare `\r`, which is
shared by every handler and out of this feature's scope; no real client
splits a CRLF across two changes of one batch, and the behavior is now
documented by a test rather than latent. If a cross-file `convert.rs`
round ever opens, this goes with it. The randomized cross-check (400
sequences against an independent model), the deliberate-breakage check
that the line table really is rebuilt per change, and the wire-level
capability assertion give this the confidence a sync rewrite needs.
Accepted as shipped.
+85 -15
View File
@@ -18,8 +18,14 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|---|---|---|
| `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed |
| `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) |
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync |
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` |
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it |
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md` |
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` |
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
@@ -37,6 +43,8 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README |
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
| `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` |
| `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` |
| `$/cancelRequest` | — | Best-effort, and honoured exactly when the cancel reaches the loop in the same burst as the request it names: that request is answered `RequestCancelled` (-32800) instead of computed. A cancel for anything else is dropped where it is read, `shutdown` is never cancellable, and nothing already running is interrupted. See `docs/features/cancel-request/README.md` |
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
(waits on TODO.md §2 `--lines`)~~ **delivered by range-formatting (round 18):
@@ -182,23 +190,45 @@ every character boundary of a document mixing all of those.
## State and staleness
Single-threaded request loop — `lsp-server`'s model. Two I/O threads (its
own) read and write stdio; this crate's loop receives one message, handles it
to completion, and sends the response before looking at the next. No shared
mutable state, no locks, no cancellation. Verilog files are small and every
handler is milliseconds; the complexity of a worker pool buys nothing yet.
own) read and write stdio; this crate's loop handles one message to completion,
and sends the response before looking at the next. No shared mutable state, no
locks, and nothing already running is ever interrupted. Verilog files are small
and every handler is milliseconds; the complexity of a worker pool buys nothing
yet.
**Since 2026-08-26 the loop reads in bursts** rather than strictly one message
at a time: it blocks for the next message, takes everything already queued
behind it without blocking, and then handles that whole burst **in arrival
order** — a `didChange` ahead of a completion is applied before the completion
is answered, exactly as before. The one thing the burst adds is
`$/cancelRequest`: a request the same burst also carries a cancel for is
answered `RequestCancelled` (-32800) instead of being computed, which is the
only moment a one-thread server can honour a cancel at all. A cancel that
names no request in its burst is dropped where it is read (the request was
answered in an earlier burst, or never existed), so cancellation costs no
state; `shutdown` is handled before any cancel is consulted and so can never
be cancelled. Because `lsp-server`'s transport uses zero-capacity rendezvous
channels — a client's backlog sits in the OS pipe, not on
`connection.receiver` — the loop first forwards incoming messages onto an
unbounded queue of its own on one small thread, which stops at `shutdown` so
`handle_shutdown` keeps its own read of the `exit` that follows. Rules,
reasoning and the measurements: `docs/features/cancel-request/README.md`.
**Two layers, invalidated by different events** — exactly the split
`docs/features/workspace-index/README.md` designed for:
| layer | rebuilt when | cost |
|---|---|---|
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute |
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, and a changed `lucisv.exclude`/`lucisv.filelist` | full re-scan of the roots |
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
deferred there.
deferred there. Incremental *sync* did not change that: the wire now carries
ranges, but a `didChange` still throws the whole `Document` away and builds a
new one — one reparse per notification, which is also the one generation bump
the pull-diagnostics `resultId` depends on.
**Open buffers override disk** in every index rebuild: the roots are walked,
each file read, and then every open document with a path replaces the disk
@@ -215,6 +245,18 @@ point where the answer is expected to change anyway. Measured cost of a
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
plus the file reads.
**Every rescan is visible since 2026-08-26**, for a client that advertised
`window.workDoneProgress`: the startup build and all three `reindex()` triggers
are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
begin/end pair on a fresh `lucisv-index-N` token, so a multi-second index on a
big filelist reads as work rather than as a hang. The `begin` does not wait for
the create's answer (the rescan blocks the loop immediately after), the answer
is ignored on the same path the watcher registrations' is, there is no
percentage and no intermediate report — the rescan is one opaque call — and the
`end` names the indexed file count. A client that did not advertise the
capability is sent nothing at all, which the spec requires. Rules and the
startup-legality argument: `docs/features/work-done-progress/README.md`.
**Changes made outside the editor close on the next notification, not on the
next save** (M9, `docs/features/file-watching/README.md`). The server registers
`workspace/didChangeWatchedFiles` for `**/*.{v,vh,sv,svh}` and for the
@@ -238,10 +280,17 @@ not see.
## Assumptions
- **Full-text document sync only.** The server advertises
`TextDocumentSyncKind::FULL`, so a `didChange` carries the whole buffer and
there is no incremental-edit application to get wrong. At Verilog file sizes
the wire cost is irrelevant.
- ~~**Full-text document sync only.**~~ **Superseded (incremental-sync, round
2026-08-26).** The server advertises `TextDocumentSyncKind::INCREMENTAL`
inside a `TextDocumentSyncOptions` (`openClose: true`,
`save.includeText: false` — the same values a bare `Kind` resolved to
client-side, so only `change` moved). A `didChange` now carries ranges, and
`sync::apply_changes` applies them in order to the buffer the server holds:
each range is positioned against what the previous ones left, a change with
no range still replaces the whole document, and every out-of-range or
backwards position clamps rather than panicking. The server is now the only
holder of the buffer text, which is what makes that function's rules worth
reading in full: `docs/features/incremental-sync/README.md`.
- **Every document URI is a `file:` URI.** `untitled:` buffers are accepted
and served for everything single-file (diagnostics, tokens, formatting,
symbols), but they have no path, so they never enter the workspace index.
@@ -378,7 +427,18 @@ Two rules that are easy to get wrong and are tested:
three multi-line token shapes that would violate it — a block comment, a
continued `` `define``, and a multi-line macro invocation. Every span is
split at `\n` before encoding, and the pieces are sorted by (line, start)
before the delta encoding runs.
before the delta encoding runs. Single-line tokens are also what lets the
`range` filter reason about overlap without looking at the text at all.
Since 2026-08-26 that classification feeds three requests, not one: the pass
produces an intermediate **absolute** form (line, column, length, type,
modifiers), `range` filters it, and one pure encoder delta-encodes whatever is
left — from the start of the document in every case, so a range answer stands
on its own. The `resultId` bookkeeping that makes `full/delta` possible lives
in `server.rs` (one counter, one remembered answer per open buffer, dropped on
`didClose`), because `tokens.rs` owns no state. Rules, the prefix/suffix
overlap trap and the round-trip property:
`docs/features/semantic-tokens-delta/README.md`.
## Hover, and the order it tries things
@@ -442,7 +502,10 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
`Semantics`, `DefineTable`, overlay), workspace walk, index rebuild.
- [x] `textDocument/formatting`.
- [x] Diagnostics on `didOpen`/`didChange`/`didSave`.
- [x] `textDocument/semanticTokens/full`.
- [x] `textDocument/semanticTokens/full`, joined by `/range` and `/full/delta`
(2026-08-26) — one tokenizer and one encoder behind all three, plus a
per-buffer `resultId` dropped on `didClose`.
`docs/features/semantic-tokens-delta/README.md`.
- [x] `textDocument/hover`.
- [x] `textDocument/definition`.
- [x] `textDocument/references`.
@@ -495,6 +558,10 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
`docs/features/hierarchy/README.md`.
- [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) —
`docs/features/macro-expansion/README.md`.
- [x] `$/cancelRequest` — delivered by **cancel-request** (2026-08-26,
completing TODO.md §9b): the loop reads in bursts and answers a queued
request whose cancel is in the same burst with `RequestCancelled`,
order across the burst unchanged. `docs/features/cancel-request/README.md`.
- [ ] **Not done:** editor packaging (the VS Code extension and the
`lspconfig` snippet are their own TODO.md §6 item).
@@ -770,7 +837,10 @@ character-past-end-of-line, line-past-end-of-file, and both-past-end → all
six combinations return graceful `null`/`[]`, no protocol error, no crash;
server process survived and later exited cleanly (code 0). `textDocumentSync`
confirmed `1` (Full) in the capabilities JSON, so the "stale/overlapping
`didChange`" scenario is moot as documented.
`didChange`" scenario is moot as documented. *(That last sentence records the
state at the time of this QA pass only: sync became incremental on
2026-08-26, and the clamping that keeps a desynced `didChange` harmless is
specified and tested in `docs/features/incremental-sync/README.md`.)*
**Robustness.** All PASS. Malformed `Content-Length: notanumber` header, and
a well-framed-but-garbage JSON body → in both cases the process does **not**
+291
View File
@@ -0,0 +1,291 @@
# pull-diagnostics
## Goal
Serve diagnostics the modern way (LSP 3.17): the client asks
`textDocument/diagnostic` for the buffer it is showing and
`workspace/diagnostic` for the rest, when *it* decides — so the visible editor
is prioritised, nothing is computed for a buffer nobody is looking at, and the
client caches by `resultId` instead of re-drawing everything on every
keystroke. lucisv had only the push model (`textDocument/publishDiagnostics`
on every change). This round adds the pull model beside it, off the same
parse+lint pass, and makes sure **one client is never served both** — two sets
of squiggles for one file is the classic way to ship this feature wrong.
## Assumptions
- **The capability is the switch.** A client that sent
`textDocument.diagnostic` at initialize is a pulling client and is pushed
*nothing at all*, ever. A client that did not keeps today's push behavior
byte for byte. There is no setting: the protocol already asks the question.
- **The `didClose` clear is not pushed to a pulling client either.** In the
push model an empty publish is how a server erases what it drew, and that
stays. In the pull model the client owns the whole lifecycle of what it
pulled — it decides when to ask and drops a closed document's diagnostics
itself (`vscode-languageclient`'s diagnostic feature does exactly this) —
so a publish arriving at close would be the server's only push of the
session and would land in a channel the client is not reading for this
document. The gate therefore sits in `send_diagnostics`, which both callers
go through: one place, no way to leak a push.
- **`resultId` is a single generation counter, and nothing else.** It is
bumped in `set_document` (a buffer's text changed) and in `reindex` (the
workspace index changed). A pull whose `previousResultId` equals the
current generation is answered `unchanged`; anything else is a full report.
This is deliberately **coarser** than per-buffer versioning: editing file A
invalidates the client's cached stamp for file B, which costs one extra
full report — a cheap, correct answer. The error the coarse direction
cannot make is the expensive one: a stale `unchanged` is a wrong squiggle
left on screen. (The brief suggested `generation/doc-version`; the server
does not track document versions at all — the sync path ignores them — so
the second half would have been a constant. One number, documented, beats a
format that implies a precision that is not there.) *(Still true after
incremental sync, 2026-08-26: `DidChangeTextDocumentParams.version` is
unread, and one notification is still exactly one generation bump however
many ranges it carried.)*
- **`inter_file_dependencies: true` is honest.** A save rebuilds the
workspace index, and a buffer's diagnostics are computed against that index
(`resolve_external` in `state.rs`), so a save in file A really can change
what file B reports. That is exactly why `reindex` bumps the generation.
- **`workspace/diagnostic` reports the open buffers only.** This server has
never diagnosed a file it was not shown: `publish` is per open buffer, and
`reindex` republishes only open buffers. Linting the whole workspace on a
pull would be a parse of every in-scope file per request, on a request a
client may send after every keystroke. So the workspace report is the open
buffers, in URI order. **This is the honest limit of the feature**: a
client using workspace diagnostics as its only source sees findings for
files it has open, not for the project. Widening it is its own round, with
its own cost model (and probably `workDoneProgress`, TODO §9b).
- **No partial results, no streaming, and no
`workspace/diagnostic/refresh`.** Partial results are not advertised, so no
client will ask for them. A refresh request would let the server tell a
pulling client "ask again, the index moved"; it is not sent, so such a
client sees post-save changes at its own next pull. Stated because it is
the one place the pull model is *lazier* than the push model this replaces.
- **Both models answer from one function.** `Server::diagnostics_of` is the
single computation (`diagnostics::all`, i.e. parse errors, then the
missing-closer warnings, then lint), and `publish` and both pull handlers
all call it. A second conversion path would be a second set of off-by-one
bugs; pinned by `both_models_say_exactly_the_same_thing_about_a_buffer`.
- **A pull for a buffer that is not open is an empty full report**, not an
error: the client asked about a document this server knows nothing about,
and "no findings" is the true answer.
## Handshakes
### `lucisv_server::main`
- `capabilities()` gains `diagnostic_provider: DiagnosticServerCapabilities::Options`
with `identifier: "lucisv"` (the same string every diagnostic's `source`
carries — one constant, `diagnostics::SOURCE`), `inter_file_dependencies:
true`, `workspace_diagnostics: true`.
- `pull_diagnostics_support(&InitializeParams)` reads
`text_document.diagnostic`; its two fields (dynamic registration, related
documents) are about things this server does not do, so the presence of the
capability is the whole of the statement.
### `lucisv_server::server`
- `ClientAbilities` gains `pull_diagnostics: bool`.
- `Server` gains `generation: u64`, bumped in `set_document` and `reindex`.
- New handlers: `DocumentDiagnosticRequest`, `WorkspaceDiagnosticRequest`.
- `send_diagnostics` is now the single gate on pushing anything.
- `diagnostics_of(uri)` is the one computation both models read.
### `diagnostics`
Unchanged. `diagnostics::all` and `diagnostics::SOURCE` are consumed as they
already were; nothing was added to that module.
### `editors/*`
No change. `vscode-languageclient` 9.x advertises the diagnostic capability
and drives the pull itself, so the VS Code extension switches models with no
edit — and `editors/vscode/smoke.js` sends `capabilities: {}`, so it stays on
the push model and keeps asserting what it always asserted.
## Status / TODO
- [x] `DiagnosticOptions` advertised, identifier pinned to the publish source
- [x] `textDocument/diagnostic`: full report with a `resultId`, `unchanged`
when the generation stands
- [x] `workspace/diagnostic`: open buffers in URI order, `previousResultIds`
honoured per file
- [x] Push suppressed for a pulling client — including the `didClose` clear
- [x] One computation behind both models
- [x] Tests: never-pushed, push-client-unchanged, full-then-unchanged-then-
full, reindex moves the stamp, unopened buffer, workspace report and
its stamps, both models identical
- [ ] Not done, deliberately: workspace diagnostics do not cover unopened
workspace files — see Assumptions.
- [ ] Not done, deliberately: no `workspace/diagnostic/refresh`, no partial
results, no `relatedDocuments`.
## Work log
### 2026-08-26 — dev agent, §9a
- **The gate went into `send_diagnostics`, not into `publish`.** Both the
change-driven publish and the `didClose` clear go through it, so one `if`
covers every push the server can make. Putting it in `publish` would have
left the close path pushing to a pulling client.
- **One generation counter** instead of the suggested
`generation/doc-version` pair: the server does not track document versions
(`DidChangeTextDocumentParams.version` is ignored under full-text sync), so
the second component would always have been the same string. Recorded in
Assumptions as a deliberate deviation from the brief, with the failure mode
it cannot have.
- **URI order in the workspace report** because `open_uris()` comes off a
`HashMap` and would otherwise shuffle between two pulls of identical state,
which reads as churn to a human and makes a test flaky.
- **`version: None`** on the workspace reports: the protocol wants the
document version the diagnostics were computed for, and this server has
none to give.
- Files touched: `crates/lucisv_server/src/server.rs`,
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`, and
the capability table in `docs/features/lucisv-server/README.md` (the
`publishDiagnostics` row is now conditional). Nothing in `diagnostics.rs`,
`lint.rs` or any engine crate.
**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings),
`cargo test --workspace`, `node editors/vscode/smoke.js` (still on the push
model, unchanged) — all clean. 8 new unit tests in `server.rs`, 2 in `main.rs`
(the options, and the capability probe), and one e2e session
(`a_pulling_client_is_answered_and_never_pushed_over_the_wire`) whose central
assertion is that the *next thing the server says* after a pull request is the
answer and not a push.
## 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, rebuilt from a
touched source tree so this wasn't answered from cache), `cargo test
--workspace` (3 full runs, no failures), `node editors/vscode/smoke.js
target/debug/lucisv-server` (exit 0, still on the push model as claimed).
**The stale-`unchanged` hunt — this was the main assignment.** Traced every
input `Server::diagnostics_of` reads (`diagnostics::all`: parse errors +
`pairs::missing_end_diagnostics` + `lint::diagnostics`, all three reading only
`doc.text`/`doc.tokens`/`doc.tree`/`doc.line_index`/`doc.semantics` —
confirmed by reading `diagnostics.rs`, `lint.rs`'s `context()`, and
`vlog_linter::registry::default_rules()`) against every event that can reach
the server without going through `set_document` (which bumps `generation`)
or `reindex` (same):
- `DidChangeConfiguration` (`server.rs`'s `notification` handler): the
settings it can change are `line_length`, `indent`, `exclude`, `filelist`,
`inline_templates` (`settings.rs`). Checked each against what
`diagnostics_of` actually reads: `line_length`/`indent` only ever reach
`format.rs` (the formatting request), never the lint or parse-error path;
`inline_templates` is ghost-text only, read nowhere near diagnostics.
`exclude`/`filelist` *do* trigger `self.reindex()` when
`set_client_settings` reports a real change — which bumps `generation`
anyway, so even though this pair does not currently touch a single open
buffer's own diagnostics, the code already treats it as invalidating.
**No live bug**, but see the finding below.
- `lucisv.toml` picked up via file watchers (`DidChangeWatchedFiles`,
`watch::touches_scope`): any matched source file always routes to
`self.reindex()`, unconditionally bumping `generation` — including for a
file nobody has open. Coarser than necessary (an edit to an unrelated file
invalidates every open buffer's stamp) but never stale-in-the-dangerous-
direction.
- `reindex` paths generally (save, watched-file change, exclude/filelist
change, `didOpen` with no workspace root): all funnel through the one
`reindex()` method, which increments `generation` unconditionally before
doing anything else — verified by reading the method body, not just the
call sites.
- **`doc.external`** (`resolve_external`, the thing the README's own
Assumptions section cites as *why* `inter_file_dependencies: true` is
honest) is read only by `hover.rs` and `nav.rs` — grepped every non-test
use. **Diagnostics never read it.** So today, no lint rule or parse error
actually depends on the workspace index at all; the README's justification
for `inter_file_dependencies` describes a coupling that does not yet exist
in the diagnostics path (it exists for hover/definition). This is not
presently a correctness bug — bumping `generation` on `reindex` is the
*safe* direction regardless of whether anything currently needs it — but
the README's Assumptions text over-claims the *reason*. **Finding
(informational, not a defect):** the real invariant this feature depends on
is "every diagnostic-affecting input bumps `generation`," which today is
satisfied only because diagnostics happen to have no configurable/workspace-
dependent input at all. `lint.rs`'s own doc comment says as much
("Selection (`--select`/`--ignore`) has no `lucisv.toml` key yet"). The
day a lint rule becomes configurable or cross-file-aware, whoever adds it
must also audit whether it needs to bump `generation` — nothing today
enforces that, and this feature's tests cannot catch a violation of an
invariant about code that doesn't exist yet. Flagged for the lead/dev to
decide whether to soften the Assumptions wording; not fixed directly since
it is a wording call, not a code defect.
- Conclusion: **no reproducible stale-`unchanged` sequence exists against
the current codebase.** I looked for one (attempted repro via a
`lineLength` push mid-session expecting it to be invisible to a pull
client — it is, but it is also invisible to a *push* client for the same
reason: line length never touched diagnostics before this feature either)
and could not construct one.
**Push/pull exclusivity, verified structurally, not just by test.** Grepped
`server.rs` for every call site of `send_diagnostics` (the only place
`PublishDiagnosticsParams` is constructed): exactly two — `publish()` (open/
change/reindex) and the `didClose` clear. Both funnel through
`send_diagnostics`, which is the single `if self.abilities.pull_diagnostics
{ return; }` gate. There is no third path that could bypass it. Existing
test `a_pulling_client_is_never_pushed_diagnostics` already exercises
didOpen/didChange/didSave/didClose; added no new test here since the
structural argument (one gate, two call sites, both covered) is stronger
than another sequence test would be.
**`workspace/diagnostic` edge cases — added three tests** in `server.rs`,
all passing:
- `an_empty_workspace_answers_a_well_formed_empty_report` — no open buffers
at all: `items` is `[]`, not an error, not a missing field.
- `a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless` — a
`previousResultIds` entry for a URI the client closed after its last pull:
the closed URI is simply absent from the answer (it is not among
`open_uris()`), never phantom-reported, never an error.
- `a_previous_result_id_for_a_uri_never_seen_is_ignored` — a
`previousResultIds` entry for a URI this server never opened: ignored,
does not disturb the report for URIs that *are* open.
**`applyEdit`-adjacent note:** `diagnostics_of`'s early-return
(`self.workspace.document(uri).map(...).unwrap_or_default()`) means a pull
for an unopened buffer is `Full` with empty `items` rather than `Unchanged`
— checked this always answers `Full` regardless of what `previousResultId`
the client sends for an unopened URI, which is correct (an unopened buffer's
"generation" was never established for that client, so there is nothing to
consider unchanged).
**CLAUDE.md compliance:** no `unwrap()`/`expect()`/`panic!` in the new
non-test code in `server.rs`/`main.rs`; `ClientAbilities::pull_diagnostics`
and `Server::generation`/`applying` (shared with apply-edit) carry doc
comments; `DiagnosticServerCapabilities` construction and
`pull_diagnostics_support` read capabilities defensively
(`.as_ref()`/`.is_some_and()`), confirmed no panic on
`InitializeParams::default()` by the existing test. README has all seven
sections; TODO.md checkbox is checked with item text unchanged.
**Verdict: no blocking findings.** One informational finding recorded above
(Assumptions text describes a coupling that isn't live code yet — cosmetic,
not a defect) for the lead to weigh in on. Three new edge-case tests added,
all passing; the exhaustive input trace found no stale-`unchanged` path.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
clean. One computation (`diagnostics_of`) behind both models, one push gate
(`send_diagnostics`), one generation counter as the whole `resultId` — the
boring shape CLAUDE.md asks for, and QA's exhaustive input trace confirms
the coarse counter cannot produce a stale `unchanged` today.
On QA's informational finding (the Assumptions justify
`inter_file_dependencies: true` via the index, which the diagnostics path
does not read yet): accepted as written. Bumping on reindex is the safe
direction and the semantic-lint roadmap (§9's future rounds, cross-file
rules) is precisely what will make the index a real input; the README
already states the true invariant — *every diagnostic-affecting input bumps
`generation`* — and whoever adds a lint config key or a cross-file rule
inherits it. The `both_models_say_exactly_the_same_thing_about_a_buffer`
test is the right tripwire for divergence. No change requested. Accepted
as shipped.
+227
View File
@@ -0,0 +1,227 @@
# 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.
@@ -0,0 +1,460 @@
# semantic-tokens-delta
## Goal
Serve the two semantic-token requests this server advertised nothing for:
`textDocument/semanticTokens/range`, so the first paint of a large file costs
the visible lines rather than the whole file, and
`textDocument/semanticTokens/full/delta`, so a client that already holds an
answer is told what *changed* instead of being handed the file's whole token
set on every keystroke (TODO.md §9b). Both are the same tokenizer that already
served `full`: the classification pass now produces an intermediate
**absolute** form — line, column, length, type, modifiers — a range answer
filters that form and the one encoder delta-encodes whatever is left, so the
three requests cannot disagree about what a token is. The delta itself is the
standard prefix/suffix trim rust-analyzer uses, with the one invariant that
matters tested as a property: applying the returned edits to the old data
reproduces the new data exactly.
## Assumptions
- **A range answer is a self-contained `SemanticTokens`, not a slice of the
full one.** The relative encoding restarts from the start of the *document*
exactly as a full answer's does; only the tokens outside the range are
missing. So the first kept token's `deltaLine`/`deltaStart` are absolute,
which is why the encoder had to be split out of the classifier rather than
the range answer being a sub-slice of the full one. (A client that pasted a
slice out of a full answer would draw line 40's tokens on line 0 — pinned by
`a_range_answer_re_encodes_from_the_start_of_the_document`.)
- **A token that only overlaps the range is kept whole.** The client asked
which tokens to draw, not where to cut them, and a `length` trimmed to the
range would be a lie about the source. Tokens are single-line by
construction (every span is split at `\n` before encoding — the rule
`no_token_ever_spans_a_line_break` has pinned since the first round), so
"overlap" never has to reason across lines.
- **An empty range answers nothing.** A zero-width range covers no characters,
so nothing intersects it. Without the explicit guard the overlap test
degenerates into *containment* and a collapsed cursor position would answer
with the token it sits inside — tokens the client has no room to draw. No
editor is known to send one; it is guarded because the arithmetic invites it.
- **`resultId`s are minted per answer, from one counter, and are not the
diagnostics generation.** A `previousResultId` must name the exact data the
client holds, which the pull-diagnostics generation cannot do: that one is
bumped by a buffer change *and* by an index rebuild, and it is shared by
every open buffer. This counter counts *answers* — one per full and per
delta, whatever the buffer — so an id is unambiguous and never reused.
Answering the same unchanged buffer twice mints two ids and one empty edit
list; that is a string per answer, not a recomputation.
- **A range answer is deliberately *not* remembered and carries no
`resultId`.** It is a partial view; a later delta computed against it would
be a diff against something the client never held whole. Only `full` and
`full/delta` write the remembered answer.
- **One answer per buffer is remembered, and it dies with the buffer.** A
client that asks again has moved on from the previous answer, so there is no
history to keep. `didClose` drops the entry, so the map is bounded by the
number of *open* buffers, not by the number of files ever opened. A delta
naming an id from before a close is answered in full.
- **Mismatched, absent or stale `previousResultId` → a full answer.**
`SemanticTokensFullDeltaResult` allows either, and a delta against data we
cannot see would be a guess. That is also what makes a server restart, a
client restart and a `didClose`/`didOpen` cycle all self-healing.
- **Minimality beyond the prefix/suffix trim is not attempted.** One
`SemanticTokensEdit` replaces everything between the common prefix and the
common suffix. A real diff would describe an insertion in the middle of a
file as two small edits, but the encoding is *relative*: the first token
after an inserted line carries a changed `deltaLine`, so a "middle"
insertion already invalidates only that one token plus the ones that moved,
and everything below it re-matches as suffix. rust-analyzer answers the same
way. The payload is what the client re-parses, not what it re-renders.
- **The buffer that does not lex still round-trips.** It has no tokens at all
(the lexer is all-or-nothing), so a delta out of it deletes everything and a
delta back into it inserts everything. Mid-keystroke this is the common
case, and it is tested in both directions.
- **`workspace/semanticTokens/refresh` is out of scope and not sent.** That
request exists for the case where the *server* decides the client's tokens
went stale without the client having edited anything — an index rebuild
changing how a name resolves, say. The case that matters (the user typing)
makes the client re-pull on its own. Recorded as backlog below, not built.
## The delta algorithm, and the bug it is easy to write
```
prefix = how many leading tokens are equal
old_rest, new_rest = both lists past the prefix
suffix = how many trailing tokens of old_rest and new_rest are equal
edit = replace old_rest[..old_rest.len() - suffix]
with new_rest[..new_rest.len() - suffix]
```
**The suffix is counted over what the prefix left, never over the whole
lists.** That is the cap, and skipping it is *the* classic bug in this
algorithm: when the two token lists repeat themselves, a suffix counted over
the whole lists claims tokens the prefix has already claimed, and
`new_rest[..new_rest.len() - suffix]` then runs backwards — a panic in debug,
an edit that deletes a region it also re-inserts in the general case.
This is not hypothetical for Verilog. The encoding is relative, so **identical
lines encode to identical tokens**: line 2 and line 3 of
```systemverilog
module m;
wire a;
wire a;
wire a;
endmodule
```
are byte-for-byte the same five numbers. Deleting one of those lines is
exactly the `old = [A, B, A]`, `new = [A]` shape. Both the hand-built shape and
the real-Verilog one are tested (`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`), and both were
confirmed to **fail** — by panic — against a deliberately uncapped
implementation before being committed to.
**`start` and `deleteCount` count numbers, not tokens.** The wire carries a
flat `u32` array of five numbers per token, and an edit indexes *that*. Both
are five times a token index (`FIELDS`), pinned by
`an_edits_indices_count_numbers_and_not_tokens` — the off-by-five here does not
fail loudly, it silently corrupts a client's cache.
## Handshakes
**Consumed from `lsp-types` (0.97, no new dependency):**
`SemanticTokensRangeParams`, `SemanticTokensRangeResult`,
`SemanticTokensDeltaParams`, `SemanticTokensFullDeltaResult`,
`SemanticTokensDelta`, `SemanticTokensEdit`, and — for the capability —
`SemanticTokensOptions { range: Option<bool>, full: Option<SemanticTokensFullOptions> }`
with `SemanticTokensFullOptions::Delta { delta: Some(true) }`. The `Delta`
variant is the full capability *plus* deltas, not a replacement:
`semanticTokens/full` is still served and still answered.
**Consumed from other crates: nothing new.** `vlog_parser`, `vlog_semantic`,
`vlog_formatter`, `vlog_refactor`, `lucisv_core` are untouched, as is every
file outside `crates/lucisv_server`. This feature is protocol arithmetic over a
classification that already existed.
**Changed inside this crate, for whoever reads `tokens.rs` next:**
- `tokens::semantic_tokens(doc)` now returns `Vec<SemanticToken>` (the `data`)
rather than a whole `SemanticTokens`. The `resultId` is the server's to
stamp, because only the server knows what it remembered — the module owns
no state.
- New: `tokens::semantic_tokens_in_range(doc, range) -> Vec<SemanticToken>`
and `tokens::delta(old, new) -> Vec<SemanticTokensEdit>`.
- Private and new: `Absolute` (line, start, length, type, modifiers),
`absolute(doc)`, `flatten(pieces, doc)`, `within(tokens, range)`,
`encode(&[Absolute])`. `encode` is pure — the same tokens always encode the
same way, whether they are the whole file's or the handful a range kept —
which is what lets `full` and `range` share it.
- `Server` gains `tokens: HashMap<Uri, TokenAnswer>` and `token_results: u64`,
written only by `remember_tokens` and cleared only by `didClose`. **Neither
touches `generation`**: every token request is read-only, and bumping the
diagnostics generation on a viewport repaint would throw away a pulling
client's whole diagnostic cache several times a second
(`no_token_request_bumps_the_diagnostics_generation`).
**Requested of other modules:** nothing.
## Status / TODO
- [x] `tokens.rs` split into classification → `Absolute` → filter → `encode`,
with `full` and `range` sharing all four steps.
- [x] `textDocument/semanticTokens/range`, advertised as `range: Some(true)`,
re-encoded from the document start, overlap kept whole, empty range
empty.
- [x] `textDocument/semanticTokens/full/delta`, advertised as
`full: Delta { delta: Some(true) }`, single-edit prefix/suffix diff with
the suffix capped.
- [x] Per-buffer `resultId` bookkeeping: minted per answer, stored by both
`full` and `full/delta`, dropped on `didClose`.
- [x] `semanticTokens/full` returns a `resultId` now (it did not before), so a
client may mix the two requests.
- [x] Round-trip property tests: append, delete, middle change, identical,
complete replacement, unlexable buffer both ways, empty buffer both
ways, the prefix/suffix-overlap shapes, and a 300-iteration fixed-seed
randomized sweep over real Verilog buffers.
- [x] Range/full agreement as a property over two corpus files, in 40-line
windows (the size of an editor viewport request), stated line-wise so it
is independent of the handler's own overlap test.
- [x] Server-level tests through the `Session` harness, and one e2e round trip
through the real binary.
- [x] TODO.md §9b box, this README, and the `lucisv-server` capability table.
- [ ] **Not done, deliberately:** `workspace/semanticTokens/refresh`. Nothing
the server learns on its own (an index rebuild changing how a name
resolves) currently invalidates a client's token cache; when something
does, this is the request to send.
- [ ] **Not done:** partial results / `workDoneProgress` on any of the three
requests. The whole-file answer is sub-millisecond at Verilog file
sizes; streaming it in chunks would be complexity for nobody.
- [ ] **Not measured:** whether the delta payload is actually smaller than the
full one for a typical edit. It must be by construction for an edit near
either end of a file, and it is at worst the full set plus one edit
header for an edit near the middle. No benchmark was written.
## Work log
### 2026-08-26 — dev agent
- **Read first**: `CLAUDE.md`, `docs/features/lucisv-server/README.md` (the
capability table and the `semanticTokens` mapping section),
`docs/features/pull-diagnostics/README.md` for the house style on result
ids, `tokens.rs` in full, and `lsp-types` 0.97's `semantic_tokens.rs` for
the exact shapes (`range` is a plain `Option<bool>` there, not an options
struct; `SemanticTokensFullDeltaResult` has three variants and we use two).
- **The refactor came before either handler.** `semantic_tokens` was one
function doing classification, line splitting, sorting and delta encoding,
and the range answer needs to cut in between the third and the fourth. It
is now `absolute(doc)` (classify + split + sort, producing `Absolute`),
`within(tokens, range)` (the filter) and `encode(&[Absolute])` (pure delta
encoding). The eleven pre-existing token tests were left with their
assertions untouched — only the test *helpers* moved, because
`semantic_tokens` now hands back the `data` rather than a `SemanticTokens`
— which is the evidence that the factoring changed no behavior.
- **The overlap cap was verified by breaking it, not by reasoning.** After
writing the capped `delta`, the suffix computation was temporarily changed
to count over the whole lists and the suite re-run: three tests failed with
a subtraction-overflow panic
(`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` via the shared
round-trip helper, and `every_pair_of_real_buffers_round_trips_through_its_delta`
— the randomized sweep found it on its own, which is why the `BODY` line
pool deliberately repeats `" wire a;"`). The implementation was then
restored. CLAUDE.md's invariant #4 is about `verify.rs`, but its spirit —
a normalization ships with the attack that would forgive a corruption —
is what this check is.
- **The one design decision that is not the obvious one**: a range answer
carries no `resultId` and is not remembered. It would have been one line to
remember it, and it would have silently made the next delta a diff against
a partial view. Written down in Assumptions and pinned by
`a_range_request_is_not_the_answer_a_later_delta_is_computed_against`.
- **The empty-range guard was written for the arithmetic, not for a client.**
`from < range.end && range.start < to` is the interval-overlap test only
when the range is non-empty; for a collapsed range it is containment. One
early return, one test, one sentence in Assumptions.
- **`generation` was deliberately not touched**, and the test for it says so
twice: directly on the field, and observably through a pull that is still
`unchanged` after a token request. Pull diagnostics' README asks every new
feature to audit whether it bumps the generation; the audit's answer here
is no, and this is where it is recorded.
- **Nothing outside this crate moved.** No new dependency, no version bump,
no engine change, no `editors/` change (`smoke.js`'s capability list already
contains `semanticTokensProvider`, and it passes against the built binary).
- **Results.** `cargo test --workspace`: **1793 passed, 0 failed** (1764
before — +29: 18 unit tests in `tokens.rs`, 9 in `server.rs`, 1 in
`main.rs`, 1 e2e). `cargo clippy --all-targets`: silent.
`cargo fmt --all -- --check`: clean. `cargo build && node
editors/vscode/smoke.js target/debug/lucisv-server`: OK. No commits.
## QA log
### 2026-08-26 — QA agent
**Gates re-run, from a clean rebuild** (`touch`ed the three changed source
files first so clippy could not reuse a stale cached pass):
`cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace
-- -D warnings`: silent. `cargo test --workspace`: **1793 passed, 0 failed**
before QA's own additions, **1802 passed, 0 failed** after (9 QA tests added,
see below). `cargo build && node editors/vscode/smoke.js
target/debug/lucisv-server`: OK. All match the dev's claims.
**1. The delta invariant, independently — verified clean, tests added.**
Wrote a second applier, `independent_apply` (`tokens.rs`, in `mod tests`),
that shares no code with the dev's `apply_edits`: it walks `SemanticToken`s
rather than the flat `u32` array, slices by hand (`extend_from_slice`)
rather than calling `Vec::splice`, and separately asserts `edit.start` /
`edit.delete_count` divide evenly by `FIELDS` — a second, independent check
of the ×5 claim. Cross-checked the two appliers directly against each other
over 200 random pairs (`qa_the_two_independently_written_appliers_never_disagree`)
— **they never disagreed**. Ran QA's applier over: both ends changing at
once, middle-only, identical, complete replacement, old empty, new empty,
and a single-token file, both directions
(`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`).
Ran a second randomized sweep, different generator (xorshift64, not the
dev's LCG), different seed (`0xDEAD_BEEF_1234_5678` vs `0x5eed`), and a
different line pool that adds a block comment spanning lines, a continued
`` `define``, and a `generate`/`endgenerate` block — pieces whose token
*count* is not simply one-line-in-N-tokens-out
(`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`).
All green. **Verdict: verified clean.**
**2. The overlap cap, re-verified — reproduced, with one correction to the
work log's specifics.** Reproduced the dev's breakage myself: changed the
suffix computation in `delta` (`tokens.rs:304-305` at the time) from
counting over `old_rest`/`new_rest` to counting over the whole `old`/`new`,
re-ran `cargo test -p lucisv_server`, and restored it — the file is back to
its pre-experiment text (diffed against git to confirm no leftover debug
code). Result: **10 tests failed** by `attempt to subtract with overflow`
panic, including `the_suffix_is_capped_so_it_cannot_overlap_the_prefix`, the
dev's own sweep `every_pair_of_real_buffers_round_trips_through_its_delta`,
and — usefully — all of QA's own new round-trip tests from surface 1 above,
which is exactly the cross-check CLAUDE.md invariant #4 asks for (an
independently-written attack finding the same class of bug). **One
correction**: the work log names
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` as one of the
three tests that failed in the dev's own experiment. Re-running the same
breakage, this specific test **passes** — traced with a temporary debug
print (`old.len()=9 new.len()=5 prefix=4 suffix=1` and the mirror), the
type/declaration-modifier mismatch a few tokens in breaks the naive
whole-list suffix match before it ever grows past `old_rest`'s length, so no
overflow occurs for this particular buffer pair under this literal
interpretation of "count over the whole lists." This is a documentation
accuracy nit, not a safety finding — the class of bug is still real and
still demonstrated by the other two named tests plus QA's own — but the dev
should either soften the claim (the failure was seen at the time, with
whatever the code looked like then, or via a different breakage) or drop
that one test's name from the sentence. **Then tried to construct a shape
that defeats the capped implementation and produces wrong data instead of a
panic**: with the cap in place, `suffix = old_rest.iter().rev().zip(new_rest.iter().rev())…`
is inherently bounded by `min(old_rest.len(), new_rest.len())` because
`Iterator::zip` itself stops at the shorter side — so `deleted =
old_rest.len() - suffix` can never underflow, and the algebra (`old[:prefix]
+ inserted + old_rest[deleted..]` reduces to exactly `new`) holds
unconditionally, not just on the tested shapes. Tried anyway: long shared
prefix and long shared suffix overlapping in the middle over periodic data
(the `[A,A,A,A,A]` → `[A,A,A]` shape, and variants with the periodic run at
different positions) — all round-trip correctly, consistent with the
argument above. **Verdict: verified clean; the cap is load-bearing (10
failures without it) and, with it, the round-trip property holds by
construction, not merely on the cases anyone thought to test.**
**3. u32 semantics — verified clean.** `an_edits_indices_count_numbers_and_not_tokens`
(dev's) and QA's own `independent_apply` (which asserts `% FIELDS == 0`
before dividing, on every edit, in every test above, including the 500
combined sweep iterations) agree the ×5 conversion is exact and consistently
applied. Wire shape: an unchanged buffer answers `edits: []` (present, empty
— `a_delta_over_an_unchanged_buffer_is_an_empty_edit_list`,
`server.rs:2508`) and a stale/unknown/absent-state id answers the
`Tokens` variant with no `edits` key at all
(`a_delta_naming_an_id_we_do_not_hold_is_answered_in_full`) — both legal per
`SemanticTokensFullDeltaResult`'s untagged enum, and both are pinned by
existing tests, not left to accident.
**4. Range self-containment — verified clean, gaps closed with new tests.**
The dev covered: full-document range, absolute first-token deltas, overlap
kept whole at the *start* boundary, empty range, whitespace-only *lines*,
range never leaking outside tokens, and a 40-line-window corpus sweep (which
QA re-ran directly against the checked-out `corpus/` — genuinely exercised,
not skipped: `windows_checked` well over 20). QA added the three shapes the
list asked for that were not yet pinned: (a) overlap kept whole at the *end*
boundary, mirroring the dev's start-boundary test
(`qa_a_range_ending_mid_token_keeps_that_token_whole`); (b) a range on a line
*with* tokens, covering only the whitespace (plus an unemitted `=`) between
two of them — not an empty line
(`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`);
(c) a reversed range (`start > end`) — `within`'s guard
(`range.start >= range.end`) is symmetric to this by construction since
`Position` derives `Ord` over `(line, character)` lexicographically, so this
was already total and already answered empty, but nothing pinned it before
now (`qa_a_reversed_range_is_total_and_answers_nothing`). All pass.
**Verdict: verified clean.**
**5. State lifecycle — verified clean, two gaps closed with new tests.** The
dev covered: didClose+reopen with the old id → full, memory dropped on
close (`server.rs:784`, `self.tokens.remove(&uri)`, confirmed keyed by
`Uri` and removed, not just marked stale), and the unopened-buffer → null
convention for all three request kinds
(`every_token_request_for_a_buffer_that_is_not_open_answers_null`, which
also asserts the map stays empty). QA added: (a) two buffers open at once,
buffer A's id presented to buffer B — answered in full, not edits computed
against A's data, and closing A leaves B's own remembered state untouched
(`qa_two_open_buffers_ids_do_not_cross_contaminate`); worth noting as a
observation rather than a bug: presenting a foreign id to B *does* mint a
fresh id for B and overwrite B's own remembered answer (every answer does,
by design — "Answering the same unchanged buffer twice mints two ids"), so
the first version of this test asserted something the design doesn't
promise (that `id_b` keeps working) — fixed once understood, noted here so
the next reader doesn't trip on the same assumption. (b) `full → delta →
full → delta → full` stays consistent across three edits
(`qa_full_delta_full_delta_stays_consistent_across_edits`), and separately,
a `full/delta` answer's *own* `resultId` chains directly into the next delta
without ever going back through `full`
(`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`)
— checked against `ground_truth`, a helper that reads the document straight
through `tokens::semantic_tokens` and bypasses the request dispatch (and
thus the very `tokens`/`token_results` bookkeeping under test) entirely, so
the check does not depend on the server's own memory being right. All pass.
**Verdict: verified clean.**
**6. No behavior change for existing clients — verified clean, two ways.**
(a) Direct code comparison: `classify`, `modifiers`, `identifier_type`,
`symbol_type`, `collect_trivia`, `split_lines`, `token_types` and
`token_modifiers` are byte-for-byte identical between
`git show 80b9afd:crates/lucisv_server/src/tokens.rs` and the new file; the
new `flatten`+`encode` pair is the old single `encode` function split at
exactly the line-splitting/sorting boundary, with no logic added or
removed. (b) Empirical, at the binary level: built the pre-refactor commit
in a separate worktree (`git worktree add`, removed after), drove both the
old and the new `lucisv-server` binaries over stdio with the same
`textDocument/semanticTokens/full` request against a real corpus file
(`corpus/picorv32/picorv32.v`, 41,325 tokens), and diffed the `data` arrays:
**byte-for-byte identical**; the only difference in the response is the new
`resultId` field, which the old binary did not send at all. The legend
(`token_types`/`token_modifiers`) is likewise unchanged (confirmed both by
the code diff and by `the_semantic_token_capability_asks_for_ranges_and_for_deltas`
asserting length 14). **Verdict: verified clean — this is about as strong
as evidence gets for "the refactor changed no behavior."**
**7. CLAUDE.md compliance — verified clean.** `grep`-checked all non-test
code in `tokens.rs`, `server.rs`, `main.rs` for `.unwrap()`, `.expect(`,
`panic!`: none. No `#[allow]` added anywhere in the diff. No `unsafe`
anywhere in the diff. The two new public functions
(`semantic_tokens_in_range`, `delta`) both carry doc comments explaining
what/why. The feature README has each of the six required sections exactly
once (plus one extra, non-required "The delta algorithm…" section, which is
additive and not a substitute for any required one). `TODO.md`'s item text
is unchanged save the checkbox and an appended `→` summary — the original
sentence is intact verbatim.
**Fixes made directly (small, per the QA remit):** none needed in the
dev's own code — every finding above was either "verified clean" or a
documentation-accuracy nit (item 2) recorded rather than edited, since
CLAUDE.md reserves the Work log for the dev agent's own account of what it
did and why, and the specific breakage the dev saw is not reproducible
after the fact to know which description would be truer. QA did fix one bug
in **QA's own** first draft of `qa_two_open_buffers_ids_do_not_cross_contaminate`
(a wrong assumption about `id_b` surviving a cross-request, see item 5)
before it ever reached this log.
**Tests added this round:** 9, all passing, workspace total 1793 → 1802.
`tokens.rs`: `qa_the_two_independently_written_appliers_never_disagree`,
`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`,
`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`,
`qa_a_range_ending_mid_token_keeps_that_token_whole`,
`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`,
`qa_a_reversed_range_is_total_and_answers_nothing`. `server.rs`:
`qa_two_open_buffers_ids_do_not_cross_contaminate`,
`qa_full_delta_full_delta_stays_consistent_across_edits`,
`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`.
**Overall verdict: committable as-is.** No corruption, non-idempotency,
dropped-comment, or safety-net-widening risk found — this feature does not
touch `verify.rs`, the formatter, or anything outside `crates/lucisv_server`,
and every claim in the dev's work log checked out except the one test name
in item 2, which is cosmetic. All gates green, all new and old tests green,
one empirical binary-level spot check green.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
(1802 workspace tests, 0 failed), clean. The refactor is the right seam:
one tokenizer, one pure encoder, and range/full provably cannot drift —
QA's byte-for-byte comparison of a 41k-token corpus file against the
pre-refactor binary is the strongest possible form of "the factoring
changed nothing". The delta design's judgment calls are all correct:
range answers carrying no resultId (a delta must never diff against a
partial view), a per-answer counter separate from the shared diagnostics
generation, and prefix/suffix-with-cap over anything cleverer — with the
round-trip property, not minimality, as the contract.
Two QA results deserve the record: the two independently written edit
appliers never disagreed across 200 random pairs, and the overlap cap was
broken on purpose twice (dev and QA separately) with the suite catching
it both times. One cosmetic correction accepted from the QA log: the work
log names `repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`
among the tests that fail with the cap reverted; QA's re-run shows that
particular pair breaks the match earlier and that test passes — the trap
is real but is caught by the other ten failures. The work log stands as
the dev's account, with the QA log as the precise version. Accepted as
shipped.
@@ -0,0 +1,388 @@
# will-save-wait-until
## Goal
Serve `textDocument/willSaveWaitUntil`, the protocol's own format-on-save hook:
the client asks the server for edits *before* it writes the file, waits for the
answer, and applies whatever comes back. VS Code users already have
`editor.formatOnSave`, which runs the ordinary `textDocument/formatting`
request — this exists for the editors that have no format-on-save of their own,
and for users who would rather the server owned the decision than their editor
config. Because a capable client sends this on **every** save of every buffer,
and because a server that formats uninvited would fight (and double up on) an
editor that already formats, the hook is gated on a new `lucisv.formatOnSave`
setting that is **off** by default and answers `null` in one comparison. When it
is on, this is `textDocument/formatting` with a different trigger — the same
engine, the same settings, the same all-or-nothing contract (CLAUDE.md
invariant #1) — so a save can never write anything a manual format would not.
## Assumptions
- **Off by default, and the decline is cheap.** `lucisv.formatOnSave` unset,
`false`, or wrong-typed all mean off. The handler returns `null` before it
looks at the buffer, the workspace, or a `lucisv.toml`. The safe direction for
a setting that rewrites the user's file on every save is the one that does
nothing, so a value that is not the JSON boolean `true` is dropped exactly as
every other wrong-typed setting in `settings.rs` is.
- **A plain `bool`, not an `Option<bool>`.** Every other field of
`ClientSettings` is "no opinion until a client says otherwise" because it has
a rung below it to fall through to. This one does not: unset and off are the
same answer, and there is no `lucisv.toml` key for it (the config file
describes *style*, and whether an editor formats on save is not style — it is
an editor behavior, and it belongs to the person at the editor).
- **Every save reason formats.** `Manual`, `AfterDelay` and `FocusOut` all
write the file, and a user who asked for their saves to be formatted asked
about all three. The `reason` field is decoded and deliberately not read. A
future knob could restrict it; none is built, because no one has asked for one.
- **The text is the buffer the server holds.** The request carries no text — it
arrives *before* `didSave`, and before the client has written — so what gets
formatted is what `didOpen`/`didChange` built. That is the same text every
other request in this server answers from. A buffer the server does not hold
answers `null` rather than reading the file from disk: the file on disk is
precisely the stale copy the save is about to replace.
- **No `tabSize` on this path, and it can differ from a manual format.** The
protocol sends `FormattingOptions` with `textDocument/formatting` and
`rangeFormatting`; it sends nothing of the sort with `willSaveWaitUntil`. So
the settings ladder in `format::settings_for` runs with rung 3 missing —
`lucisv.toml` > `lucisv.indent` > the built-in 2 — exactly as it already does
for a lint fix's indent (`format::indent_width`). **Honest consequence:** a
user with no `lucisv.toml` and no `lucisv.indent`, whose editor tab size is 4,
gets 4-space indent from a manual format and 2-space indent from a save. That
is a gap in the protocol, not a bug we can close from here — the request
simply does not carry the number — and the fix a user has is to say what they
want once, in a `lucisv.toml` or in `lucisv.indent`. It is written down in
`editors/vscode/package.json`'s setting description and in
`editors/nvim/README.md` so nobody has to discover it by diffing a save.
- **A formatter refusal is shown on every save, on purpose.** `edits()` is
reused unchanged, so an unparsable buffer produces no edit and one ERROR
message — per save, not once per file change. The alternative (dedup, the way
`warn_about_config` dedups a broken `lucisv.toml`) was rejected: that warning
is about a *config file* the user is not editing, while this is about the save
the user just performed. A save the user asked to be formatted, that was not
formatted, is worth saying every time it happens; going quiet would leave the
user believing their file was formatted when it was not. The repetition is
bounded by the user's own saves, and the broken-config warning keeps its
dedup — though QA sharpened what that dedup actually is (see the QA log):
it is cleared by `set_document`, so a save whose own edit comes back
through `didChange` re-arms it for the *next* save. Once per buffer
state, not once per broken config; still bounded by the user's saves
either way.
- **The capability is advertised unconditionally**, even though the default
answers `null`. It has to be: the setting can be pushed mid-session, and
`initialize` is the only time the sync options are sent. A client whose user
never turns it on pays one round trip per save for a `null`.
- **`willSave` (the notification) stays unadvertised.** It carries no reply, so
there is nothing this server could do with it that `didSave` does not already
cover.
## Handshakes
- **Consumes `format::settings_for` / `format::formatting`** — the same two
calls `Server::formatting` makes, in the same order, so the two paths cannot
drift. Added one function to `format.rs`,
`settings_without_editor_options(doc, client)`, which is `settings_for` with
a `FormattingOptions` that opts out of rung 3 (hard tabs, zero width — values
`config_from` already refuses). It is the options-less sibling of
`indent_width`, and it lives in `format.rs` so the reasoning about the
precedence ladder stays in one file.
- **Consumes `Server::edits`** unchanged — the all-or-nothing reply shape, and
the ERROR message on a refusal. `Ok(None)` becomes `[]`, matching what
`textDocument/formatting` answers for an already-formatted buffer; a test
asserts the two are byte-identical rather than merely equivalent.
- **Consumes `Server::warn_about_config`** unchanged — a broken `lucisv.toml`
is reported once per buffer state (the dedup is cleared by `set_document`;
see the Assumptions bullet and the QA log for the exact bound), which keeps
a save loop that changes nothing from repeating it.
- **Adds one field to `settings::ClientSettings`** (`format_on_save: bool`,
from `lucisv.formatOnSave`). `Workspace::set_client_settings` needed no
change: the field moves no files, so it does not ask for a reindex, and it is
read afresh by each save exactly as `indent`/`lineLength` are read afresh by
each format.
- **Changes what the client is told at `initialize`:**
`text_document_sync.will_save_wait_until` moves from `None` to `Some(true)`.
Nothing else in the sync options moves — `will_save` stays `None`,
`change: INCREMENTAL` and `save.includeText: false` are untouched — so no
client's sync or save behavior changes beyond gaining one request it may now
send.
- **Editor packaging:** `lucisv.formatOnSave` declared in
`editors/vscode/package.json` (default `false`); no `extension.js` change was
needed, because the client already pushes the whole `lucisv` section
(`synchronize.configurationSection: 'lucisv'`) and `vscode-languageclient`
registers the will-save feature from the advertised capability on its own.
`editors/nvim/README.md` documents the setting next to the `BufWritePre`
autocmd it is an alternative to, including the tab-settings caveat above.
- **No other crate is touched, and no new dependency.**
## Status / TODO
- [x] Advertise `will_save_wait_until: Some(true)`; leave `will_save` `None`.
- [x] `lucisv.formatOnSave` in `settings.rs`, default off, wrong types dropped.
- [x] `WillSaveWaitUntil` arm in the request dispatch + `will_save_wait_until`
handler: off → `null`, unopened → `null`, on → the formatting path.
- [x] `format::settings_without_editor_options` — the ladder with no `tabSize`
rung.
- [x] Reuse `edits()` and `warn_about_config()` unchanged.
- [x] Settings unit tests (present true/false, absent, wrong types, the
default VS Code payload).
- [x] `format.rs` unit test for the options-less ladder.
- [x] Server-level tests: off → `null` and silent; on → the edit; identical to
what `textDocument/formatting` answers; every save reason; unopened
buffer; already-formatted buffer → `[]`; unparsable buffer → no edits +
one ERROR per save; setting toggled on and off mid-session.
- [x] Idempotency guard: apply the edit, ask again, get no edits.
- [x] e2e: the capability on the wire, the push, the edit, the second save.
- [x] `editors/vscode/package.json` + `editors/nvim/README.md`.
- [x] `docs/features/lucisv-server/README.md` capability table.
- [x] TODO.md §9b item checked off.
## Work log
**2026-08-26 — dev.** Implemented in one round; no deviations from the plan.
- **`main.rs`**: one field of the existing `TextDocumentSyncOptions` moved,
`will_save_wait_until: None` → `Some(true)`, with the reasoning in a comment
next to it. New test `the_sync_options_ask_for_the_save_hook_and_not_the_
notification` pins both that and `will_save: None`, since "advertise exactly
what we implement" is the rule that block already lives by.
- **`settings.rs`**: `format_on_save: bool`, parsed with the existing `flag()`
helper plus `.unwrap_or(false)`. Chose `bool` over `Option<bool>`
deliberately — see Assumptions; the type says "unset is off", which is the
actual semantics, and it keeps every reader from writing
`.unwrap_or(false)` at the use site. The `vscode_payload` test helper gained
`"formatOnSave": false` so it stays the real shape of what the extension
pushes, and `the_default_vscode_payload_is_no_opinion_about_anything` still
passes unchanged (the default *is* the `Default` value).
- **`format.rs`**: `settings_without_editor_options`. The alternative —
calling `settings_for` with `FormattingOptions::default()` from the handler —
works (its `insert_spaces: false` makes rung 3 inert), but it makes
server.rs depend on a default value being inert somewhere else. A named
function with the reasoning attached costs three lines and makes the
precedence decision greppable from the module that owns precedence.
- **`server.rs`**: one dispatch arm and one handler. The handler is five
statements and reads top to bottom: setting → buffer → settings → format →
warn → `edits()`. The setting check comes *first*, before the workspace
lookup, because the decline is the hot path — this arrives on every save.
- **The error-on-every-save decision** was the one real judgement call; it is
argued in Assumptions and pinned by
`a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`,
which drives two saves and asserts exactly one ERROR each time. If a user
ever complains, the change is a dedup keyed on (uri, generation) — but
guessing at that now would mean shipping silence for a failed save, which is
the worse failure.
- **Tests: 1 settings unit + 1 format unit + 1 capability unit + 7
server-level + 1 e2e = 11 new.** The idempotency guard
(`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`) applies
the returned edit through a real `didChange` and asserts the next save has
nothing to do — the formatter's own invariant #2, asserted through this new
path rather than assumed from the engine's suite. The byte-identity test
(`the_save_hook_answers_exactly_what_the_formatting_request_answers`)
compares the two JSON results directly; it is what would catch the two paths
drifting apart.
- Nothing outside `crates/lucisv_server` changed in code. The three
documentation/packaging files touched outside this feature dir
(`TODO.md`, `docs/features/lucisv-server/README.md`,
`editors/vscode/package.json`, `editors/nvim/README.md`) are additions in the
house style; no QA log or Review section anywhere was edited.
## QA log
**2026-08-26 — QA.** Re-ran all gates, then attacked the six surfaces the lead
called out plus one I found on my own. No masked-corruption test was needed
(CLAUDE.md invariant #4): this feature touches nothing in `verify.rs` and adds
no new normalization to it. **Verdict: committable as-is.** Five findings
below, none blocking — one small fix made directly (pre-authorized), four are
new regression tests that now guard behavior the dev's suite did not exercise,
plus one real documentation gap for the dev to word better (not a code fix).
**Gates, re-run clean:**
- `cargo fmt --all -- --check` — clean.
- `cargo clippy --all-targets --workspace` — clean, no warnings.
- `cargo test --workspace` — all green (643 in the `lucisv_server` unit binary
after my additions, up from the dev's 638; every other crate unchanged and
green).
- `cargo test -p vlog_formatter` — 114 passed.
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` —
`smoke: OK`.
**A. Hard invariants ride through the new path — verified clean.**
- (a) No partial output on a refusal: structural, not just tested —
`format::formatting` (`format.rs:83-89`) uses `?` on `format_source`'s
`Result` before it ever constructs a `TextEdit`, so an `Err` cannot reach an
edit. `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`
(`server.rs`) confirms it end to end: `[]` plus one ERROR, twice.
- (b) The runtime safety net runs inside this path: read the call chain —
`Server::will_save_wait_until` → `format::formatting` (`format.rs:83`) →
`vlog_formatter::format_source` (`crates/vlog_formatter/src/format.rs:80`),
which calls `verify_equivalence` then reformats and calls
`verify_convergence` before returning `Ok`. This is the exact same call
`Server::formatting` makes (`server.rs:410` vs `server.rs:463`) — same
function, same arguments shape, no bypass.
- (c) The idempotency guard is real, not string arithmetic:
`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` sends a
genuine `textDocument/didChange` notification through
`Session::notify`/`Server::notification` (the real dispatch), which lands in
`set_document` (`server.rs:816`) exactly as an editor's own edit would, and
then re-asks `willSaveWaitUntil` against the workspace's own copy of the
buffer. Confirmed by reading `change()`/`buffer()` (`server.rs:1821-1834`) —
they are the same helpers the pre-existing incremental-sync suite uses.
**B2. Byte-identity and the tab-size asymmetry — verified clean, gap
confirmed real by test, not just documented.** Added two tests to
`server.rs` (`the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`,
`a_lucisv_toml_erases_the_tab_size_gap`) that construct exactly the case the
README's Assumptions section describes: no `lucisv.toml`, no
`lucisv.indent`, editor `tabSize: 4` — manual format indents 4
(`config_from`'s rung 3), the save hook indents 2 (the built-in default,
since `settings_without_editor_options` sends `insert_spaces: false`, which
short-circuits rung 3's `options.insert_spaces && INDENT_RANGE.contains(...)`
check in `format.rs:162` regardless of the tab size carried). With a
`lucisv.toml { indent = 4 }` present, the two paths land on byte-identical
JSON even when the manual request's `tabSize` is 8 — rung 1 outranks both.
This matches the README exactly; nothing to fix.
**B3. Setting plumbing — verified clean, plus one gap closed.**
- `vscode_payload`'s shape matches `extension.js`'s actual
`synchronize: { configurationSection: 'lucisv' }` (`editors/vscode/extension.js:68`,
unmodified by this diff) and `DidChangeConfigurationParams::settings`'s
unwrap in `server.rs`'s notification handler — traced, matches.
- Mid-session toggle both directions: `the_save_hook_declines_until_format_on_save_is_pushed`
covers on then off. Wrong types (`"true"`, `1`, `null`, `[true]`,
`{"on": true}`) → off, no panic: `format_on_save_is_off_until_a_client_asks_for_it`
(`settings.rs`) — ran clean.
- Reindex / generation: `set_client_settings` (`state.rs:163-168`) computes
its rescan bool from `exclude`/`filelist` equality only, so a `format_on_save`
change can never trigger it — verified by reading the code, but the dev's
own `only_an_exclude_change_asks_for_a_rescan` test (`state.rs`) predates
this field and so never actually exercised it (it builds
`ClientSettings { line_length, indent, ..Default::default() }`, which
defaults `format_on_save` to `false` either way — a no-op assertion for this
field). **Finding (low severity, fixed directly):** extended that test with
an explicit `ClientSettings { format_on_save: true, ..Default::default() }`
case (`state.rs`). Also added
`toggling_format_on_save_neither_rescans_nor_bumps_the_generation`
(`server.rs`) at the session level, asserting `session.server.generation`
is unmoved by a `formatOnSave` push in either direction — this is what
would catch it bumping a pull-diagnostics client's `resultId` for free.
All new assertions pass against the dev's code unchanged; this was a test
gap, not a behavior bug.
**B4. Error-spam decision — verified clean, plus one real finding on the
"warns once" framing.**
- Two saves of an unparsable buffer → exactly two ERRORs: already covered by
the dev's `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`.
Confirmed passing, no changes needed.
- formatOnSave on + buffer fine + broken config → formats with defaults,
warns once: added `a_broken_config_still_saves_with_defaults_and_warns_once`
(`server.rs`). Had to build it carefully — see the finding below.
- **Finding (moderate, not fixed — needs a documentation call from the dev,
not a code change).** "Warns once" (Assumptions, work log) is **not**
once-per-broken-config; it is once-per-buffer-state.
`warn_about_config`'s dedup (`config_warnings: HashSet<Uri>`) is cleared by
`set_document` (`server.rs:816-817`, doc comment: "re-arming its
`lucisv.toml` warning"), and `set_document` is exactly what runs when the
client applies a save hook's returned edit and the resulting `didChange`
reaches the server — the same sequence
`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` already
models on purpose. So: a save that itself needs reformatting under a
broken config warns on save 1, and warns **again** on save 2 (because the
intervening apply-and-write re-armed the dedup), and only goes quiet from
save 3 onward once the buffer stops changing. Proved by a new test,
`a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save`
(`server.rs`) — three saves, shown-counts 1, 1, 0. This is consistent with
`warn_about_config`'s own doc comment ("once per change of a file"), so it
is not a bug against that contract; it is the save-hook feature's own
Assumptions prose ("warns once") reading as a stronger guarantee than the
mechanism actually gives. Left to the dev to reword — a single edit to the
Assumptions bullet, not a behavior change, and QA does not redesign.
- Interaction case is otherwise as documented: single-edit-free saves (the
buffer already at the fallback default) stay deduped indefinitely, which is
the common case a per-save-loop actually cares about.
**B5. Capability shape on the wire — verified clean, no strengthening
needed.** The new e2e test pins `willSaveWaitUntil: true` and `willSave`
absent (`sync.get("willSave").is_none()` — checked against the JSON, not a
Rust `Option`, so this really is "key missing" and not "key present as
`null`" — confirmed against `lsp-types`' `#[serde(skip_serializing_if =
"Option::is_none")]` on both fields). `change: 2` / `openClose: true` /
`save.includeText: false` are **not** re-pinned in the new test, but they
already are, unmodified, by the pre-existing
`incremental_changes_land_the_same_buffer_as_one_full_change`-adjacent e2e
test (`crates/lucisv_server/tests/e2e.rs:2805-2808`) against the same
`initialize` response shape — the two tests together pin the complete set
this attack surface asks for. Nothing to strengthen.
**B6. CLAUDE.md compliance — verified clean.**
- No `unwrap()`/`expect()`/`panic!()` outside `#[cfg(test)]` in any of
`format.rs`, `main.rs`, `server.rs`, `settings.rs` — checked by line number,
every hit is inside a `mod tests` block.
- Doc comments present on `settings_without_editor_options` (`format.rs:63-71`)
and the `format_on_save` field (`settings.rs:47-53`) — both explain why, not
just what.
- `grep -c '^## ' docs/features/will-save-wait-until/README.md` → 7 matches,
one per section (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA
log, Review — "Status / TODO" and each of the six headers count once each);
no duplicates.
- `TODO.md`'s §9b item text is untouched — only the checkbox flipped and an
indented `→ ...` continuation appended, the same pattern every other
checked-off item in that file already uses.
- `editors/vscode/package.json`'s new entry sits between `inlineTemplates` and
`lineLength`, matching the file's feature-introduction ordering (not
alphabetical — confirmed against the surrounding keys); `editors/nvim/README.md`'s
new section matches the surrounding prose voice.
**C. Pre-authorized small fix — done.** Checked `main.rs`'s `capabilities()`
against `editors/nvim/README.md:101-102`'s claim ("Not advertised by the
server ... range formatting, completion, rename, signature help, and
cross-file references"): false for all four named capabilities —
`document_range_formatting_provider`, `completion_provider`, `rename_provider`,
and `signature_help_provider` are all `Some(...)` in `capabilities()`
(`main.rs`, unchanged by this feature). Fixed the two lines to state that all
four are advertised and Neovim's built-in client wires them up with no extra
config, dropping the stale "your client will correctly refuse them" claim.
Left `cross-file references` out of the corrected line — it was never a
capability separate from `references_provider` (which *is* advertised); the
real limitation is the in-file-only scope already stated two lines above
(line 96), so restating it here as "not advertised" would have been wrong in
a different way.
**D. Beyond the list — nothing further broken.** Checked and found clean,
no test added (already structurally impossible or already covered):
`TextDocumentSaveReason` is `#[serde(transparent)]` around a bare `i32`
(`lsp-types-0.97.0`), so an out-of-range `reason` (not 1/2/3) still decodes
without error — consistent with "decoded, deliberately unread," no panic
risk. `will_save_wait_until`'s dispatch arm decodes params before checking
the setting, same as every other request — not a new cost surface. Verified
`editors/vscode/package.json` is syntactically valid JSON after the edit.
**Tests added this round (7, all passing):**
`server.rs`: `the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`,
`a_lucisv_toml_erases_the_tab_size_gap`,
`a_broken_config_still_saves_with_defaults_and_warns_once`,
`a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save`,
`toggling_format_on_save_neither_rescans_nor_bumps_the_generation`.
`state.rs`: one case added inside `only_an_exclude_change_asks_for_a_rescan`.
`editors/nvim/README.md:101-102`: one-line-pair fix (not a test).
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
clean. The design holds the line where it matters: the new door into the
formatter goes through the same `format::formatting` call — and so through
the runtime safety net — as the manual request, with the all-or-nothing
`edits()` contract unchanged; QA traced the chain to `format_source`'s
verification and I confirm the reading. Default-off was the right call
(a save hook that formats uninvited fights the editor's own
format-on-save), and `settings_without_editor_options` keeping the
precedence reasoning inside `format.rs` is the correct home for it.
On QA's finding (the config warning's dedup is per buffer *state*, not
per broken config — a reformatting save re-arms it): accepted, and I have
reworded the Assumptions bullet to say exactly what QA proved; the
pinning test stays. The behavior itself is acceptable — the warning is
still bounded by the user's own saves, and a user who both breaks their
lucisv.toml and saves in a loop is being told something true each time.
The error-on-every-save decision for refusals stands as argued. QA's
tab-size-gap tests turned the README's honesty into executable fact,
which is the standard here. Accepted as shipped.
+383
View File
@@ -0,0 +1,383 @@
# work-done-progress
## Goal
A workspace rescan is the one thing this server does that a user can feel.
`Server::reindex()` is a synchronous full re-walk of the roots — 0.68 s for the
860-file corpus, seconds for a real filelist — and it runs on every save, on
every watched-file notification, and whenever `lucisv.exclude`/`lucisv.filelist`
changes. Until now it happened in total silence: the editor's status bar said
nothing, the server simply stopped answering for a while, and a user with a
large project had no way to tell a slow index from a hung server. This round
wraps every rescan — the startup build included — in server-initiated work-done
progress: one `window/workDoneProgress/create`, one `$/progress` begin, the
scan, one `$/progress` end naming the file count. Gated on the client's own
`window.workDoneProgress` capability, because the spec forbids creating
progress a client never asked for (TODO.md §9b).
## Assumptions
- **`window.workDoneProgress` is the gate, and there is no fallback.** A client
that did not advertise it is sent no `create` and no `$/progress` — not a
degraded bar, not a `showMessage`. The spec is explicit that a server may
only initiate progress against a client that asked; and a popup per save
would be worse than the silence it replaced.
- **`begin` is sent without waiting for the `create`'s answer.** The spec
permits it ("the server is allowed to report progress before the create
request is answered"), and here it is not merely permitted but necessary:
the rescan blocks the single-threaded loop the moment `begin_indexing`
returns, so waiting for the answer would mean the loop never processes it
and the bar appears only after the work it describes is over. A client that
*errors* the create is required to ignore the `$/progress` notifications
carrying that token, so the worst case is a client that renders nothing —
which is exactly what it rendered before this feature existed.
- **The create's answer is ignored.** It goes through `Server::response`'s
existing "not in the `applying` map, fall through" path, the same one the
file-watcher (un)registrations use. Nothing is retried and nothing is
remembered: the ids are minted from the one shared `request_ids` counter, so
a progress answer can never be mistaken for an `applyEdit` answer.
- **No percentage, and no intermediate `report`.** `Workspace::rebuild_index`
is one opaque call: it walks the roots, reads every file, builds the index,
the completion tables and the include graph, and returns. There is no
progress to observe without threading a callback through three engine
layers, and an invented percentage — "it is probably about half done" — is a
lie the user would learn to distrust. An indeterminate bar is the honest
shape.
- **The end message is the index's own file count**, read from
`WorkspaceIndex::files().len()` after the scan. That number was already
public and already computed; nothing was plumbed to obtain it. It counts the
files the index was built from — in-scope files that read successfully, with
open buffers overriding disk — which is what "indexed" means everywhere else
in this server.
- **The bar covers the scan, not the republish.** `end` is sent the instant
`rebuild_index` returns, before `report_scope`'s warnings and before the
per-buffer republishes that follow. Either order is defensible; this one is
pinned by a test (`the_bar_is_down_before_the_republish`) because the bar
names the *scan*, and the republish is per-open-buffer work the user already
pays on every keystroke without a bar.
- **The startup build gets a bar too, and that is legal.** `Server::new` runs
after `main`'s `initialize_finish`, which returns only once the client's
`initialized` notification has arrived — the same fact that makes the
existing watcher registration legal there, and it is already stated in that
code's comment. So the first index build, which is the slowest of the
session, is wrapped like every other. Determined by reading `main.rs:59-79`
and `server.rs`'s `Server::new`, not assumed.
- **No cancellation.** `cancellable: Some(false)` is stated rather than left
unset: the loop is one thread, a rescan runs to completion, and there is no
`window/workDoneProgress/cancel` handler. A cancel button the user could
press and that did nothing would be worse than no button.
- **One bar at a time, in practice.** The loop is synchronous, so a rescan
cannot overlap another rescan; every `begin` is followed by its own `end`
before the next `begin` can be minted. The token counter guarantees
uniqueness regardless.
## Handshakes
### `lucisv_server::server`
- `ClientAbilities` gains `work_done_progress: bool`, filled by `main.rs` from
`InitializeParams.capabilities.window.work_done_progress` (absent → false),
in the style of the three fields already there. Every existing test that
builds `ClientAbilities { ..Default::default() }` is unaffected.
- `Server` gains `indexings: u32` — the progress-token counter. It is
deliberately *not* the request-id counter: a token is not a request id, and
`lucisv-index-3` reads as the fourth rescan rather than as an unrelated
ordinal.
- Two new private methods, `begin_indexing() -> Option<ProgressToken>` and
`end_indexing(Option<ProgressToken>)`, plus a one-line `progress()` sender.
`None` is the whole of the "this client cannot show a bar" path, so neither
caller branches on the ability itself.
- `Server::new` is restructured: the `Server` is built around a
`Workspace::default()` and `open_roots` is then called *through* it, so the
startup build can sit between a `begin_indexing`/`end_indexing` pair. Same
work, same order relative to `report_scope` and `register_watchers`.
- `Server::response`'s doc comment now names three things asked of the client
rather than two. Its code is unchanged — the create's answer already fell
through the `applying` lookup.
### `state::Workspace`, and every engine crate
**Untouched.** The file count comes from `Workspace::index()` and
`WorkspaceIndex::files()`, both of which were already public and already
called from this crate. No signature moved, `rebuild_index` still returns just
its scope warnings, and nothing was plumbed for the sake of the end message.
### `editors/vscode`
**No extension change.** `vscode-languageclient` advertises
`window.workDoneProgress` itself and renders server-initiated progress in the
status bar with no help from `extension.js`. `smoke.js` sends
`capabilities: {}`, so it takes the no-progress path and passes untouched —
verified by running it.
## Status / TODO
- [x] `window.workDoneProgress` read into `ClientAbilities` at initialize
- [x] `begin_indexing`/`end_indexing` around `rebuild_index()` in `reindex()`
- [x] The startup index build wrapped in the same pair (legal: `Server::new`
runs after `initialize_finish`)
- [x] A fresh `lucisv-index-N` token per rescan, never reused
- [x] `end` carries the indexed file count, singular and plural
- [x] A client without the capability is sent zero progress messages
- [x] The create's answer stays ignored and cannot disturb `applyEdit` routing
- [x] Tests: 8 unit (7 in `server.rs`, 1 in `main.rs`), 2 e2e over the wire
- [x] TODO.md §9b checkbox, `docs/features/lucisv-server/README.md` staleness
section
- [ ] **Not done, deliberately:** no `$/progress` on anything else. Formatting,
a rename across the workspace and `callHierarchy/incomingCalls` are the
other candidates; all three are request-scoped, so they would use the
*client-supplied* `workDoneToken` rather than a created one, which is a
different mechanism with a different gate. Filed here, not built.
- [ ] **Not done, deliberately:** no `window/workDoneProgress/cancel` handler.
There is nothing in this server to cancel — see Assumptions.
## Work log
### 2026-08-26 — dev agent, §9b
- **Read the code before deciding about the startup build, as the brief asked.**
`main.rs` calls `connection.initialize_finish(...)` on line 74 and
`Server::new(...)` on line 76, and `initialize_finish` returns only after the
client's `initialized` notification has been received and consumed. So the
startup build happens at a moment when server-initiated requests are legal —
the existing `register_watchers()` call in `Server::new` already relies on
exactly that, and says so in a comment. **Verdict: wrapped.** It is the
slowest rescan of the session and the one most worth a bar.
- **The one structural change is in `Server::new`**: the struct is now built
first and `open_roots` called through it, because `begin_indexing` needs
`&mut self`. Nothing else about that function moved — `report_scope` still
runs on the warnings `open_roots` returned, and `register_watchers` still
runs last.
- **`Option<ProgressToken>` is the ability check.** `begin_indexing` returns
`None` for a client that cannot show a bar and `end_indexing` returns on
`None`, so neither `reindex` nor `Server::new` mentions the capability. That
also makes "a bar that went up came down" structural rather than a
discipline: there is exactly one value that ends it and exactly one place
it is produced.
- **Tokens are strings, `lucisv-index-N`, off their own counter.** A number
token would collide conceptually with the `lucisv-N` request ids in a log,
and the string says what the bar is for. The counter starts at the startup
build, so `lucisv-index-0` is always the first index and the first save is
always `lucisv-index-1` — pinned by tests at both the unit and the wire
level.
- **The end message reads `WorkspaceIndex::files().len()`,** which was already
public and already reachable through `Workspace::index()`. The brief's
fallback ("end with no message if no count is cheaply available") was not
needed; nothing was plumbed. The singular case has its own assertion, because
"1 files indexed" is the kind of thing that ships.
- **`report_scope` still shows its popup after the bar comes down.** A filelist
warning and a progress bar are unrelated; sequencing them the other way would
have meant holding the bar up across a modal in some clients.
- Files touched: `crates/lucisv_server/src/server.rs`,
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`,
`TODO.md`, `docs/features/lucisv-server/README.md`, this README. No engine
crate, no `editors/`, no new dependency, no version bump.
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
--all-targets`: zero warnings. `cargo test --workspace`: **1812 passed, 0
failed** (1802 on `HEAD`, measured — 7 new unit tests in `server.rs`, 1 in
`main.rs`, 2 new e2e sessions). `cargo build && node editors/vscode/smoke.js
target/debug/lucisv-server`: OK, exit 0. No commits.
The ten tests, and what each is for:
| test | pins |
|---|---|
| `the_startup_index_build_runs_under_the_first_bar` | the startup determination above, as observable traffic |
| `a_save_puts_a_bar_up_and_takes_it_down_again` | create → begin → end, one token, on the save path |
| `the_bar_says_how_many_files_were_indexed` | the end message, plural and singular |
| `the_bar_is_down_before_the_republish` | the documented ordering against `publishDiagnostics` |
| `a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all` | zero messages of any kind, at startup and on save |
| `every_rescan_path_gets_its_own_bar_and_its_own_token` | the watched-file and config-change paths, three distinct tokens, no leaked begin, no `report` |
| `a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit` | an `Ok` *and* an `Err` create answer arriving between an `applyEdit` push and its answer; the refusal still reported exactly once |
| `work_done_progress_support_is_read_from_the_clients_own_capabilities` (`main.rs`) | absent/false/true, and no panic on `InitializeParams::default()` |
| `indexing_reports_its_progress_over_the_wire` + `a_client_that_never_asked_for_progress_is_sent_none_over_the_wire` (e2e) | the whole sequence against the real binary, both gate states, including `title`, `cancellable: false` and the absence of `percentage` |
## QA log
### 2026-08-26 — QA agent, §9b
**Gates re-run**, on the working tree as handed off (commit `00c03ec` +
uncommitted): `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` zero warnings. `cargo test --workspace`: **1812 passed, 0
failed** — matches the dev log exactly. `cargo build && node
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. After the
four tests added below: **1816 passed, 0 failed**, gates re-checked and still
clean.
Per attack surface (lead's numbering):
1. **`Server::new` restructuring — verified clean, structurally rather than
just empirically.** `Workspace::default()` then `open_roots(roots)` is the
same value undergoing the same two operations in the same order whether the
mutation happens on a local binding before it moves into the `Server`
literal (old, `server.rs` pre-`00c03ec`-diff) or on `&mut self.workspace`
after it is already a field (new) — a move is bitwise and Rust invokes no
`Drop`/observer between them, so there is no field `open_roots` could leave
stale that the old order would have filled: every field of `Workspace`
(`docs`, `roots`, `index`, `candidates`, `includes`, `client`) gets the
identical value either way. Every other `Server` field's initializer
(`connection`, `config_warnings`, `abilities`, `watchers`, `registrations`,
`request_ids`, `applying`, `generation`, `tokens`, `token_results`, and the
new `indexings: 0`) is inert and side-effect-free, so field-initializer
order carries no risk. `report_scope` still receives `open_roots`'s
warnings (`server.rs:109-111`); `register_watchers` still runs last
(`server.rs:116`).
**Gap found and fixed**: the ordering the lead flagged as the actual risk —
whether `register_watchers`'s request lands before or after the startup
bar comes down — was not observable in any existing test, because every
dev test using `watching_progress()` (`work_done_progress: true`) leaves
`file_watching` at its `Default::default()` of `false`, so
`register_watchers` is a no-op in all of them; conversely every test that
turns `file_watching` on (`Session::new(_, true)`) leaves
`work_done_progress` off. No test ever ran both abilities together. Added
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`
(`server.rs`, in `mod tests`, right after
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`),
which turns both abilities on and pins the wire order `create, begin, end,
register`.
2. **Protocol conformance — verified clean.** The e2e test
`indexing_reports_its_progress_over_the_wire` decodes the actual JSON
(not the Rust struct) off the real binary and asserts, in one ordered
`Vec`: `create` precedes `begin` for the *same* token, for both the
startup rescan (`lucisv-index-0`) and the save-triggered one
(`lucisv-index-1`) — i.e., create-before-begin holds across consecutive
rescans, not just once. The token is read with
`.as_str().expect("a string token")`, which fails the test if the wire ever
sends a JSON number instead — so the string-typed-token requirement is
pinned, not assumed. `title`, `cancellable: false` (explicit `false`, not
absent), and the absence of `percentage` are asserted off the decoded
`begin`; the `end`'s `message` is asserted off the decoded `end`. No gap.
3. **Pairing is structural — verified clean.** Read `reindex()`
(`server.rs:887-897`) and `Server::new` (`server.rs:140-169`): in both,
nothing sits between `begin_indexing()` and `end_indexing()` but a call
that returns a plain `Vec<String>` (`rebuild_index`/`open_roots`), never a
`Result` — there is no `?` and no early-return expression available to
write between them even by accident. `end_indexing` is therefore
unconditionally reached in every existing and reachable call site.
Multiple rapid reindexes: the server is single-threaded and `reindex()` is
fully synchronous (begin, scan, end, all before the call returns), so two
rescans provably cannot interleave regardless of how close together their
triggers arrive — confirmed observably by
`every_rescan_path_gets_its_own_bar_and_its_own_token`, which fires a save,
a watched-file change and a config change back-to-back and gets three
strictly-paired, strictly-increasing tokens. No gap.
4. **Capability gating — mostly verified clean, one gap fixed.** Startup and
save, both gated correctly, per `a_client_that_did_not_ask_for_a_bar_is_
sent_no_progress_at_all`. `window: {}` and `window: {
workDoneProgress: false }` are both covered by
`work_done_progress_support_is_read_from_the_clients_own_capabilities`
(`main.rs`) via `saying(None)` and `saying(Some(false))` respectively —
`ClientCapabilities::default()`'s `window` field is itself `None`, and
`saying(None)` still wraps a `Some(WindowClientCapabilities{ .. })`, which
is exactly the `window: {}` shape; neither panics on
`InitializeParams::default()`.
**Gap found and fixed**: the watched-file and `lucisv.exclude`/`filelist`
reindex triggers were never driven with the capability *off* — only proven
off by reading that they share `reindex()`'s single `begin_indexing` call
with the save path. Added
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`
(`server.rs`), which drives both and asserts `session.progress()` empty
after each.
5. **Response routing under interleaving — one direction existing, the
reverse was missing; fixed.** The dev's
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`
answers the create (`Ok` then, for the same id, `Err`) while the
`applyEdit` is still outstanding, then answers the edit — this is a real
interleaving (create resolved first), and both answer shapes are exercised.
The reverse ordering the lead asked for — `applyEdit` resolved *first*,
then a *late* create answer — was not present. Added
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`
(`server.rs`): answers the edit as accepted, confirms nothing is shown, then
feeds a late `Response::new_ok` for the create's id and confirms it is
still silently dropped. This same test doubles as "a create answer arriving
for a token the server already Ended": by the time the edit is answered,
the watched-file reindex that minted the create has already run its
`begin`/`end` pair synchronously (per point 3), so the create answer that
follows is necessarily late-for-an-ended-bar. It is ignored cleanly because
`response()` keys off `RequestId`, never off `ProgressToken` — the two are
different namespaces and `request_ids` never repeats, so there is no
representable state where a create's id could collide with anything a
still-outstanding request cares about. No further scenario to test here.
6. **End-message count — verified clean, one gap fixed.** `end_indexing`
reads `self.workspace.index().files().len()` (`server.rs:192`), which is
the index's own file list, computed by `rebuild_index` immediately before
`end_indexing` runs — not open-buffer count, not scope-file count before
filtering. Singular/plural pinned by `the_bar_says_how_many_files_were_
indexed` ("2 files indexed" / "1 file indexed", explicitly asserting `"not
`1 files`"`).
**Gap found and fixed**: no test drove a rootless workspace with zero open
buffers through startup. Traced `default_files()` → `sibling_files()`
(`state.rs:308-328`) for that case: no roots and no docs means no
directories to walk, so the index is empty and `files == 0`; the plural
branch (`files == 1` is false for 0) correctly renders `"s"`. Added
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
crashing` (`server.rs`), asserting `"0 files indexed"` and, by not
panicking, non-crashing. Confirmed passing.
7. **CLAUDE.md compliance — verified clean.** Grepped every non-`#[cfg(test)]`
line of `server.rs` and `main.rs` (i.e., everything before their `mod
tests`) for `unwrap(`, `expect(`, `panic!(`: zero hits. Every new item
(`ClientAbilities::work_done_progress`, `Server::indexings`,
`INDEXING_TITLE`, `begin_indexing`, `end_indexing`, `progress`,
`work_done_progress_support`) carries a doc comment. This README's seven
required sections (`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`,
`Work log`, `QA log`, `Review`) each appear exactly once
(`grep -n "^## "`). `TODO.md`'s §9b item text is untouched — only its
checkbox flipped to `[x]` and an indented `→` note appended below, per the
existing convention elsewhere in that file.
**Beyond the list.** One thing noted for the record, not a defect in this
diff: `Workspace::collect_sources` (`state.rs`, untouched by this round) folds
in every open buffer's path unconditionally, even one outside the walked
scope, so in principle an open buffer for a file the workspace walk would not
have found could nudge the "N file(s) indexed" count up by one beyond what a
disk-only scan would report. This is pre-existing behavior this feature did
not introduce and does not change (`state.rs` has no diff against `00c03ec`),
so it is not filed as a finding against this round — just flagged in case a
future change to the end message's wording ever needs it.
**Fixes made** (all additive; no dev code changed): four new tests in
`crates/lucisv_server/src/server.rs`'s `mod tests`, inserted after
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`:
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`,
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`,
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
crashing`. All four pass; full workspace suite is green at 1816; `cargo fmt`
and `cargo clippy --all-targets` stay clean.
**Verdict: committable as-is.** No corruption risk, no idempotency risk (this
feature touches only the LSP transport, never formatted output), no dropped
comments, no widened `verify.rs` forgiveness (that file has no diff in this
round). The one structurally risky change — `Server::new`'s construction
order — is provably equivalent to the old order and now has its
previously-unpinned watcher-vs-bar ordering under test. No dev follow-up
required.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
(1816 workspace tests, 0 failed), clean. The `Option<ProgressToken>`-as-
capability-gate design is the kind of structural guarantee this repo
prefers over discipline: neither caller can put a bar up for a client
that cannot show one, and nothing between `begin` and `end` can return
early — I read the two call sites and confirm QA's finding that the
pairing is unconditional. The startup-build determination was done the
right way (read from `initialize_finish`'s contract and the existing
`register_watchers` comment, not guessed), and the restructured
`Server::new` is provably equivalent — same value, same two operations,
different borrow spelling — with the previously-unpinned
watcher-after-bar ordering now under test thanks to QA. Honesty calls
all correct: no invented percentage, `cancellable: false` because
nothing here can cancel, and the end message costing nothing because the
index already knew its file count. QA's four gap-closing tests (both
interleaving directions, capability-off on all trigger paths, the
rootless zero-count startup) complete the surface. Accepted as shipped.
+27 -3
View File
@@ -98,8 +98,9 @@ including `` `define`` expansion), `vim.lsp.buf.format()`, document and
workspace symbols, diagnostics as you type, and semantic tokens — Neovim
applies those on top of its treesitter/syntax highlighting with no extra setup.
Not advertised by the server, so your client will correctly refuse them: range
formatting, completion, rename, signature help, and cross-file references.
Range formatting, completion, rename and signature help are advertised too —
Neovim's built-in client wires all four up with no extra config, same as
everything above.
**Inline completion (ghost text) needs a client that speaks it.** The server
advertises `inlineCompletionProvider` — grey `) begin … end` after an `if (`,
@@ -120,7 +121,8 @@ Two behaviors worth knowing before you file a bug:
editor default is not a deliberate override), and without a config your
editor's tab size governs the indent.
Format on save, if you want it:
Format on save, if you want it — one `autocmd`, and your client stays in
charge of when it runs:
```lua
vim.api.nvim_create_autocmd('BufWritePre', {
@@ -129,6 +131,28 @@ vim.api.nvim_create_autocmd('BufWritePre', {
})
```
Or let the server do it, for a client that speaks
`textDocument/willSaveWaitUntil` — it asks before every write and applies what
comes back:
```lua
vim.lsp.config('lucisv', {
cmd = { 'lucisv-server' },
filetypes = { 'verilog', 'systemverilog' },
root_markers = { 'lucisv.toml', '.lucisv.toml', '.git' },
settings = { lucisv = { formatOnSave = true } },
})
```
Pick one, not both. `lucisv.formatOnSave` is **off** unless you set it: the
server answers the save hook with "no edits" until you ask, so an editor that
already formats on save does not format twice. One difference from the
`autocmd` above is worth knowing: `willSaveWaitUntil` carries no tab settings,
so the indent comes from the project's `lucisv.toml`, then `lucisv.indent`,
then the built-in 2 — your `shiftwidth` is not consulted on this path even
though `vim.lsp.buf.format()` sends it. Set `lucisv.indent` if the two need to
agree.
## Checking it works
```
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lucisv",
"version": "0.7.1",
"version": "0.7.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lucisv",
"version": "0.7.1",
"version": "0.7.2",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+6 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the lucisv language server.",
"version": "0.7.1",
"version": "0.9.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -168,6 +168,11 @@
"default": true,
"markdownDescription": "Show grey ghost text that finishes a block as you open it: `if (` suggests `) begin … end`, a `case (` suggests its arms and `endcase`, and a `begin`, `fork`, `generate` or `module` at the end of a line suggests its closer. Tab accepts it as a snippet, so the cursor lands in the condition first and in the body second; where more than one shape fits (`always @(`), `Alt+]` cycles them. The accepted text is indented with the editor's own `editor.tabSize`/`editor.insertSpaces`, not with `#lucisv.indent#`. Requires `editor.inlineSuggest.enabled`."
},
"lucisv.formatOnSave": {
"type": "boolean",
"default": false,
"markdownDescription": "Let the server format the file when you save it, over `textDocument/willSaveWaitUntil`. Off by default, and **not** what a VS Code user wants: `#editor.formatOnSave#` already formats through lucisv and turning both on formats twice. This exists for the editors that have no format-on-save of their own. The indent comes from the project's `lucisv.toml`, then `#lucisv.indent#`, then the built-in 2 — never from `#editor.tabSize#`, which the protocol does not send with this request."
},
"lucisv.lineLength": {
"type": [
"number",
+1
View File
@@ -0,0 +1 @@
813
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# CI gate over the corpus score: fail on any regression from the recorded
# baseline. `scripts/corpus-baseline` holds the passing-file count the tree
# must sustain; a verification error or a crash fails regardless of the
# count — those are formatter bugs by definition (see tools/corpus_check.sh).
#
# Usage: scripts/corpus_gate.sh [corpus-dir]
#
# An improvement does not fail, it nags: bump the baseline in the same
# change that earns it, so the gate ratchets and never slides back.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
corpus=${1:-corpus}
baseline=$(cat "$here/corpus-baseline")
json=$("$here/score.sh" "$corpus")
printf '%s\n' "$json"
passing=$(printf '%s' "$json" | jq .passing)
verr=$(printf '%s' "$json" | jq '.failures_by_category["verification-error"] // 0')
crash=$(printf '%s' "$json" | jq '.failures_by_category.crash // 0')
status=0
[ "$verr" -eq 0 ] || { echo "FAIL: $verr verification error(s) — always a formatter bug" >&2; status=1; }
[ "$crash" -eq 0 ] || { echo "FAIL: $crash crash(es) — always a formatter bug" >&2; status=1; }
if [ "$passing" -lt "$baseline" ]; then
echo "FAIL: corpus regression — $passing passing, baseline is $baseline" >&2
status=1
elif [ "$passing" -gt "$baseline" ]; then
echo "note: $passing passing beats the baseline $baseline — bump scripts/corpus-baseline"
fi
exit $status
+6
View File
@@ -230,3 +230,9 @@ mode), running via `brew services start gitea-runner`; config at
one-time and minted in Gitea's admin UI; nothing secret lives in this
repo — the release workflow authenticates with the `GITHUB_TOKEN` Gitea
Actions injects per job.
Since 0.7.2 the release workflow also runs `tools/audit_artifacts.sh`
before publishing — the automated form of the manual symbol/file-type
audit above (musl static-ness, the GLIBC_2.28 ceiling, PE/Mach-O types) —
and ordinary CI gates every push on the corpus score
(`scripts/corpus_gate.sh` against `scripts/corpus-baseline`).
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# Audit the cross-built release artifacts in a dist directory.
#
# Usage: tools/audit_artifacts.sh [dist-dir]
#
# There is no Linux or Windows machine in the release loop, so the
# non-macOS artifacts are never executed; this automates the audit
# tools/RELEASING.md documented as manual, and the release fails if any
# check does:
# *-linux-musl ELF x86-64, statically linked (zero NEEDED entries)
# *-linux-gnu ELF x86-64, glibc symbol ceiling <= 2.28 (RHEL 8)
# *-windows-gnu.exe PE32+ x86-64
# *-apple-darwin Mach-O 64-bit (arm64 / x86_64 per triple)
#
# Needs the messense x86_64-unknown-linux-gnu toolchain's objdump for the
# ELF checks (the same toolchain the linux-gnu build itself needs).
set -eu
dist=${1:-dist}
objdump=x86_64-unknown-linux-gnu-objdump
glibc_max=2.28
command -v "$objdump" >/dev/null || { echo "no $objdump on PATH" >&2; exit 2; }
[ -d "$dist" ] || { echo "no dist directory at $dist" >&2; exit 2; }
status=0
fail() { echo "FAIL: $*" >&2; status=1; }
checked=0
for f in "$dist"/lucisv-*; do
[ -f "$f" ] || continue
name=$(basename "$f")
case $name in
*.vsix | SHA256SUMS | RELEASE_NOTES.md) continue ;;
esac
kind=$(file -b "$f")
case $name in
*x86_64-unknown-linux-musl)
case $kind in
*ELF*x86-64*) ;;
*) fail "$name: not an x86-64 ELF: $kind" ;;
esac
if "$objdump" -p "$f" | grep -q NEEDED; then
fail "$name: musl build has dynamic dependencies (must be static)"
fi
;;
*x86_64-unknown-linux-gnu)
case $kind in
*ELF*x86-64*) ;;
*) fail "$name: not an x86-64 ELF: $kind" ;;
esac
top=$("$objdump" -T "$f" | grep -o 'GLIBC_[0-9.]*' | sort -Vu | tail -1)
top=${top#GLIBC_}
highest=$(printf '%s\n%s\n' "$top" "$glibc_max" | sort -V | tail -1)
if [ "$highest" != "$glibc_max" ]; then
fail "$name: glibc ceiling $top exceeds $glibc_max (breaks RHEL 8)"
fi
;;
*x86_64-pc-windows-gnu.exe)
case $kind in
*PE32+*x86-64*) ;;
*) fail "$name: not a PE32+ x86-64 executable: $kind" ;;
esac
;;
*aarch64-apple-darwin)
case $kind in
*Mach-O*arm64*) ;;
*) fail "$name: not a Mach-O arm64 binary: $kind" ;;
esac
;;
*x86_64-apple-darwin)
case $kind in
*Mach-O*x86_64*) ;;
*) fail "$name: not a Mach-O x86_64 binary: $kind" ;;
esac
;;
*)
fail "$name: unrecognized artifact name — teach this script about it"
;;
esac
checked=$((checked + 1))
echo "ok: $name"
done
[ "$checked" -gt 0 ] || { echo "no binaries found under $dist" >&2; exit 2; }
echo "audited $checked binaries"
exit $status