Compare commits

...
13 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 34b766cbef Release 0.15.0 — the interactive-latency release
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 19s
release / build-and-publish (push) Successful in 4m25s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:48:48 -07:00
lucio 8cdc1b3375 Merge the design-hierarchy sidebar (codex + integration round)
ci / checks (push) Successful in 47s
ci / corpus (push) Successful in 19s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	crates/lucisv_server/src/main.rs
2026-08-29 03:39:31 -07:00
lucioandClaude Fable 5 651e58bfb3 The design-hierarchy sidebar: codex's feature, integrated
An instance-oriented hierarchy view in the Activity Bar —
lucisv/moduleHierarchy snapshots (schema 2: uri table, flat ranges,
derived ids; 11.6 MB -> 2.3 MB on opentitan) plus
lucisv/moduleHierarchyChanged invalidation, gated on the extension's
initializationOptions. Format 5 carries decl spans, instance
occurrences and client positions for file-scope declarations
(+1.7-1.9 % store), so a snapshot reads no files at all: handler
145-167 -> 17-20 ms settled, a save with the sidebar open 366 ->
141 ms. complete is !scanning && !must_wait, pinned. Owner UI rounds:
no hover preview, all levels collapsed by default with stable ids
across refreshes, and search over a resident flat model (freeze
diagnosed: materialized expanded tree x undebounced double
fuzzyScore x whole-tree clone per keystroke) — prebuilt lowercased
index, bitmask prefilter, top-K counting, 200-row cap with an honest
remainder, single-digit ms over a 120k-entry fixture.
LineIndex::utf16_position unifies the index's and the wire's position
math under a cross-crate agreement test.

Implementation: codex. Integration fixes + owner items: Opus dev.
QA: lead (measurement pass) + Sonnet (SHIP, independent oracles).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:39:06 -07:00
lucioandClaude Fable 5 37560cad5e A subsuming widen was already incremental; its word merge was not
ci / checks (push) Failing after 1m4s
ci / corpus (push) Successful in 26s
Take 2 filed the RTL didOpen freeze as a chooser bug; measuring with
the HEAD binary refuted that — scope_dirs keeps every raised dir so
subsumption is Added, and begin_widen has file-diffed against the
index since the widen round; the 1.4-1.7 s figures were cold-store.
The real cost was candidates.absorb inserting each new word into the
sorted table one memmove at a time — quadratic in the batch, 403 ms
of a 935 ms warm jump — replaced by a counted one-pass merge whose
equivalence with build's sort is structural (43 ms). Warm hw/ip jump
935/881 -> 555/564 ms (QA: 872-880 -> 535-546 from its own builds);
the residual is real work, 1 683 new files and a 325 ms word re-lex
filed as the store's FACTS_FORMAT follow-up. The two previously
accidental properties are now pinned, QA's five-mutation matrix
confirming each test binds exactly its property. TODO.md carries take
2's other findings (codeAction big-fan-out zero-offers, inlayHint at
default scope) as deferred items.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 02:52:55 -07:00
lucioandClaude Fable 5 e4407984cb Hotfix: --stdio is accepted, because real VS Code sessions send it
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 21s
vscode-languageclient appends --stdio for TransportKind.stdio — the
spawn the shipped extension actually makes — and the --verbose round's
strict argument parser refused it: exit 2, five crashes, the client
gives up. Nothing in the loop caught it because smoke.js and the
restart harness spawn the binary directly, never through the library.
--stdio now parses as the statement of fact it is (stdio is the only
transport), in every combination, changing nothing; near misses and
genuinely unknown args still exit 2 with the usage line, which now
names both flags. smoke.js spawns with --stdio so the library's real
spawn shape stays covered from here on.

Found live by the owner installing the hierarchy preview build.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 02:48:56 -07:00
lucioandClaude Fable 5 40094c4c4e lucisv-server --verbose: per-operation timing as a shipped toggle
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
The hand-patched diagnostic build becomes a feature: --verbose gates
the timing lines (request answered / notification handled / HELD
behind a rescan / scan and widen lifecycle / flush / reindex_one, the
exact wordings of the two diagnostic builds) as LOG messages into the
client's output channel; without the flag not one line is sent and
the cost is one branch, measured unmeasurable against HEAD. Unknown
args exit 2 with usage before the transport opens. The extension
gains lucisv.verbose (default off) and its first restart-on-settings
machinery: restart.js, one serialized chain reconciling to the last
toggle, no client transition outside it — activation and deactivate
included — after QA twice caught the alternatives (a mid-start toggle
silently rejoining the stale start; deactivate's out-of-chain stop
orphaning a spawn). Headless node harness restart_test.js, 44 checks,
five mutations caught. Spawn contract amended everywhere it is
written: no args required, --verbose optional.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 01:44:56 -07:00
lucioandClaude Fable 5 829302d0bf CLAUDE.md: the 2-agent parallel-lane loop, codified
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 24s
Up to two dev/QA lanes concurrently when TOPO.md proves the features
independent (no shared edges, disjoint files; unanswerable = serial).
Each lane: own worktree off one trunk commit, a brief whose file list
is the merge contract, dev then QA in that worktree, lead review and
merge per lane with full gates on the merged tree. Wave tracking in a
TODO.md section written on trunk before branching. Distilled from the
2026-08-28 performance wave, where the shape was proven end to end.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 00:55:45 -07:00
lucio ee1efe3fb1 Merge performance-wave Lane A (prepareRename, rename, willRenameFiles)
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	docs/perf/README.md
2026-08-29 00:11:42 -07:00
lucioandClaude Fable 5 1029d2f199 Performance wave Lane A: the rename family reads its fan-out
prepareRename answered F2 by reading every in-scope file (1.6-3.0 s on
opentitan, blocking the loop); it now answers from the open buffer and
the index in 139 ns, with a refusal-by-refusal parity table (7
reproduced, 4 deferred to rename, none lost). rename computes over
rename_sources — declarers, reference postings, open buffers, and,
after QA's HIGH finding gated the round, rung 6: files_spelling over
the index's reference facts (resolved or not, FACTS_FORMAT untouched),
restoring the dangling-new-name capture refusal the first five rungs
lost; the old name needs no rung and the argument is written and
pinned, QA's shadowing hunt included. 3.47 s -> 105 ms at a 7-file
fan-out, rung cost 852 us worst-case, byte-parity swept at four real
cursors and 564 offsets, ambiguity escaping to the whole scope.
willRenameFiles rides IncludeGraph::includers(): 249 ms -> 14 ms over
331 includers of 3 976 files. Accepted residue, documented: files
whose only mention of the name is inside opaque macro tokens lose one
warning flavour; the FileFacts macro census is filed as the real fix.

Dev Opus + QA Sonnet (REWORK-gate, fix, SHIP on re-verify) in a
dedicated worktree. Lead-reviewed and merged.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 00:11:13 -07:00
lucioandClaude Fable 5 36caf1dd19 Merge performance-wave Lane B (completion, documentHighlight, scope default)
ci / checks (push) Successful in 47s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 23:58:29 -07:00
lucioandClaude Fable 5 61f345aca7 Performance wave Lane B: completion hot path, highlight fix, scope default
Completion stops parsing whole declaring files per keystroke: tier 0
slices the module header at its terminating ';' via a whitelist walk
over a bounded lex window, anchored on the index span and re-planning
whole-file on anything unrecognized (non-ANSI included); the module
table replaces a per-keystroke workspace_symbols(""). 53 -> 3.2 ms at
the empty prefix (opentitan wire 63-66 -> 13-15 ms; typing an 11-char
word 201 -> 64 ms), items pinned byte-identical.

documentHighlight answered 0 on any name the file uses but does not
declare (both cursor questions were single-file); nav gains
external_occurrences over the overlay, grouping by the whole defs()
slice, written failing-first and pinned at the two opentitan
positions over the wire.

lucisv.index.scopeDepth default 0 -> 2 (behavior change; CHANGELOG at
release): a dv/tb file now indexes its IP block (21 files / 15 ms)
instead of one file with every cross-file answer empty. Rootless
sessions no longer climb (latent unnamed-tree walk removed).

Dev Opus + QA Sonnet in a dedicated worktree; QA SHIP with one LOW
(pre-existing attribute-instance indexing gap, pinned) and one
recorded asymmetry. Lead-reviewed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 23:58:22 -07:00
lucioandClaude Fable 5 ad27ed23dc codeAction reads the module's fan-out, not the workspace
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
The owner's slow-F12 root cause: textDocument/codeAction on a module
instantiation read every in-scope file through ws.sources() and ran
the port-refactor engine over them, per cursor move — 3.1-4.6 s on
opentitan's 3 976 files, blocking the single-threaded loop so every
queued definition/hover paid the bill. Workspace::module_sources now
hands the engine the cursor modules' fan-out: declarers (units),
instantiation-edge files, references_to postings (the fourth rung —
edges_of drops owner-less file-scope instantiations, so edges alone
are not a superset), and every open buffer. 4.56 s -> 7.1 ms typical,
83 ms at a 36-file fan-out; equality with the whole-workspace
computation pinned by four dev + six QA equivalence/attack tests.
Disclosed behavior change: the answer now sees the workspace as the
index describes it, like every other index-backed answer.

Also: performance.md (full opentitan benchmark of every LSP action)
committed at the root, and TODO.md gains section 10 tracking the
performance wave the benchmark spawned (rename family, completion,
documentHighlight, scope default) with per-lane file ownership.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 22:35:00 -07:00
lucioandClaude Fable 5 bf9170a850 A scope widen indexes the folders it added, not everything again
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
Every F12 jump into a new folder didOpen-widened the scope and re-ran
a full rescan of all folders accumulated so far, growing with browsing
(opentitan, warm: 120-169 ms per jump, ~90 ms of it re-opening and
decoding the whole persistent store). widen_of chooses: pure folder
adds take a widen scan over only the new files (absorbed into the live
index/candidates/includes, open buffers refreshed from held analyses,
store handle kept, no compaction); anything else still takes the whole
rescan; mid-scan defers to one whole follow-up. Jumps now cost the new
folder alone (12-44 ms flat), first definition of a session 99.7 ->
0.9 ms. IncludeGraph stores edges as the filesystem answered them and
re-spells on relearn so a newly scoped file lends its spelling to
earlier edges. Watcher-coverage narrowing documented: watcher-less
clients lose the widen's incidental disk re-read, same staleness class
as the save path since 2026-08-27. QA was stopped by the owner
mid-gates after its adversarial phases; lead gates run twice, green.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 21:36:55 -07:00
68 changed files with 15135 additions and 366 deletions

No files matched your search

+63
View File
@@ -4,6 +4,69 @@ 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.15.0 — 2026-08-29
The interactive-latency release, benchmarked twice against a real
3 976-file opentitan checkout (`performance.md`, `performance_take2.md`
at the repo root), plus a design-hierarchy sidebar contributed by
codex.
### Every hot path measured, then fixed
- **codeAction** (fires per cursor move): 3.1–4.6 s → **7 ms** — the
port-refactor engine reads the cursor module's indexed fan-out, not
the workspace; equality with the whole-workspace computation is
pinned, ambiguity refusals intact.
- **prepareRename** (pressing F2): 2.5–3.0 s → **microseconds**, flat
in project size — answered from the open buffer and the index, with
a refusal-by-refusal parity table; refusals are deferred to the
rename, never lost.
- **rename**: 3.6–8.7 s → **~105 ms** over the reference-postings
fan-out, including a sixth rung over unresolved spellings so the
dangling-import capture refusal fires exactly as the whole-workspace
walk's did. willRenameFiles rides the include graph: 250 → 14 ms.
- **completion**: 34–66 ms per keystroke → **3–15 ms** — module
headers are sliced, not whole-file-parsed, with whole-file re-plans
wherever the slice cannot be proven identical; items byte-identical.
- **documentHighlight**: fixed — it answered nothing for any name the
file uses but does not declare (a module instance, a connected
port), which is most of what a tb hovers.
- A widen that subsumes the old scope indexes only its new files, and
the word table merges per batch instead of per word (935 → 555 ms
for the first jump into a 1 685-file root, warm).
### The scope default finds your block
**Behavior change:** `lucisv.index.scopeDepth` defaults to **2** (was
0). Opening `hw/ip/aes/dv/tb/tb.sv` now indexes the aes block and
cross-file answers work immediately, where before exactly one file was
indexed and every cross-file answer was empty until a jump widened the
scope. An explicit `0` restores the old behavior exactly.
### `--verbose`, when you want receipts
`lucisv-server --verbose` (or the `lucisv.verbose` setting, which
restarts the server through a race-proof one-chain restarter) prints a
`timing:` line for every operation into the output channel. Off by
default and free when off. `--stdio` is accepted as the statement of
fact it is.
### The design-hierarchy sidebar (contributed by codex)
An instance-oriented hierarchy in the Activity Bar: every module, its
instances, search over the whole design, bookmarks, click-to-jump.
Snapshots read no files at all — the index now carries client
positions — so the handler answers in ~17 ms on opentitan and a save
with the sidebar open costs ~141 ms total. Search runs over a resident
model in single-digit milliseconds at 120 000 entries, collapsed by
default, expansion preserved across refreshes.
### One-time index rebuild
The persisted facts format moved to 5 (declaration spans, instance
occurrences, client positions; ~+2 % store). The first scan after
upgrading rebuilds the store once.
## 0.14.0 — 2026-08-28
The first-hover release: the owner's "hover is really slow on first
+35
View File
@@ -86,3 +86,38 @@ Rules:
(`cargo test -p vlog_formatter`).
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
their features do not collide in `TOPO.md`: no shared edge between them
(no `──▶`, no `◀──▶`, and neither touching the same open handshake in
§2.9), and disjoint file sets. `TOPO.md` is the authority; if the
collision question is not answerable from it, the features are not
proven independent and run serially. Rules for a parallel wave:
- **The lead plans the lanes** before anything is dispatched: one brief
per lane with an explicit file-ownership list. That list is the merge
contract — a lane touches nothing outside it. A needed change to a
file the other lane owns (or to any unlisted file) is a Handshake
request in the lane's README plus a flag in its report, never a
silent edit; the lead rules on it at merge.
- **Each lane works in its own git worktree** branched from the same
trunk commit. Never two agents in one tree. Trunk stays untouched
while lanes are in flight; the lead merges each lane back only after
that lane's QA verdict and lead review, and re-runs the full gates on
the merged tree before pushing.
- **Roles per lane are unchanged**: one dev (Opus), then one QA
(Sonnet) in the same worktree, then the lead's review — so at most
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
its own dev is done. A QA rework loops inside its lane without
blocking the other lane.
- **Tracking lives in `TODO.md`**: the lead writes the wave's section
(one subsection per lane, each item naming its files) on trunk before
branching; each lane ticks only its own lines. Shared-by-nature files
(`TODO.md`, `docs/perf/README.md`) may be appended to by both lanes
in their own sections — the lead resolves the trivially-parallel
merge; anything worse than trivially-parallel means the lanes were
not actually independent, which is a planning failure to record.
- After merging, the lead updates `TOPO.md` for any edge a lane added
or amended, so the next wave plans against reality.
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.14.0"
version = "0.15.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.14.0"
version = "0.15.0"
[[package]]
name = "lucisv_server"
version = "0.14.0"
version = "0.15.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.14.0"
version = "0.15.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.14.0"
version = "0.15.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.14.0"
version = "0.15.0"
[[package]]
name = "vlog_refactor"
version = "0.14.0"
version = "0.15.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.14.0"
version = "0.15.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.14.0"
version = "0.15.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+5 -1
View File
@@ -678,7 +678,11 @@ to the folder walk, so the index is never silently empty.
<path-to-binary>` spawns it exactly as the extension does and drives a whole
`initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if
the handshake and the advertised capabilities are intact — which tells you
whether a failure is the server or your editor config.
whether a failure is the server or your editor config. Its neighbour
`node editors/vscode/restart_test.js` needs no binary at all: it drives the
extension's server-restart chain (the one `lucisv.verbose` uses) against a
scripted fake client, so a toggle can never be lost to a restart that was
already in flight.
**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
+182 -1
View File
@@ -651,12 +651,25 @@ section only tracks the milestones.
**Since 2026-08-28 a rescan no longer re-parses the buffers it already
analyzed** — an open buffer's index facts and completion words come from the
analysis it holds — so a scope-widening `didOpen` with a 1.4 MB buffer open
costs ~23 ms rather than ~228 ms.
costs ~23 ms rather than ~228 ms. **And since 2026-08-28 a widen indexes only
the folders it added** rather than rescanning every folder reached so far, so
the wait a jump puts in front of the next request stops growing with the
session: over opentitan's 3 979 files, 120/132/137/169 ms per jump became
22/18/12/44 ms.
- [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
`prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves,
cross-file, whole-edit-or-nothing verified by re-parse.
- [x] **M3 `refactor-ports`** — add/remove/propagate module ports across
the declaration and every instantiation (named/ordered/`.*`).
**Amended 2026-08-28** (`docs/features/refactor-ports/README.md`): a
`textDocument/codeAction` no longer reads the in-scope file set from
disk per cursor move. The engine is handed the cursor's module's own
fan-out through the index — definers, instantiation edges, reference
postings, open buffers — by one builder both the code action and the
three commands use, and the answer is asserted equal to the
whole-workspace one. Over opentitan a code action went 4.56 s → 7.1 ms
(2.93 s → 83 ms for a module instantiated in 36 files); it was the
request every queued definition and hover had been waiting behind.
- [x] **M4 `refactor-instantiate`** — module hinting: instantiation
skeleton completion from the definition, auto-connect, signature help.
- [x] **M5 `completion-core`** — keyword + project-wide identifier
@@ -1115,3 +1128,171 @@ 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.
## 10. Performance wave (2026-08-28) — performance.md findings
Source: `performance.md` (benchmark of every LSP action against
opentitan, 3 976 files). Tracking for the two-worktree parallel round;
each lane's dev ticks only its own lines. Lane file ownership is the
merge contract — a lane touches no file outside its list.
### Done before the wave (trunk)
- [x] `textDocument/codeAction` 3.1–4.6 s per cursor move →
7.1 ms (83 ms at a 36-file fan-out): `Workspace::module_sources`
subset instead of `ws.sources()` — refactor-ports README,
2026-08-28 work log + Review.
### Lane A — rename family (worktree A; files: crates/vlog_refactor/*,
crates/lucisv_server/src/{rename.rs,file_ops.rs,state.rs,perf.rs},
docs/features/{refactor-rename,file-operations}/README.md,
docs/perf/README.md)
- [x] `prepareRename` 2.5–3.0 s (F2 blocks everything) → buffer+index
answer, < 1 ms; refusal-by-refusal parity table in the README.
**1.663 s → 139 ns on OpenTitan**; parity table and six
byte-by-byte parity suites in refactor-rename's README, plus 564
offsets of a real `tb.sv` swept identical, zero deferrals.
- [x] `rename` 3.6–8.7 s → reference-postings fan-out subset with a
written sufficiency argument; verifier integrity proven.
**3.467 s → 105.5 ms on OpenTitan**, edits byte-identical at every
cursor checked (7 files at `aes`, 114 files at `clk_rst_if`), the
capture refusal still firing on a real workspace. QA found one
lost refusal (a dangling use of the *new* name); closed by a sixth
rung, `WorkspaceIndex::files_spelling` — 852 µs worst case on
OpenTitan. One accepted residue remains —
macro-**invocation**-argument warnings in files outside the
fan-out, costing no edit and no refusal.
- [x] `willRenameFiles` same `ws.sources()` shape (file_ops.rs:120) →
include-graph/index-bounded subset. **249 ms of `sources()` → a
14.1 ms whole answer on OpenTitan** (331 includers of 3 976).
### Lane B — hot path + UX (worktree B; files:
crates/lucisv_server/src/{completion.rs,candidates.rs,nav.rs,
settings.rs,perf.rs}, crates/lucisv_server/tests/e2e.rs,
editors/vscode/package.json, docs/features/{completion-core,
references-nav,index-scope}/README.md, docs/perf/README.md)
- [x] `completion` 34–66 ms per keystroke (worst at 0–4 chars) →
profile, then < 5 ms with item-identical answers pinned.
Profiled: the whole cost was tier 0, the module skeletons — every
other tier is 0.19 ms at every prefix. Tier 0 now parses the
declaring file's *header* instead of all of it, and reads the
module names off a table built with the index instead of sorting
the workspace's whole symbol table per keystroke. **3.17 ms** at
the empty prefix on a 4 000-file generated corpus (was 53.2 ms);
**13–15 ms** worst case on opentitan (was 34–66), and typing
`aes_reg_top` 201 ms → 64.5 ms. Items pinned identical by a
fifteen-shape plan-equality test and a module-table equality test.
- [x] `documentHighlight` answered 0 results at every opentitan
position while references answered — root-cause and fix (or
prove the benchmark request wrong and correct performance.md).
**A real bug, not a benchmark mistake**: the handler asked only
single-file `Semantics`, so a name this file uses but does not
declare — an instantiated module, a `.port` connection — had no
symbol to find, while `references` read the workspace overlay.
Fixed in `nav::external_occurrences`, with a unit regression test
and the two opentitan positions pinned over the wire.
- [x] Default `lucisv.index.scopeDepth` 0 → 2 (folder scope indexed
exactly one file in opentitan's dv/tb layout; every cross-file
answer empty until a jump widens) — behavior change, CHANGELOG
callout at release. Also removed the *rootless* climb, which had
no root to clamp against and would have walked an unnamed tree at
the new default. Cost measured rung by rung: 1 / 1 / 21 / 252
files at depths 0 / 1 / 2 / 3.
### Take 2 follow-up (2026-08-29) — the first RTL open at the default scope
Measured in `performance_take2.md` §5b: opening `hw/ip/aes/rtl/aes.sv`
at `scopeDepth: 2` raises the scope to `hw/ip` and costs 1.4–1.7 s.
Files: `crates/lucisv_server/src/{candidates.rs,state.rs,server.rs,perf.rs}`,
`docs/features/index-scope/README.md`, `docs/perf/README.md`.
- [x] Diagnosis corrected against the running binary: the widen already
takes the cheap path for a subsuming scope and already diffs by
**file against the index** (the bar reads 1 685, not 1 807, when
the old block's 124 files are inside the new root), so nothing was
re-indexed. The chooser's `Whole` arm is still unreachable. Pinned
by `state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`
and a `widen_of` table row.
- [x] The real cost found and fixed: folding a widen's words into the
completion table inserted each new word into a sorted `Vec` on its
own, which is quadratic in the batch — **403 ms of the 935 ms** on
opentitan's `hw/ip`. Counted per batch and merged once: 43 ms.
Warm **935 / 881 → 555 / 564 ms**, cold **1 529 → 1 175 ms**.
- [ ] **Still slow, filed:** what is left of that jump is real work over
1 683 genuinely new files — 325 ms re-lexing them for the
completion word table (the persistent store holds a file's facts
but not its words), ~100 ms walking and reading them, ~80 ms
hashing and decoding records. Storing the word list beside the
facts is the next lever and is `index-persistence`'s call: it is a
`FACTS_FORMAT` change.
- [ ] **Not done, deliberately:** a widen still does not interleave, so
this is a bar the user watches once per session per big widen. The
coalescing rule is unchanged.
### Deferred, filed
- [ ] `codeAction` costs 185–201 ms at a 128-file fan-out and offers
**zero** actions there (`performance_take2.md` §6a): ~1.4 ms per
instantiating file plus a ~13 ms floor, paid before anything knows
there is nothing to offer. Wants either the lazy resolve below or
a cheap zero-detector that answers before the fan-out is walked.
- [ ] `inlayHint` returns **0 hints at the default scope** where the
workspace scope returns 4 (`performance_take2.md` §8): investigate
before assuming it is scope-relative-answers working as intended —
the hinted instantiation's module may be in scope and still unhinted.
- [ ] codeAction lazy resolution (`codeAction/resolve`): make the offer
index-only (~0 ms regardless of fan-out), edits computed on
lightbulb click — kills the 83 ms worst case. Owner-approved
direction, after the wave.
- [x] Rename over an index-stale workspace: Lane A must state the
staleness premise; if the verifier cannot catch a hidden
reference, the honesty gate is the lead's review call. Stated
verbatim under "The staleness premise, stated exactly" in
refactor-rename's README, with what it costs (a file whose disk
copy moved unseen is neither rewritten nor refused over) and the
one exemption (open buffers, always in the set). Both residues
ruled on: the dangling-use lost refusal was rejected and fixed
(rung 6, `files_spelling`); the macro-invocation warning loss is
accepted as documented, with the `FileFacts` macro census filed
as the real fix.
## VS Code design-hierarchy sidebar (2026-08-29)
Feature by codex; this section is that round plus the lead's QA finding
and three owner items. See
`docs/features/vscode-hierarchy-sidebar/README.md`.
- [x] `lucisv/moduleHierarchy` + `lucisv/moduleHierarchyChanged`, gated
on `initializationOptions.hierarchyView`; Activity Bar container,
webview view, navigation, context menu, bookmark.
- [x] `FACTS_FORMAT` 4 → 5: `Def::decl_span`, per-instance
`InstanceOccurrence`s on the statement edge, and client positions
on file-scope declarations and instance occurrences. Call
hierarchy and code-lens counts unchanged.
- [x] **Lead's HIGH finding — the snapshot read every module-declaring
file per request.** Fixed by index-carried positions (zero file
I/O), `WorkspaceIndex::units_of`, and a schema-2 wire (file
table, four-number ranges, no ids, no per-instance definition
copies). On opentitan, server-side handler **145–167 ms → 17–20 ms**
warm, response **11.6 MB → 2.3 MB**, a definition pipelined behind
a snapshot **263 ms → 41 ms**. Store cost of the positions: +1.7 %
on the corpus, +1.9 % on opentitan.
- [x] `complete` tightened to `!scanning && !must_wait()` and the
window it has to be honest about written down and tested.
- [x] Owner: the five-line hover source preview removed — the feature's
last consumer of file text.
- [x] Owner: every tree level collapsed by default; expansion state
survives a refresh on stable row ids.
- [x] Owner: search freeze fixed. The model is flat and resident, tree
levels are built lazily, and a query is one pass over a prebuilt
lowercased index with a character-mask pre-filter and a counting
top-K — 3–8 ms per query over a generated 120 000-entry
hierarchy, asserted in the node suite.
- [ ] Filed, not done: rewire `locate::location` onto `DeclPositions`
so `textDocument/definition`, references, the lens and both
hierarchies stop reading a file to convert an indexed span. Every
unit's range is now in the index for free.
- [ ] Manual extension-host acceptance (themes, keyboard-only, zoom,
screen readers, an old server binary, both VSIX shapes).
+236 -22
View File
@@ -53,6 +53,15 @@ pub struct Macro {
#[derive(Debug, Default)]
pub struct Candidates {
units: Vec<Candidate>,
/// Every module name the index declares, in the order
/// `WorkspaceIndex::workspace_symbols` puts them in.
///
/// Its own table beside [`Candidates::units`] because tier 0 of a
/// completion asks a different question of it: a *substring* match, not a
/// prefix one, so it cannot ride the binary search the others do. What it
/// buys is that the whole symbol table is no longer built and sorted per
/// keystroke — see `docs/features/completion-core/README.md`, 2026-08-28.
modules: Vec<String>,
macros: Vec<Macro>,
words: Vec<String>,
/// How many in-scope files contain each word. What makes it possible to
@@ -83,11 +92,9 @@ impl Candidates {
sources: &[(PathBuf, String)],
mut known: HashMap<PathBuf, Vec<String>>,
) -> Candidates {
let mut out = Candidates {
units: units_of(index),
macros: macros_of(index),
..Candidates::default()
};
let (units, modules) = index_tables(index);
let mut out =
Candidates { units, modules, macros: macros_of(index), ..Candidates::default() };
for (path, text) in sources {
let words = match known.remove(path) {
Some(words) => words,
@@ -121,7 +128,7 @@ impl Candidates {
/// [`Candidates::update_file`] for a file whose words the caller already
/// has — an open buffer's, read off the tokens it was analyzed from.
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
self.units = units_of(index);
(self.units, self.modules) = index_tables(index);
self.macros = macros_of(index);
self.set_words(path, words);
}
@@ -133,39 +140,64 @@ impl Candidates {
/// than one per file: they are read off the index and nothing else, so
/// doing it once at the end of the batch is doing it once with the same
/// answer. The word table is patched per file exactly as it is there.
/// **One re-sort of the word table for the whole batch, too**, which is
/// what makes a scope widen over a big folder affordable: the table is a
/// sorted `Vec`, and inserting each of a widen's tens of thousands of new
/// words into it one at a time moves the tail of the table once per word.
/// Counted per batch and merged once, the same batch is one pass
/// (`docs/features/index-scope/README.md`, 2026-08-29 — 403 ms → 43 ms for
/// the 1 807 files of opentitan's `hw/ip`).
pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec<String>)>) {
let mut touched: HashMap<String, bool> = HashMap::new();
for (path, words) in batch {
self.set_words(&path, words);
self.count_words(&path, words, &mut touched);
}
self.units = units_of(index);
self.merge_words(touched);
(self.units, self.modules) = index_tables(index);
self.macros = macros_of(index);
}
/// Drop one file's contribution entirely.
pub fn remove_file(&mut self, index: &WorkspaceIndex, path: &Path) {
self.units = units_of(index);
(self.units, self.modules) = index_tables(index);
self.macros = macros_of(index);
self.set_words(path, Vec::new());
}
/// Make `words` this file's words, adjusting the workspace-wide table.
fn set_words(&mut self, path: &Path, words: Vec<String>) {
let mut touched = HashMap::new();
self.count_words(path, words, &mut touched);
self.merge_words(touched);
}
/// Make `words` this file's words in the per-file tables and the counts,
/// leaving the sorted table to [`Candidates::merge_words`].
///
/// `touched` collects every word whose count this call moved, against
/// **whether the workspace held it before the batch began** — recorded at
/// the first touch, so a word a batch takes and gives back is correctly
/// seen as never having moved.
fn count_words(
&mut self,
path: &Path,
words: Vec<String>,
touched: &mut HashMap<String, bool>,
) {
for word in self.per_file.remove(path).unwrap_or_default() {
let Some(count) = self.word_files.get_mut(&word) else { continue };
*count -= 1;
if *count == 0 {
self.word_files.remove(&word);
if let Ok(at) = self.words.binary_search_by(|held| word_cmp(held, &word)) {
self.words.remove(at);
}
touched.entry(word).or_insert(true);
}
}
for word in &words {
let held = self.word_files.contains_key(word);
let count = self.word_files.entry(word.clone()).or_default();
*count += 1;
if *count == 1 {
let at = self.words.partition_point(|held| word_cmp(held, word) == Ordering::Less);
self.words.insert(at, word.clone());
if !held {
touched.entry(word.clone()).or_insert(false);
}
}
if !words.is_empty() {
@@ -173,11 +205,63 @@ impl Candidates {
}
}
/// Bring the sorted word table back in step with the counts, in one pass.
///
/// A word in `touched` that the counts still hold and the table does not is
/// an insertion; one the counts have dropped and the table still holds is a
/// removal; a word that ends where it started is neither. What comes out is
/// the table [`Candidates::build`] would have sorted from the same counts,
/// because [`word_cmp`] is a total order on distinct words — so merging a
/// sorted run into a sorted table is that sort's own answer.
fn merge_words(&mut self, touched: HashMap<String, bool>) {
let mut added: Vec<String> = Vec::new();
let mut dropped: HashSet<String> = HashSet::new();
for (word, was_held) in touched {
match (was_held, self.word_files.contains_key(&word)) {
(false, true) => added.push(word),
(true, false) => {
dropped.insert(word);
}
_ => {}
}
}
if added.is_empty() && dropped.is_empty() {
return;
}
sort_by_name(&mut added, |word| word.as_str());
let held = std::mem::take(&mut self.words);
let mut out = Vec::with_capacity(held.len() + added.len());
let mut added = added.into_iter().peekable();
for word in held {
if dropped.contains(&word) {
continue;
}
while let Some(new) = added.next_if(|new| word_cmp(new, &word) == Ordering::Less) {
out.push(new);
}
out.push(word);
}
out.extend(added);
self.words = out;
}
/// Index names starting with `prefix`, case-insensitively.
pub fn units(&self, prefix: &str) -> &[Candidate] {
matching(&self.units, prefix, |c| &c.name)
}
/// Module names *containing* `query`, case-insensitively — what
/// `vlog_refactor::module_names` answers, off a table instead of off the
/// index. A substring match, so it is a scan; the table it scans holds one
/// entry per module rather than one per declaration in the workspace.
pub fn modules(&self, query: &str) -> Vec<&str> {
self.modules
.iter()
.filter(|name| contains_ignore_case(name, query))
.map(String::as_str)
.collect()
}
/// `` `define`` names starting with `prefix`, case-insensitively.
pub fn macros(&self, prefix: &str) -> &[Macro] {
matching(&self.macros, prefix, |m| &m.name)
@@ -189,12 +273,26 @@ impl Candidates {
}
}
/// Every name the index carries, as a lookup table.
fn units_of(index: &WorkspaceIndex) -> Vec<Candidate> {
// The empty query means "everything"; it is paid once per index build
// rather than once per keystroke, which is the whole point of this table.
let mut out: Vec<Candidate> = index
.workspace_symbols("")
/// Every name the index carries, and the module names among them, from one
/// pass over its symbol table.
///
/// One pass because that pass is the expensive part: `workspace_symbols("")`
/// builds and sorts a record per declaration in the workspace, and the two
/// tables want the same records. It is paid once per index build rather than
/// once per keystroke, which is the whole point of both.
fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
let symbols = index.workspace_symbols("");
// `workspace_symbols` sorts by name first, so same-named declarations are
// already adjacent and a plain `dedup` leaves one entry per module name —
// which is exactly what `vlog_refactor::module_names` does to the same
// list, minus the per-keystroke rebuild.
let mut modules: Vec<String> = symbols
.iter()
.filter(|symbol| symbol.container.is_none() && symbol.def.kind == SymbolKind::Module)
.map(|symbol| symbol.name.to_string())
.collect();
modules.dedup();
let mut out: Vec<Candidate> = symbols
.into_iter()
.map(|symbol| {
let detail = match symbol.container {
@@ -212,7 +310,7 @@ fn units_of(index: &WorkspaceIndex) -> Vec<Candidate> {
sort_by_name(&mut out, |c| c.name.as_str());
// A name two files declare is one completion item, not two.
out.dedup_by(|a, b| a.name == b.name && a.kind == b.kind);
out
(out, modules)
}
/// Every `` `define`` the workspace declares. `` `undef`` entries are skipped:
@@ -322,6 +420,17 @@ fn lower_cmp(a: &str, b: &str) -> Ordering {
a.bytes().map(|c| c.to_ascii_lowercase()).cmp(b.bytes().map(|c| c.to_ascii_lowercase()))
}
/// Whether `word` holds `query` anywhere in it, ignoring ASCII case — the
/// match `WorkspaceIndex::workspace_symbols` makes, which
/// [`Candidates::modules`] has to make the same way to answer the same set.
fn contains_ignore_case(word: &str, query: &str) -> bool {
if query.is_empty() {
return true;
}
let query = query.as_bytes();
word.as_bytes().windows(query.len()).any(|window| window.eq_ignore_ascii_case(query))
}
/// Whether `word` starts with `prefix`, ignoring ASCII case.
pub fn starts_with_ignore_case(word: &str, prefix: &str) -> bool {
word.len() >= prefix.len()
@@ -446,6 +555,34 @@ mod tests {
assert!(!names.contains(&"never_seen"), "{names:?}");
}
/// The module table exists to answer what `vlog_refactor::module_names`
/// answers without the index rebuilding its whole symbol table per
/// keystroke, so the two must agree — set *and* order — at every query.
/// A substring match, not a prefix one: `module_names` asks the index for
/// `contains`, and `prim_aes_sbox` is an answer to `aes`.
#[test]
fn the_module_table_answers_exactly_what_module_names_answers() {
let files = [
("/rtl/aes.sv", "module aes;\nendmodule\npackage aes_pkg;\nendpackage\n"),
("/rtl/aes_reg_top.sv", "module aes_reg_top;\nendmodule\n"),
("/rtl/prim.sv", "module prim_aes_sbox;\nendmodule\nmodule PRIM_UPPER;\nendmodule\n"),
("/rtl/other.sv", "interface i;\nendinterface\nclass c;\nendclass\n"),
// A module name two files declare — one entry, not two.
("/rtl/twin_a.sv", "module twin;\nendmodule\n"),
("/rtl/twin_b.sv", "module twin;\nendmodule\n"),
];
let srcs = sources(&files);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let candidates = Candidates::build(&index, &srcs, HashMap::new());
for query in ["", "a", "ae", "aes", "AES", "prim", "PRIM", "_", "twin", "zzz", "aes_reg"] {
assert_eq!(
candidates.modules(query),
vlog_refactor::module_names(&index, query),
"query {query:?}"
);
}
}
// ------------------------------------------------------------------
// QA (incremental-index, 2026-08-27): `word_files`'s exact bookkeeping
// ------------------------------------------------------------------
@@ -501,4 +638,81 @@ mod tests {
candidates.remove_file(&current, Path::new("/rtl/a.sv"));
assert!(candidates.words("w2").is_empty(), "removing an already-removed file is a no-op");
}
#[test]
fn a_batch_absorbed_leaves_the_word_table_a_whole_build_would_have_sorted() {
// The scope widen's own path, and since 2026-08-29 the batch pays one
// merge instead of one insert per word. The claim that buys is exact:
// what comes out is the table `build` sorts from the same counts. The
// hostile cases are all in this one batch — a word only one of the
// batch's files still holds, a word the batch takes from one file and
// gives back through another, a word nothing holds afterwards, and
// case variants, which `word_cmp` orders case-insensitively first and
// exactly second.
let held = [
(
"/rtl/a.sv",
"module a;\n logic Shared;\n logic only_a;\n logic gone;\nendmodule\n",
),
("/rtl/b.sv", "module b;\n logic shared;\n logic Only_B;\nendmodule\n"),
];
let after = [
// `a.sv` rewritten: `gone` leaves the workspace, `only_a` leaves
// this file but arrives in `c.sv` in the same batch.
("/rtl/a.sv", "module a;\n logic Shared;\n logic zeta;\n logic Alpha;\nendmodule\n"),
("/rtl/b.sv", "module b;\n logic shared;\n logic Only_B;\nendmodule\n"),
(
"/rtl/c.sv",
"module c;\n logic shared;\n logic alpha;\n logic only_a;\nendmodule\n",
),
("/rtl/d.sv", "module d;\n logic ALPHA;\n logic mid;\nendmodule\n"),
];
let held_srcs = sources(&held);
let held_index =
WorkspaceIndex::build(held_srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut widened = Candidates::build(&held_index, &held_srcs, HashMap::new());
let srcs = sources(&after);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let batch: Vec<(PathBuf, Vec<String>)> = after
.iter()
.filter(|(path, _)| *path != "/rtl/b.sv")
.map(|(path, text)| (PathBuf::from(*path), words_in(text)))
.collect();
widened.absorb(&index, batch);
let rebuilt = Candidates::build(&index, &srcs, HashMap::new());
assert_eq!(widened.words(""), rebuilt.words(""), "the whole table, in order");
for prefix in ["", "a", "al", "ALPHA", "shared", "only", "only_a", "gone", "z", "zzz"] {
assert_eq!(widened.words(prefix), rebuilt.words(prefix), "prefix {prefix:?}");
}
assert_eq!(widened.words("gone").len(), 0, "the word nothing holds any more");
assert_eq!(widened.words("only_a").len(), 1, "taken and given back inside one batch");
}
#[test]
fn qa_extra_empty_and_noop_batches_do_not_disturb_the_table() {
let held = [("/rtl/a.sv", "module a;\n logic w1;\n logic w2;\nendmodule\n")];
let held_srcs: Vec<(PathBuf, String)> =
held.iter().map(|(p, t)| (PathBuf::from(*p), t.to_string())).collect();
let index = WorkspaceIndex::build(held_srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut c = Candidates::build(&index, &held_srcs, HashMap::new());
let before = c.words("").to_vec();
// Empty batch: nothing to absorb.
c.absorb(&index, Vec::new());
assert_eq!(c.words(""), before.as_slice(), "empty batch changes nothing");
// Batch that re-declares exactly the same words for the same file
// (the module name "a" included, or dropping it would be a real
// change): no net change to the counts, so no add or drop should
// survive to the merge.
let batch: Vec<(PathBuf, Vec<String>)> = vec![(
PathBuf::from("/rtl/a.sv"),
vec!["a".to_string(), "w1".to_string(), "w2".to_string()],
)];
c.absorb(&index, batch);
assert_eq!(c.words(""), before.as_slice(), "re-declaring the same words is a no-op");
}
}
+444 -5
View File
@@ -33,7 +33,7 @@ use lsp_types::{
use vlog_parser::token::{Comment, Token, TokenKind};
use vlog_parser::{TextRange, KEYWORDS};
use vlog_refactor::{InstantiationPlan, Layout, Site};
use vlog_semantic::{Semantics, Symbol, SymbolKind};
use vlog_semantic::{Semantics, Symbol, SymbolKind, WorkspaceIndex};
use crate::candidates::starts_with_ignore_case;
use crate::pairs;
@@ -59,6 +59,19 @@ const LIMIT: usize = 512;
/// table built at index time. Unchanged from M4.
const MODULE_LIMIT: usize = 64;
/// How far past a module's name [`module_header`] reads looking for the end of
/// its header, smallest first.
///
/// A ladder rather than one bound because the lex is the whole cost of the
/// slice and it is linear in what it is handed, so every header would
/// otherwise pay for the widest one. The rungs come from measuring opentitan's
/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB,
/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB.
/// The top rung is well past that, because a rung that is too small is not a
/// wrong answer but a whole-file parse, and for those files that is 2–4 ms
/// against the 0.6 ms of lexing 16 KB.
const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024];
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
/// order; the name follows so each tier is alphabetical within itself.
const TIER_MODULE: char = '0';
@@ -211,7 +224,10 @@ fn module_tier(
let layout = layout_at(ws, doc, word.start);
let site = Site { semantics: &doc.semantics, offset: word.start };
let names = vlog_refactor::module_names(ws.index(), &word.text);
// The same names `vlog_refactor::module_names` answers, off the table
// built with the index instead of off the index's whole symbol table —
// which the old call rebuilt and re-sorted on every keystroke.
let names = ws.candidates().modules(&word.text);
if names.len() > MODULE_LIMIT {
items.incomplete = true;
}
@@ -220,14 +236,145 @@ fn module_tier(
// is silently skipped: a completion list is not the place to argue.
let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue };
let Some(definition) = ws.text_of(path) else { continue };
let Ok(plan) = vlog_refactor::instantiation_plan(name, &definition, Some(site)) else {
continue;
};
let Ok(plan) = plan_for(ws.index(), name, &definition, site) else { continue };
let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string();
items.push(item(&plan, &layout, word.range(cursor), doc, &file, snippets));
}
}
/// One module's instantiation plan, off its header alone where that is the
/// whole of what the plan reads, and off its whole file otherwise.
///
/// The slice is an optimisation and never an answer of its own. Two things
/// send this back to the whole file, and both leave the answer exactly what it
/// was before the slice existed:
///
/// * the slice does not plan at all — [`module_header`] cut a header this
/// parser does not read as one;
/// * the plan it produced has a port with neither a direction nor a type,
/// which is what a **non-ANSI** port list looks like once its body is gone:
/// `module m (a); input wire a;` writes the direction below the header, and
/// the body is the part the slice drops.
fn plan_for(
index: &WorkspaceIndex,
module: &str,
definition: &str,
site: Site<'_>,
) -> Result<InstantiationPlan, String> {
let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site));
let Some(header) = module_header(index, module, definition) else { return whole() };
match vlog_refactor::instantiation_plan(module, &header, Some(site)) {
Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan),
_ => whole(),
}
}
/// The text one skeleton is planned from: the declaring file's header alone
/// where this function can find it, and the whole file where it cannot.
///
/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed
/// the whole declaring file — three hundred lines of body to read a header a
/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads
/// nothing but the header, so nothing but the header needs to be parsed.
///
/// The prefix is kept **byte for byte**: every span the plan reads is an offset
/// into the text it was parsed from, so cutting the front off would move them
/// all. Only the body is dropped, and an `endmodule` is written in its place so
/// the declaration is closed.
pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option<String> {
let [def] =
index.units(module).iter().filter(|d| d.kind == SymbolKind::Module).collect::<Vec<_>>()[..]
else {
return None;
};
let name = def.name_span;
// The index's span is as of the last scan. A file edited on disk since
// then has moved it, and a slice taken at a stale offset would be a
// different module's header — so the name has to still be there.
if text.get(name.start as usize..name.end as usize) != Some(module) {
return None;
}
let from = name.end as usize;
for size in HEADER_WINDOWS {
// A window that cuts a block comment or a string in half does not lex,
// and one that cuts the port list in half runs out of tokens before
// the `;`. Both answer "not in this window" and are asked again at the
// next rung; both answer `None` at the last one.
let window = text.get(from..text.len().min(from + size))?;
if let Ok(tokens) = vlog_parser::tokenize(window) {
if let Some(end) = header_end(&tokens) {
let head = text.get(..from + end as usize)?;
return Some(format!("{head}\nendmodule\n"));
}
}
if from + size >= text.len() {
break;
}
}
None
}
/// Where the header that begins just after a module's name ends: the offset
/// one past its terminating `;`, in the window's own coordinates.
///
/// A **whitelist**, not a scan for the first `;`: `module aes import
/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the
/// header. Anything this does not recognise — a compiler directive between the
/// name and the port list, a header longer than the window — answers `None`,
/// and the caller parses the whole file rather than guessing.
fn header_end(tokens: &[Token]) -> Option<u32> {
let mut at = 0;
loop {
let token = tokens.get(at)?;
match token.text.as_str() {
";" => return Some(token.span.end),
// A lifetime qualifier: `module automatic foo (...);`.
"static" | "automatic" => at += 1,
// A package import written into the header, whose own `;` is not
// the header's.
"import" => at = skip_to_semicolon(tokens, at + 1)?,
// The parameter list, the port list, and an attribute instance —
// each one parenthesised, each one skipped whole.
"#" | "(" => at = skip_parens(tokens, at)?,
_ => return None,
}
}
}
/// Past the parenthesised group starting at `at`, which a `#` may introduce.
fn skip_parens(tokens: &[Token], mut at: usize) -> Option<usize> {
while tokens.get(at)?.text == "#" {
at += 1;
}
if tokens.get(at)?.text != "(" {
return None;
}
let mut depth = 0i32;
loop {
match tokens.get(at)?.text.as_str() {
"(" => depth += 1,
")" if depth == 1 => return Some(at + 1),
")" => depth -= 1,
_ => {}
}
at += 1;
}
}
/// Past the next `;` written outside any parentheses.
fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
let mut depth = 0i32;
loop {
match tokens.get(at)?.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
";" if depth == 0 => return Some(at + 1),
_ => {}
}
at += 1;
}
}
/// Tier 1: everything the scope chain at the cursor binds.
fn scope_tier(items: &mut Items, doc: &Document, word: &Word) {
for symbol in visible_symbols(&doc.semantics, word.start) {
@@ -1040,6 +1187,298 @@ endmodule
items.iter().map(|item| item.label.as_str()).collect()
}
// ------------------------------------------------------------------
// tier 0's header slice (2026-08-28) — it must change no answer
// ------------------------------------------------------------------
/// Every header shape the slice has to survive, as (file text, module).
///
/// The list is the argument that the slice changes nothing: each entry is
/// planned both ways below and the two plans are compared field by field.
const SHAPES: &[(&str, &str)] = &[
// The ordinary ANSI header, params and all.
(SUB, "sub"),
// No ports at all.
("module bare;\nendmodule\n", "bare"),
// An empty port list.
("module empty ();\n logic x;\nendmodule\n", "empty"),
// A package import written into the header: its `;` is not the
// header's, and a slice that stopped there would report no ports.
(
"package p;\n localparam int W = 4;\nendpackage\n\
module imported import p::*; #(\n parameter int W = 8\n) (\n \
input logic clk,\n output logic [W-1:0] q\n);\n \
assign q = '0;\nendmodule\n",
"imported",
),
// Two imports, then a parameter list.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
"twice",
),
// A **non-ANSI** port list: the directions live in the body, which is
// exactly what the slice drops.
(
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
always @* b = |a;\nendmodule\n",
"old",
),
// Non-ANSI with nothing declaring the ports at all.
("module silent (a, b);\nendmodule\n", "silent"),
// A comment and an attribute inside the header.
(
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
input logic clk\n);\nendmodule\n",
"noisy",
),
// A lifetime qualifier.
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
// A second module in the same file, after the one being planned.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"first",
),
// …and before it, so the slice's prefix carries a whole module.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"second",
),
// A compiler directive between the name and the port list, which the
// whitelist refuses outright.
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
// A directive *inside* the port list, which carries a warning the two
// plans must both raise.
(
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
`endif\n);\nendmodule\n",
"ifdefd",
),
// An escaped identifier for the module and for a port.
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
// A header longer than the first rung of the window ladder.
(WIDE, "wide"),
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
// instance, `(* ... *)`, right after the module name and before the
// parameter list — the one shape the "noisy" case above is commented
// as covering but does not (it has two comments, no attribute).
// **Finding, not a regression this round introduced**: a module with
// an attribute anywhere near its header is not indexed as a `Module`
// unit at all (see
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
// so this pins the safe side effect — `module_header` declines before
// its whitelist walk ever runs — rather than the whitelist's own
// handling of attributes, which this shape cannot reach.
(
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
input logic clk\n);\nendmodule\n",
"attributed",
),
// An attribute instance *inside* the port list, attached to one port.
// Same finding as `attributed`: not indexed, so not reached either.
(
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
);\nendmodule\n",
"port_attributed",
),
// A single import declaration naming several packages, comma
// separated (`import a::*, b::*;`) — one statement, not two, and the
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module chained import p::*, q::*; (input logic a);\nendmodule\n",
"chained",
),
// A parameter default whose string literal carries the exact bytes
// the whitelist watches for — `;` and `)` — which must stay inside
// the `String` token and never be mistaken for header punctuation.
(
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
input logic clk\n);\nendmodule\n",
"stringy",
),
// CRLF line endings through the whole header.
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
];
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
input logic port_number_one_with_a_long_name,\n \
input logic port_number_two_with_a_long_name,\n \
input logic port_number_three_with_a_long_name,\n \
input logic port_number_four_with_a_long_name,\n \
input logic port_number_five_with_a_long_name,\n \
output logic port_number_six_with_a_long_name\n);\n \
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
/// The whole argument for the slice: for every shape above, the plan built
/// from the header alone is the plan built from the whole file. Where it
/// would not be — a non-ANSI list, a header the whitelist refuses — the
/// guard in [`plan_for`] sends the question back to the whole file, so the
/// comparison holds there too.
#[test]
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
for (text, module) in SHAPES {
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
let ours = plan_for(&index, module, text, site);
assert_eq!(ours, whole, "{module}");
}
}
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
/// trivially for a shape the whitelist declines — both sides parse the
/// whole file, so a wrong slice could hide behind that. These shapes must
/// actually slice, so the comparison exercises the whitelist walk it is
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
/// `;`/`)` sitting inside a string literal, and CRLF endings.
#[test]
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
module_header(&index, module, text).is_some(),
"{module}: expected the header to actually slice, not fall back whole-file"
);
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// anywhere near its header — right after its name, or on one of its
/// ports — is not indexed as a `Module` unit **at all**.
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
/// at the very first line (no `[def]` to anchor on) before the whitelist
/// walk ever runs, and completion's module tier — which sources its
/// candidate names from the same table — never offers the module in the
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
/// completion-core one: it is filed in `docs/features/completion-core/
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
/// outside this round's touched files. The two "attribute" shapes this QA
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
/// because both sides of that comparison fall back to the same whole-file
/// parse, which this test makes explicit rather than leaving it as an
/// unremarked side effect of the pin.
#[test]
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
for module in ["attributed", "port_attributed"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units(module).is_empty(),
"{module}: if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(
module_header(&index, module, text).is_none(),
"{module}: no unit to anchor on"
);
}
}
/// The guard is not decoration: a non-ANSI module really does plan
/// differently off its header, and really is sent back to the whole file.
#[test]
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
let path = PathBuf::from("/rtl/old.sv");
let index = WorkspaceIndex::build(vec![(path, text)]);
let header = module_header(&index, "old", text).expect("the header slices");
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
assert!(
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
"premise: the header alone knows nothing about these ports"
);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let guarded = plan_for(&index, "old", text, site).expect("a plan");
assert_eq!(guarded.ports[0].dir, "input");
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
}
/// The whole answer, pinned at the prefixes the hot path is worst at — the
/// empty one and a one-character one, where every tier is at its widest.
/// Tier 0 is what the slice changed, so the pin spells out every skeleton's
/// label *and* the text it inserts, which is the part a wrong header would
/// corrupt.
#[test]
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
let tree = Tree::new("pinned");
tree.write("sub.sv", SUB);
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
let (_tree, mut ws, uri, _) =
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
// Nothing typed, then one character — the two widest requests there
// are. `top` is in the answer because the buffer declares it and the
// index holds it like any other module.
let mut answer = |typed: &str| {
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
+ typed.len() as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
items(completions(&ws, &uri, position, true))
};
for (typed, expected) in
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
{
let items = answer(typed);
let found: Vec<&str> =
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
assert_eq!(found, expected, "skeletons after typing {typed:?}");
}
// …and the exact text one of them inserts, ports, defaults and all.
let items = answer("");
assert_eq!(
inserted(find(&items, "sub").expect("the skeleton")),
"\
sub #(
.WIDTH(${1:8})
) ${2:u_sub} (
.clk(clk),
.data(${3:data}),
.ready(${4:ready})
);"
);
assert_eq!(
inserted(find(&items, "alpha").expect("the skeleton")),
"alpha ${1:u_alpha} (\n .clk(clk)\n );"
);
assert_eq!(
inserted(find(&items, "submarine").expect("the skeleton")),
"submarine ${1:u_submarine} ();"
);
}
/// A file edited on disk since the index last read it has moved every span
/// the index holds, so the slice must not take one on trust.
#[test]
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
let text =
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
// The same index against a file whose text has shifted underneath it.
let moved = format!("// a line nobody told the index about\n{text}");
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
}
// ------------------------------------------------------------------
// tier 0 — module hinting (M4, unchanged behaviour)
// ------------------------------------------------------------------
+6 -8
View File
@@ -24,15 +24,13 @@ impl<'a> Positions<'a> {
/// The LSP position of a byte offset. An offset inside a multi-byte
/// character is floored to that character's start.
///
/// The conversion itself lives on [`LineIndex`], so that the semantic
/// index — which records the same positions for a declaration while its
/// file is scanned — cannot answer differently from the wire.
pub fn position(&self, offset: u32) -> Position {
let offset = self.floor_boundary(offset);
let (line, _) = self.index.line_col(offset);
let start = self.index.line_range(line).map_or(0, |r| r.start) as usize;
let slice = self.text.get(start..offset as usize).unwrap_or("");
// LSP line content excludes the whole `\r\n`; `LineIndex` keeps the
// `\r` as an ordinary byte of its line, so drop it here.
let slice = slice.strip_suffix('\r').unwrap_or(slice);
Position { line: line - 1, character: utf16_len(slice) }
let (line, character) = self.index.utf16_position(self.text, offset);
Position { line, character }
}
/// A cursor for converting many byte offsets in one non-decreasing sweep,
@@ -0,0 +1,500 @@
//! The VS Code instance-oriented design hierarchy.
//!
//! LSP call hierarchy deliberately groups a module's calls by target module
//! type. The sidebar needs the other view of the same facts: every individual
//! instance name, its source range, and every declaration its module type may
//! name. The response stays flat; the client chooses roots and expands paths,
//! which keeps recursion out of the protocol and lets one snapshot serve
//! search as well as rendering.
//!
//! **Two things this answer must not be, and the shape follows from both.** It
//! must not read files — every line and character below was converted once,
//! when the declaring file was scanned, and rides the index
//! (`vlog_semantic::DeclPositions`, `InstanceOccurrence::positions`). And it
//! must not be enormous: a whole design re-sent on every save is a message the
//! request queue is blocked writing. So a URI is written **once**, in `files`,
//! and every location names it by index; a range is four numbers rather than
//! four nested objects; a row carries no id, because the client can compose the
//! one it used to be sent; and an instance carries no copy of the declarations
//! its module name resolves to, because the client already has every module.
//! Those four together are 11.6 MB → 1.9 MB on opentitan, and the client
//! rebuilds the richer shape in `hierarchyModel.js`'s `validateSnapshot` — see
//! `docs/features/vscode-hierarchy-sidebar/README.md`.
use std::collections::HashMap;
use serde::Serialize;
use vlog_semantic::{FileId, SymbolKind, Utf16Range, WorkspaceIndex};
use crate::state::Workspace;
use crate::uri::path_to_uri;
pub const METHOD: &str = "lucisv/moduleHierarchy";
pub const CHANGED_METHOD: &str = "lucisv/moduleHierarchyChanged";
/// The wire version. Bumped on any change to the shape below; the client
/// refuses a snapshot it does not recognise rather than half-reading one.
const SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
schema_version: u32,
revision: u64,
complete: bool,
/// Every file a location below names, once. Locations index into this.
files: Vec<String>,
modules: Vec<Module>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Module {
module_name: String,
definition: Location,
instances: Vec<Instance>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Instance {
instance_name: String,
module_name: String,
site: Location,
}
/// A place in the workspace: which file, the whole construct, and the name
/// inside it. Each range is `[startLine, startCharacter, endLine,
/// endCharacter]`, 0-based lines and UTF-16 characters — an LSP `Range` with
/// its four field names left off.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Location {
file: u32,
range: [u32; 4],
selection_range: [u32; 4],
}
/// A complete snapshot of the index currently installed in `workspace`.
///
/// **It reads no files.** The first shape of this function read every
/// module-declaring file and built a `LineIndex` over each — 5.0 s cold and
/// ~300 ms warm on opentitan, on *every* request, which is the per-request
/// whole-workspace read the release before it existed to kill.
///
/// `complete` is false only when the request arrived between two files of the
/// startup scan. The server sends `CHANGED_METHOD` when that scan lands, so a
/// client can render the partial answer as loading and replace it once.
pub fn snapshot(workspace: &Workspace, revision: u64, complete: bool) -> Snapshot {
let index = workspace.index();
let mut files = FileTable::default();
let mut modules = Vec::new();
let mut module_at = HashMap::new();
for (name, def) in index.units_of(SymbolKind::Module) {
// Every file-scope declaration carries its positions; one without them
// would be a declaration the index built by some other route, and
// dropping it beats inventing a range for it.
let Some(positions) = def.lines.positions else { continue };
let Some(file) = files.of(index, def.file) else { continue };
module_at.insert((def.file, def.name_span.start, def.name_span.end), modules.len());
modules.push(Module {
module_name: name.to_string(),
definition: location(file, positions.name, positions.decl),
instances: Vec::new(),
});
}
for (target_name, edges) in index.instantiations() {
for edge in edges {
let owner = (edge.file, edge.owner.name_span.start, edge.owner.name_span.end);
let Some(&owner_at) = module_at.get(&owner) else { continue };
let Some(file) = files.of(index, edge.file) else { continue };
for occurrence in &edge.instances {
modules[owner_at].instances.push(Instance {
instance_name: occurrence.name.clone(),
module_name: target_name.to_string(),
site: location(file, occurrence.name_positions, occurrence.positions),
});
}
}
}
// `sort_by_cached_key`, not `sort_by`: both keys lowercase a name, and
// paying for that once per element rather than twice per comparison is the
// difference between a few and a few hundred thousand allocations on a
// workspace with 14 000 instances in it.
for module in &mut modules {
module.instances.sort_by_cached_key(|instance| instance_key(&files, instance));
}
modules.sort_by_cached_key(|module| module_key(&files, module));
Snapshot { schema_version: SCHEMA_VERSION, revision, complete, files: files.uris, modules }
}
/// The snapshot's file table: one URI per file, given an index the first time
/// a location needs it.
#[derive(Default)]
struct FileTable {
uris: Vec<String>,
at: HashMap<FileId, Option<u32>>,
}
impl FileTable {
/// This file's index, adding it if it is new. `None` for a path that is
/// not a URI — the same answer every other feature gives for such a path,
/// and it drops that file's rows rather than the whole snapshot.
fn of(&mut self, index: &WorkspaceIndex, file: FileId) -> Option<u32> {
if let Some(&known) = self.at.get(&file) {
return known;
}
let found = index.path(file).and_then(path_to_uri).map(|uri| {
self.uris.push(uri.as_str().to_string());
self.uris.len() as u32 - 1
});
self.at.insert(file, found);
found
}
fn uri(&self, file: u32) -> &str {
self.uris.get(file as usize).map_or("", |uri| uri.as_str())
}
}
/// One location, built from ranges the index already holds.
fn location(file: u32, selection: Utf16Range, whole: Utf16Range) -> Location {
Location { file, range: range(whole), selection_range: range(selection) }
}
fn range(range: Utf16Range) -> [u32; 4] {
[range.start.line, range.start.character, range.end.line, range.end.character]
}
fn module_key(files: &FileTable, module: &Module) -> (String, String, u32, u32) {
(
module.module_name.to_ascii_lowercase(),
files.uri(module.definition.file).to_string(),
module.definition.selection_range[0],
module.definition.selection_range[1],
)
}
fn instance_key(files: &FileTable, instance: &Instance) -> (String, String, String, u32, u32) {
(
instance.instance_name.to_ascii_lowercase(),
instance.module_name.to_ascii_lowercase(),
files.uri(instance.site.file).to_string(),
instance.site.selection_range[0],
instance.site.selection_range[1],
)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{json, Value};
use std::path::PathBuf;
struct Tree(PathBuf);
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_design_hierarchy_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree(path)
}
fn write(&self, name: &str, text: &str) {
std::fs::write(self.0.join(name), text).expect("write fixture");
}
fn workspace(&self) -> Workspace {
let mut workspace = Workspace::default();
workspace.open_whole_workspace(vec![self.0.clone()]);
workspace
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn taken(workspace: &Workspace) -> Value {
serde_json::to_value(snapshot(workspace, 7, true)).expect("serializes")
}
#[test]
fn a_snapshot_is_flat_sorted_and_keeps_every_individual_instance() {
let tree = Tree::new("flat");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf zed (), alpha ();\nendmodule\n");
tree.write("tb.sv", "module TB; top dut (); missing u_missing (); endmodule\n");
let value = taken(&tree.workspace());
assert_eq!(value["schemaVersion"], 2);
assert_eq!(value["revision"], 7);
assert_eq!(value["complete"], true);
let modules = value["modules"].as_array().expect("modules");
let names: Vec<&str> =
modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect();
assert_eq!(names, ["leaf", "TB", "top"], "case-insensitive alphabetical order");
let top = module(modules, "top");
// `[startLine, startCharacter, endLine, endCharacter]`: the whole
// module for `range`, its name alone for `selectionRange`.
assert_eq!(top["definition"]["range"], json!([0, 0, 2, 9]));
assert_eq!(top["definition"]["selectionRange"], json!([0, 7, 0, 10]));
let instances = top["instances"].as_array().expect("instances");
let names: Vec<&str> = instances
.iter()
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
assert_eq!(names, ["alpha", "zed"], "one statement became two sorted children");
let tb = module(modules, "TB");
let missing = tb["instances"]
.as_array()
.expect("instances")
.iter()
.find(|instance| instance["instanceName"] == "u_missing")
.expect("unresolved instance is still a row");
// Nothing on the wire says "unresolved": the client asks its own module
// table for `missing`, finds none, and that is the same answer.
assert_eq!(missing["moduleName"], "missing");
assert_eq!(missing["site"]["selectionRange"][0], 0);
}
/// The round's central claim, pinned the way `hover-line-index` pinned its
/// own: delete every source file after indexing, and the answer is
/// byte-identical, because no part of it comes from a file.
#[test]
fn a_snapshot_reads_no_files_at_all() {
let tree = Tree::new("noreads");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf u_leaf ();\nendmodule\n");
let workspace = tree.workspace();
let before = taken(&workspace);
assert_eq!(
before["modules"].as_array().expect("modules").len(),
2,
"premise: both indexed"
);
for name in ["leaf.sv", "top.sv"] {
std::fs::remove_file(tree.0.join(name)).expect("delete");
}
assert_eq!(taken(&workspace), before, "the snapshot came from the index, not the disk");
}
/// A URI appears once however many rows name it, and a range is four
/// numbers — the two decisions that took the opentitan answer from 11.6 MB
/// to under 2 MB.
#[test]
fn every_file_is_named_once_and_a_range_is_four_numbers() {
let tree = Tree::new("filetable");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf a (), b (), c ();\nendmodule\n");
let value = taken(&tree.workspace());
let files = value["files"].as_array().expect("files");
assert_eq!(files.len(), 2, "one entry per file, not one per row: {files:#?}");
let text = serde_json::to_string(&value).expect("serializes");
for uri in files {
let uri = uri.as_str().expect("a uri string");
assert_eq!(text.matches(uri).count(), 1, "{uri} is written more than once");
}
let top = module(value["modules"].as_array().expect("modules"), "top");
for instance in top["instances"].as_array().expect("instances") {
assert!(instance["site"]["file"].is_number(), "a file index, not a URI");
assert_eq!(instance["site"]["range"].as_array().expect("range").len(), 4);
}
}
/// Positions are the client's, not the index's: 0-based lines and UTF-16
/// code units, so a two-byte character before a name still counts one.
#[test]
fn positions_are_zero_based_utf16_even_through_multibyte_text() {
let tree = Tree::new("utf16");
// `🎉` is four UTF-8 bytes and two UTF-16 units, so every column after
// it on that line differs from the byte column the index records.
tree.write("m.sv", "module top;\n /*\u{1F389}*/ sub u_x ();\nendmodule\n");
let value = taken(&tree.workspace());
let top = module(value["modules"].as_array().expect("modules"), "top");
assert_eq!(
top["definition"]["selectionRange"],
json!([0, 7, 0, 10]),
"line 0 counting from 0, `top` at character 7"
);
let instance = &top["instances"].as_array().expect("instances")[0];
assert_eq!(instance["instanceName"], "u_x");
assert_eq!(instance["site"]["selectionRange"], json!([1, 13, 1, 16]));
assert_eq!(instance["site"]["range"], json!([1, 13, 1, 19]));
}
/// **The one property the whole zero-I/O trick rests on**: a position the
/// index recorded while a file was scanned is the position `convert` would
/// have produced from that file's text on the wire. The two answers come
/// from one function on `LineIndex`, and this is what says so out loud —
/// over the shapes that break naive conversions.
#[test]
fn an_indexed_position_is_the_position_the_wire_converter_would_have_given() {
let sources = [
"module plain;\n sub u ();\nendmodule\n",
// A CRLF file: `\r` is a byte of its line but not of its content.
"module crlf;\r\n sub u_crlf ();\r\nendmodule\r\n",
// Two, three and four byte characters ahead of the names.
"// \u{e9}\u{2713}\u{1F389}\nmodule wide;\n /*\u{1F389}*/ sub u_wide ();\nendmodule\n",
// A name on the last line, with no trailing newline at all.
"module tail;\n sub u_tail ();\nendmodule",
// Two instances in one statement, and an attribute before `module`.
"(* keep *) module many;\n sub a (), b ();\nendmodule\n",
// CRLF and bare LF mixed in one file: the `\r`-stripping rule must
// apply per line, not once for the whole file.
"module mixed;\r\n sub u_a ();\n sub u_b ();\r\nendmodule\n",
// The instance on the very same line as the module header, so the
// name and the instance share a line's worth of UTF-16 columns.
"module oneline; sub u_same ();\nendmodule\n",
];
let tree = Tree::new("agreement");
let mut texts = Vec::new();
for (at, source) in sources.iter().enumerate() {
tree.write(&format!("f{at}.sv"), source);
texts.push((tree.0.join(format!("f{at}.sv")), *source));
}
let workspace = tree.workspace();
let index = workspace.index();
let mut checked = 0usize;
for (path, text) in &texts {
let lines = vlog_parser::LineIndex::new(text);
let positions = crate::convert::Positions::new(text, &lines);
let file = index.file_id(path).expect("the file is indexed");
for (_, def) in index.units_of(vlog_semantic::SymbolKind::Module) {
if def.file != file {
continue;
}
let recorded = def.lines.positions.expect("a unit carries positions");
assert_eq!(range(recorded.name), as_four(positions.range(def.name_span)));
assert_eq!(range(recorded.decl), as_four(positions.range(def.decl_span)));
checked += 1;
}
for (_, edges) in index.instantiations() {
for edge in edges.iter().filter(|edge| edge.file == file) {
for occurrence in &edge.instances {
assert_eq!(
range(occurrence.name_positions),
as_four(positions.range(occurrence.name_span))
);
assert_eq!(
range(occurrence.positions),
as_four(positions.range(occurrence.span))
);
checked += 1;
}
}
}
}
assert!(checked >= 16, "premise: every fixture contributed rows, got {checked}");
}
/// QA (2026-08-29): two files declaring the same module name must each
/// keep their own row, their own instances, and never merge — the wire's
/// only handle on a module is `(file, definition range)`, exactly as an
/// ambiguous type is meant to look on the client.
#[test]
fn duplicate_module_names_across_files_stay_two_distinct_rows() {
let tree = Tree::new("duplicate");
tree.write("a.sv", "module dup;\n sub u_in_a ();\nendmodule\n");
tree.write("b.sv", "module dup;\n sub u_in_b ();\nendmodule\n");
tree.write("sub.sv", "module sub; endmodule\n");
let value = taken(&tree.workspace());
let modules = value["modules"].as_array().expect("modules");
let dups: Vec<&Value> =
modules.iter().filter(|module| module["moduleName"] == "dup").collect();
assert_eq!(dups.len(), 2, "one row per declaration, not one merged row: {dups:#?}");
assert_ne!(
dups[0]["definition"]["file"], dups[1]["definition"]["file"],
"the only thing distinguishing them is which file",
);
let mut instance_names: Vec<&str> = dups
.iter()
.flat_map(|module| module["instances"].as_array().expect("instances"))
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
instance_names.sort_unstable();
assert_eq!(
instance_names,
["u_in_a", "u_in_b"],
"each declaration keeps only the instances its own body writes",
);
}
/// QA (2026-08-29): an escaped Verilog identifier (`\foo$bar `, terminated
/// by whitespace, the space itself not part of the name) is as ordinary a
/// module or instance name as any other — the wire and the position
/// conversion must not choke on the backslash or the trailing space.
#[test]
fn an_escaped_identifier_names_a_module_and_an_instance() {
let tree = Tree::new("escaped");
tree.write(
"m.sv",
"module \\weird$leaf ;\nendmodule\n\
module top;\n \\weird$leaf \\u$inst ();\nendmodule\n",
);
let value = taken(&tree.workspace());
let modules = value["modules"].as_array().expect("modules");
let leaf = module(modules, "\\weird$leaf");
assert_eq!(leaf["instances"].as_array().expect("instances").len(), 0);
let top = module(modules, "top");
let instances = top["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 1);
assert_eq!(instances[0]["instanceName"], "\\u$inst");
assert_eq!(instances[0]["moduleName"], "\\weird$leaf");
}
/// QA (2026-08-29): a module instantiated 100 times in one statement list
/// produces 100 individual, individually sorted instance rows — the
/// flattening the sidebar exists for, at a scale one instance would not
/// exercise.
#[test]
fn one_hundred_instances_of_one_module_are_one_hundred_sorted_rows() {
let tree = Tree::new("manyinstances");
tree.write("leaf.sv", "module leaf; endmodule\n");
let instances: Vec<String> = (0..100).map(|n| format!("u_{n:03} ()", n = n)).collect();
tree.write(
"top.sv",
&format!("module top;\n leaf {};\nendmodule\n", instances.join(", ")),
);
let value = taken(&tree.workspace());
let top = module(value["modules"].as_array().expect("modules"), "top");
let instances = top["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 100, "every one of the 100 instances is its own row");
let names: Vec<&str> = instances
.iter()
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
let mut sorted = names.clone();
sorted.sort_unstable();
assert_eq!(names, sorted, "sorted by instance name, as every module's instances are");
assert!(instances.iter().all(|instance| instance["moduleName"] == "leaf"));
}
fn as_four(range: lsp_types::Range) -> [u32; 4] {
[range.start.line, range.start.character, range.end.line, range.end.character]
}
fn module<'a>(modules: &'a [Value], name: &str) -> &'a Value {
modules
.iter()
.find(|module| module["moduleName"] == name)
.unwrap_or_else(|| panic!("no module {name}: {modules:#?}"))
}
}
+153 -5
View File
@@ -105,10 +105,15 @@ pub struct Rewrite {
/// Rewrite every `` `include`` in the workspace that resolves to a file the
/// client is about to rename.
///
/// The sweep reads the in-scope files (`Workspace::sources`, so an unopened
/// file is read off disk and an open buffer contributes its unsaved text), and
/// asks the include graph — never the filename — which of them point at
/// something that moves.
/// The sweep reads the files the include graph recorded an `` `include`` in
/// (`Workspace::include_sources`, so an unopened one is read off disk and an
/// open buffer contributes its unsaved text), and asks the include graph —
/// never the filename — which of them point at something that moves.
///
/// It used to read *every* in-scope file, which on a 3 976-file workspace is
/// 3 900-odd reads to answer "this file has no `` `include``". The graph
/// already holds that answer; the argument that the smaller set gives the
/// identical `Rewrite` is in `docs/features/file-operations/README.md`.
pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
let moves = Moves::announced(files);
if moves.0.is_empty() {
@@ -117,7 +122,7 @@ pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
let graph = ws.includes();
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
let mut warnings = Vec::new();
for (path, text) in ws.sources() {
for (path, text) in ws.include_sources() {
// The overwhelming majority of files include nothing; one substring
// test each is what keeps this off the resolver for all of them.
if !text.contains("`include") {
@@ -542,6 +547,35 @@ mod tests {
path_to_uri(path).expect("uri").as_str().to_string()
}
/// The sufficiency property [`will_rename`]'s narrowed sweep rests on,
/// asserted directly over whatever tree the caller built: every in-scope
/// file the sweep no longer reads writes no `` `include`` this workspace
/// can resolve, so its turn in the loop could only ever have `continue`d.
///
/// Checked as the complement rather than as an equality because it is the
/// complement that could hide a lost edit: an extra file in the set costs
/// a read, a missing one costs an `` `include`` left pointing at nothing.
fn nothing_skipped_has_an_include_to_rewrite(ws: &Workspace) {
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
let graph = ws.includes();
let mut skipped = 0usize;
for (path, text) in ws.sources() {
if read.contains(&path) {
continue;
}
skipped += 1;
for include in scan(&text) {
assert!(
graph.resolve(Some(&path), &include).is_none(),
"{} was skipped but its `include \"{}\"` resolves",
path.display(),
include.target
);
}
}
assert!(skipped > 0, "the tree must actually exercise the narrowing");
}
/// The one file the rewrite touches, as (uri, the new path spellings).
fn only_file(rewrite: &Rewrite) -> (String, Vec<String>) {
let edit = rewrite.edit.as_ref().expect("an edit");
@@ -579,6 +613,120 @@ mod tests {
out
}
/// A wide workspace where almost nothing includes anything — the shape a
/// real one has, and the reason the sweep no longer reads all of it. The
/// answer must be the one the whole-workspace sweep gave, and the property
/// above must hold over the same tree.
#[test]
fn the_narrowed_sweep_reads_the_includers_and_answers_the_same() {
let tree = Tree::new("narrowed");
tree.write("rtl/defs.svh", "`define W 8\n");
let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
let mut list = String::from("rtl/top.sv\nrtl/defs.svh\n");
// Twenty files with no `include at all, plus two whose includes name
// nothing on disk — both kinds are files the sweep may skip.
for n in 0..20 {
let rel = format!("rtl/quiet{n}.sv");
tree.write(&rel, &format!("module quiet{n};\n wire w;\nendmodule\n"));
list.push_str(&format!("{rel}\n"));
}
for n in 0..2 {
let rel = format!("rtl/dangling{n}.sv");
tree.write(&rel, &format!("`include \"no_such_{n}.svh\"\nmodule d{n};\nendmodule\n"));
list.push_str(&format!("{rel}\n"));
}
tree.write("files.f", &list);
let ws = tree.workspace();
assert_eq!(ws.sources().len(), 24, "the whole scope");
assert_eq!(ws.include_sources().len(), 1, "only `top.sv` includes anything that lands");
nothing_skipped_has_an_include_to_rewrite(&ws);
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
}
/// An `` `include`` typed into a buffer and not yet saved is in no edge the
/// graph holds — the graph is rebuilt on save. The buffer is in the sweep
/// whatever the graph says, which is what keeps that include rewritten.
#[test]
fn an_unsaved_include_is_still_rewritten() {
let tree = Tree::new("unsaved_include");
tree.write("rtl/defs.svh", "`define W 8\n");
let top = tree.write("rtl/top.sv", "module t;\nendmodule\n");
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
let mut ws = tree.workspace();
assert_eq!(ws.include_sources().len(), 0, "premise: the graph knows of no include");
let buffered = "`include \"defs.svh\"\nmodule t;\nendmodule\n";
ws.set_document(path_to_uri(&top).expect("uri"), buffered.to_string());
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
assert_eq!(
applied(buffered, &rewrite, &uri_of(&top)),
"`include \"widths.svh\"\nmodule t;\nendmodule\n"
);
}
/// QA, 2026-08-28 attack: a chain `a.svh -> b.svh`. Renaming `b.svh` must
/// narrow to `a.svh` (its *direct* includer, via `includers()`), and must
/// **not** narrow away a file that includes `a.svh` but never spells
/// `b.svh` at all — `will_rename` only ever rewrites a *direct* include of
/// the file that moves, so a third-order includer has nothing to rewrite
/// either way, but it must still not be mistaken for a candidate (which
/// would cost a read, not a corruption, but is worth pinning).
#[test]
fn an_include_chain_narrows_to_the_direct_includer_of_the_moved_file() {
let tree = Tree::new("chain");
tree.write("rtl/b.svh", "`define W 8\n");
let a = tree.write("rtl/a.svh", "`include \"b.svh\"\n");
let c = tree.write("rtl/c.sv", "`include \"a.svh\"\nmodule c;\nendmodule\n");
tree.write("files.f", "rtl/a.svh\nrtl/b.svh\nrtl/c.sv\n");
let ws = tree.workspace();
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
assert!(read.contains(&a), "a.svh includes b.svh directly: {read:?}");
assert!(read.contains(&c), "c.sv includes a.svh directly: {read:?}");
nothing_skipped_has_an_include_to_rewrite(&ws);
let rewrite = will_rename(&ws, &[tree.rename("rtl/b.svh", "rtl/renamed_b.svh")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
// Only a.svh's own `include \"b.svh\"` line changes; c.sv's
// `include \"a.svh\"` is untouched because a.svh itself did not move.
assert_eq!(only_file(&rewrite), (uri_of(&a), vec!["renamed_b.svh".to_string()]));
}
/// QA, 2026-08-28 attack: an include spelled with different letter case
/// than the file actually has on disk (`` `include "DEFS.svh"`` against a
/// real `defs.svh`) — legal and silently resolved on the common
/// case-insensitive filesystems (confirmed case-insensitive in this test
/// environment). `IncludeGraph::found`/`found_as_if` resolve through the
/// filesystem's own `Path::is_file`, so the includer still lands in `raw`
/// (keyed by the *includer's* path, not the target's spelling) and
/// therefore in `includers()`/`include_sources()` — the narrowing must not
/// accidentally depend on the include's target spelling matching the
/// disk's.
#[test]
fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() {
let tree = Tree::new("case_mismatch");
tree.write("rtl/defs.svh", "`define W 8\n");
let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n");
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
let ws = tree.workspace();
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
assert!(
read.contains(&top),
"top.sv's case-mismatched include still resolves and must narrow in: {read:?}"
);
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
}
#[test]
fn a_same_directory_rename_keeps_the_bare_form() {
let tree = Tree::new("samedir");
+123 -27
View File
@@ -92,8 +92,21 @@ pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
/// order. Empty when no filelist governs the workspace.
incdirs: Vec<PathBuf>,
/// Including file → the files it resolves to, in source order.
/// Including file → the files it resolves to, in source order, spelled the
/// way the index spells them. Derived from `raw` by [`IncludeGraph::respell`]
/// and never written to directly.
edges: HashMap<PathBuf, Vec<PathBuf>>,
/// The same edges as the *filesystem* answered them: normalized, but
/// before [`IncludeGraph::as_the_index_spells_it`] re-spells them against
/// the in-scope file list.
///
/// Kept because which file an `` `include`` lands on is a question for the
/// disk and which *spelling* that file has is a question for the scope, and
/// only the second one moves when the scope grows. Holding the first means
/// a scope widen can re-spell every edge it already had without re-reading
/// a single file — which is what makes an incrementally widened graph
/// byte-identical to a rebuilt one (`docs/features/index-scope/README.md`).
raw: HashMap<PathBuf, Vec<PathBuf>>,
/// Every in-scope file, exactly as the index spells it.
known: HashSet<PathBuf>,
/// Lower-cased spelling → the one in-scope file that has it, or `None`
@@ -110,14 +123,9 @@ impl IncludeGraph {
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
graph.relearn(&paths);
for (path, text) in sources {
let targets: Vec<PathBuf> = scan(text)
.iter()
.filter_map(|include| graph.resolve(Some(path), include))
.collect();
if !targets.is_empty() {
graph.edges.insert(path.clone(), targets);
}
graph.rescan_edges(path, text);
}
graph.respell();
graph
}
@@ -130,18 +138,17 @@ impl IncludeGraph {
///
/// One honest limit, and the reason the incremental path in `state.rs`
/// takes it only for a file that already existed: an edge of a *different*
/// file is not re-resolved. So a file appearing or vanishing does not
/// change whether some other file's `` `include "x.svh"`` resolves until
/// the next whole rebuild. For the case this is used in — one file's text
/// changed, the file set did not — there is nothing stale at all.
/// file is not re-**resolved** against the disk. So a file appearing or
/// vanishing on disk does not change whether some other file's
/// `` `include "x.svh"`` finds anything until the next whole rebuild. Every
/// held edge *is* re-spelled against the new file list, because that half
/// costs no filesystem call — see [`IncludeGraph::respell`]. For the case
/// this is used in — one file's text changed, the file set did not — there
/// is nothing stale at all.
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
self.relearn(known);
let targets: Vec<PathBuf> =
scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect();
match targets.is_empty() {
true => self.edges.remove(path),
false => self.edges.insert(path.to_path_buf(), targets),
};
self.rescan_edges(path, text);
self.respell();
}
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
@@ -159,20 +166,51 @@ impl IncludeGraph {
self.incdirs = incdirs.to_vec();
self.relearn(known);
for (path, text) in batch {
let targets: Vec<PathBuf> =
scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect();
match targets.is_empty() {
true => self.edges.remove(*path),
false => self.edges.insert(path.to_path_buf(), targets),
};
self.rescan_edges(path, text);
}
self.respell();
}
/// Drop one file from the graph: its own edges, and its place among the
/// known files.
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
self.relearn(known);
self.edges.remove(path);
self.raw.remove(path);
self.respell();
}
/// Read one file's `` `include``s off its text and hold where the disk says
/// each one lands. A file that includes nothing holds no entry at all,
/// which is what keeps `raw` a set of edges rather than a set of files.
fn rescan_edges(&mut self, path: &Path, text: &str) {
let targets: Vec<PathBuf> =
scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect();
match targets.is_empty() {
true => self.raw.remove(path),
false => self.raw.insert(path.to_path_buf(), targets),
};
}
/// Re-derive every edge's spelling from the file list learned last.
///
/// The cheap half of resolving an include: which file it lands on was
/// settled by the filesystem when the edge was read, and only how the index
/// spells that file depends on which files are in scope. So a scope that
/// grows re-spells what it already had here, in memory, rather than
/// re-reading and re-scanning every file it already knew about.
fn respell(&mut self) {
// Taken out and put back so the re-spelling may read the tables on
// `self` while it walks the edges — the same map, never a copy of it.
let raw = std::mem::take(&mut self.raw);
self.edges = raw
.iter()
.map(|(path, targets)| {
let spelled =
targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect();
(path.clone(), spelled)
})
.collect();
self.raw = raw;
}
/// Re-derive the known-file set and the folded-spelling table from the
@@ -222,10 +260,29 @@ impl IncludeGraph {
from: Option<&Path>,
include: &Include,
exists: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
self.found_as_if(from, include, exists).map(|found| self.as_the_index_spells_it(found))
}
/// [`IncludeGraph::resolve`] as far as the *filesystem* answers it: the
/// search rungs and `normalize`, without the index's own spelling.
///
/// The half of an edge that only a disk change can move, which is what the
/// graph holds in `raw`.
fn found(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
self.found_as_if(from, include, &|path| path.is_file())
}
/// [`IncludeGraph::found`] against a filesystem `exists` describes.
fn found_as_if(
&self,
from: Option<&Path>,
include: &Include,
exists: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
let target = Path::new(&include.target);
if target.is_absolute() {
return exists(target).then(|| self.as_the_index_spells_it(normalize(target)));
return exists(target).then(|| normalize(target));
}
let own = match include.system {
true => None,
@@ -235,7 +292,7 @@ impl IncludeGraph {
.chain(self.incdirs.iter().map(PathBuf::as_path))
.map(|dir| dir.join(target))
.find(|candidate| exists(candidate))
.map(|found| self.as_the_index_spells_it(normalize(&found)))
.map(|found| normalize(&found))
}
/// A resolved path, re-spelled the way the index spells that file.
@@ -268,6 +325,18 @@ impl IncludeGraph {
}
}
/// Every file that writes at least one `` `include`` the disk answered —
/// the keys of the edge table, in no particular order.
///
/// The complement is the interesting half: a file that is *not* here
/// either includes nothing or includes only what nothing resolves, so
/// [`IncludeGraph::resolve`] answers `None` for every include it writes.
/// `file_ops.rs` reads that as "this file cannot produce an edit or a
/// warning" and never reads it (`Workspace::include_sources`).
pub fn includers(&self) -> impl Iterator<Item = &PathBuf> {
self.raw.keys()
}
/// Every file reachable from `seeds` through include edges, the seeds
/// themselves included.
///
@@ -287,6 +356,33 @@ impl IncludeGraph {
}
seen
}
/// Everything this graph answers with, as one deterministic string.
///
/// Test-only, and the witness for "a graph widened one folder at a time is
/// the graph a whole rebuild would have produced": the two hash maps are
/// rendered in sorted order, so the comparison is of the contents and never
/// of the iteration order.
#[cfg(test)]
pub fn fingerprint(&self) -> String {
let mut out = format!("incdirs {:?}\n", self.incdirs);
let mut known: Vec<&PathBuf> = self.known.iter().collect();
known.sort();
out.push_str(&format!("known {known:?}\n"));
let mut folded: Vec<(&String, &Option<PathBuf>)> = self.folded.iter().collect();
folded.sort();
out.push_str(&format!("folded {folded:?}\n"));
let mut edges: Vec<(&PathBuf, &Vec<PathBuf>)> = self.edges.iter().collect();
edges.sort();
out.push_str(&format!("edges {edges:?}\n"));
// The unspelled edges too, so a widen that left a stale entry behind
// fails here rather than waiting for the scope to grow far enough for
// the spelling to notice.
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
raw.sort();
out.push_str(&format!("raw {raw:?}\n"));
out
}
}
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
+32 -19
View File
@@ -594,16 +594,17 @@ mod tests {
}
// And the belt to that brace: a record really written in the previous
// format — this one is a format-3 record, which is today's minus the
// two per-declaration line fields `hover-line-index` added — does not
// decode as one of today's *even if* something served it past the
// header. Field-shifting is what the length prefixes and the
// end-of-record check exist to make impossible.
let format_3 = strip_the_line_fields(&encoded);
assert_ne!(format_3, encoded, "premise: the fixture has a declaration to strip");
// format — this one is a format-4 record, which is today's minus every
// field `vscode-hierarchy-sidebar` added — does not decode as one of
// today's *even if* something served it past the header.
// Field-shifting is what the length prefixes and the end-of-record
// check exist to make impossible.
let previous = as_a_format_4_record(&encoded);
assert_ne!(previous, encoded, "premise: the fixture has fields to strip");
assert!(
FileFacts::decode(&format_3).is_none(),
"a format-3 record decoded as a format-4 one: {format_3}"
FileFacts::decode(&previous).is_none(),
"a format-{} record decoded as a format-{FACTS_FORMAT} one: {previous}",
FACTS_FORMAT - 1
);
// Finally, the store is replaced under this build's header rather than
@@ -621,20 +622,32 @@ mod tests {
);
}
/// Today's encoded record, minus the two line fields every declaration
/// gained in `FACTS_FORMAT` 4 — i.e. what format 3 wrote for the same
/// file. `M` declares exactly one unit and no members, so the fields to
/// drop are the two immediately after that unit's four span offsets.
fn strip_the_line_fields(encoded: &str) -> String {
/// Today's encoded record, minus everything `FACTS_FORMAT` 5 added — i.e.
/// exactly what format 4 wrote for the same file. Three additions and all
/// three come out: a declaration's `decl_span`, a file-scope declaration's
/// client positions, and an instantiation's per-instance occurrences.
///
/// `M` declares exactly one unit, no members, and one instantiation of one
/// instance, so every group's field index can be computed rather than
/// parsed. Highest index first, so removing one strip does not move the
/// others.
fn as_a_format_4_record(encoded: &str) -> String {
let mut fields: Vec<&str> = encoded.split('\t').collect();
let Some(instantiations) = fields.iter().position(|f| *f == "I") else {
return encoded.to_string();
};
// I, count, module, owner (name + two ranges), site range — ten
// fields, then the occurrence count and its one thirteen-field
// occurrence.
fields.drain(instantiations + 10..instantiations + 10 + 1 + 13);
let Some(units) = fields.iter().position(|f| *f == "U") else {
return encoded.to_string();
};
// U, count, name, kind, name_span×2, detail×2, then the two lines.
let lines_at = units + 8;
if fields.len() > lines_at + 1 {
fields.drain(lines_at..lines_at + 2);
}
// U, count, then name, kind, name_span×2, decl_span×2, detail×2,
// lines×2, and the unit's two client ranges — four numbers each.
let decl_at = units + 2;
fields.drain(decl_at + 10..decl_at + 18);
fields.drain(decl_at + 4..decl_at + 6);
fields.join("\t")
}
+136 -1
View File
@@ -10,6 +10,7 @@ mod candidates;
mod code_action;
mod completion;
mod convert;
mod design_hierarchy;
mod diagnostics;
mod expand;
mod file_ops;
@@ -69,7 +70,34 @@ use vlog_parser::PARSE_STACK_SIZE;
use crate::server::{ClientAbilities, Server};
use crate::uri::uri_to_path;
/// The one flag this binary takes: per-operation timing lines in the client's
/// log channel. One spelling, no `-v` — see
/// `docs/features/verbose-timing/README.md`.
const VERBOSE: &str = "--verbose";
/// `vscode-languageclient` (and other LSP clients) append `--stdio` to the
/// spawn when the transport is stdio — the only transport this server has.
/// Accepted as the statement of fact it is; rejecting it turned out to crash
/// every real VS Code session the moment strict argument parsing shipped
/// (lead hotfix, 2026-08-29 — the smoke and restart harnesses spawn the
/// binary directly, so nothing in the loop exercised the library's spawn).
const STDIO: &str = "--stdio";
/// What someone who spelled an argument wrong is told, on stderr. One line:
/// this binary is spawned by an editor, not typed at a prompt.
const USAGE: &str = "usage: lucisv-server [--verbose] [--stdio]";
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// Before the transport: an argument we do not understand means the client
// asked for something we are not doing, and answering LSP anyway would
// hide that for the whole session.
let verbose = match verbose_flag(std::env::args().skip(1)) {
Ok(verbose) => verbose,
Err(unknown) => {
eprintln!("error: unknown option: {unknown}");
eprintln!("{USAGE}");
std::process::exit(2);
}
};
let (connection, io_threads) = Connection::stdio();
let (id, params) = connection.initialize_start()?;
@@ -81,6 +109,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// capability at all: `initializationOptions` is whatever the client's
// extension put there.
let storage = storage_path(&params);
let hierarchy_view = hierarchy_view_support(&params);
// A client that sends params we cannot read still gets a server; every
// field we want is optional anyway.
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
@@ -95,6 +124,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
show_document: show_document_support(&params),
configuration: configuration_support(&params),
token_server_cancel: token_server_cancel_support(&params),
hierarchy_view,
};
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
@@ -108,13 +138,35 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
std::thread::Builder::new()
.name("lucisv-main".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || Server::new(connection, roots, abilities, storage).run())?
.spawn(move || Server::new(connection, roots, abilities, storage, verbose).run())?
.join()
.map_err(|_| "the server thread panicked")??;
io_threads.join()?;
Ok(())
}
/// Whether the arguments ask for verbose timing, or the first argument this
/// binary does not take.
///
/// Refused rather than ignored: a client that spawns `lucisv-server --verbos`
/// would otherwise get a whole session of silence and no way to tell it from a
/// flag that does not work. Repeating the flag is not an error — it says the
/// same thing twice — and no argument at all is the spawn every editor has
/// always used.
fn verbose_flag(args: impl Iterator<Item = String>) -> Result<bool, String> {
let mut verbose = false;
for arg in args {
if arg == STDIO {
continue;
}
if arg != VERBOSE {
return Err(arg);
}
verbose = true;
}
Ok(verbose)
}
/// What the server tells the client it can do. Nothing is advertised that is
/// not implemented: a capability an editor discovers to be a lie is worse than
/// one it never had.
@@ -412,6 +464,13 @@ fn storage_path(params: &serde_json::Value) -> Option<PathBuf> {
(!path.trim().is_empty()).then(|| PathBuf::from(path))
}
/// Whether this client hosts lucisv's custom hierarchy view and therefore
/// wants invalidation notifications for it. The snapshot request itself is
/// always served; this gate prevents unsolicited traffic to other LSP clients.
fn hierarchy_view_support(params: &serde_json::Value) -> bool {
params["initializationOptions"]["hierarchyView"] == true
}
/// Whether the client can expand `${1:x}` tabstops in a completion item.
///
/// A client that did not say so gets the skeleton as plain text: a literal
@@ -553,6 +612,68 @@ fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
mod tests {
use super::*;
/// [`verbose_flag`] over what a spawn would really hand it.
fn args(args: &[&str]) -> Result<bool, String> {
verbose_flag(args.iter().map(|arg| (*arg).to_string()))
}
#[test]
fn no_arguments_is_the_spawn_every_editor_has_always_used() {
assert_eq!(args(&[]), Ok(false), "and it must never become verbose by accident");
}
#[test]
fn the_one_flag_is_the_one_spelling() {
assert_eq!(args(&["--verbose"]), Ok(true));
// Twice says the same thing twice.
assert_eq!(args(&["--verbose", "--verbose"]), Ok(true));
// Every near miss is refused, `-v` included: one spelling, so a client
// that guessed is told rather than silently given nothing.
for wrong in ["-v", "--Verbose", "--verbos", "verbose", "--verbose=true", "--help"] {
assert_eq!(args(&[wrong]), Err(wrong.to_string()), "{wrong} is not the flag");
}
}
#[test]
fn stdio_is_accepted_as_the_statement_of_fact_it_is() {
// `vscode-languageclient` appends `--stdio` for TransportKind.stdio —
// the spawn every real VS Code session actually makes. Rejecting it
// crashed the extension five times and gave up (lead hotfix,
// 2026-08-29); it must parse in every combination and change nothing.
assert_eq!(args(&["--stdio"]), Ok(false));
assert_eq!(args(&["--stdio", "--verbose"]), Ok(true));
assert_eq!(args(&["--verbose", "--stdio"]), Ok(true));
assert_eq!(args(&["--stdio", "--stdio"]), Ok(false));
// And a near miss of IT is still refused.
assert_eq!(args(&["--Stdio"]), Err("--Stdio".to_string()));
}
#[test]
fn the_first_argument_we_do_not_take_is_the_one_reported() {
// Named, so the message can say which word was wrong — the whole
// reason this refuses instead of ignoring.
assert_eq!(args(&["--verbose", "--colour"]), Err("--colour".to_string()));
assert_eq!(args(&["--colour", "--verbose"]), Err("--colour".to_string()));
assert_eq!(args(&["/some/file.sv"]), Err("/some/file.sv".to_string()));
}
#[test]
fn the_extension_ships_the_flag_off_which_is_what_no_argument_means() {
// The two halves of the contract live in different languages: the
// manifest's default decides whether `extension.js` puts `--verbose`
// in the spawn arguments, and `verbose_flag` decides what the server
// does with the arguments it gets. They must agree that the shipped
// state is off.
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: serde_json::Value = serde_json::from_str(&text).expect("valid json");
let verbose = &manifest["contributes"]["configuration"]["properties"]["lucisv.verbose"];
assert_eq!(verbose["type"], serde_json::json!("boolean"), "{verbose:#?}");
assert_eq!(verbose["default"], serde_json::json!(false), "{verbose:#?}");
assert_eq!(args(&[]), Ok(false), "which is what the server does with no argument");
}
#[test]
fn every_advertised_capability_is_implemented() {
let caps = capabilities();
@@ -735,6 +856,20 @@ mod tests {
assert!(!ranges_formatting_support(&serde_json::Value::Null));
}
#[test]
fn hierarchy_notifications_are_an_explicit_initialization_option() {
let saying = serde_json::json!({ "initializationOptions": { "hierarchyView": true } });
assert!(hierarchy_view_support(&saying));
for silent in [
serde_json::json!({}),
serde_json::json!({ "initializationOptions": { "hierarchyView": false } }),
serde_json::json!({ "initializationOptions": { "hierarchyView": "yes" } }),
serde_json::Value::Null,
] {
assert!(!hierarchy_view_support(&silent), "{silent:#?}");
}
}
#[test]
fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() {
// The gate's whole point: every client that shipped before this round
+219 -2
View File
@@ -363,8 +363,10 @@ fn in_file_references(
/// — a use sits on, and LSP is explicit that plain `Text` is a valid answer.
/// Building that analysis for a highlight colour is not a trade worth making.
pub fn document_highlights(doc: &Document, offset: u32) -> Option<Vec<DocumentHighlight>> {
let symbol_id = symbol_at(&doc.semantics, offset)?;
let spans = occurrences(&doc.semantics, symbol_id, true);
let spans = match symbol_at(&doc.semantics, offset) {
Some(symbol_id) => occurrences(&doc.semantics, symbol_id, true),
None => external_occurrences(doc, offset),
};
if spans.is_empty() {
return None;
}
@@ -383,6 +385,49 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option<Vec<DocumentHi
)
}
/// Every use in *this* file of the declaration the workspace overlay answered
/// for the cursor — the half of the question `Semantics` alone cannot see.
///
/// A name this file uses but does not declare has no in-file symbol at all:
/// `Semantics` records the use as an external candidate and leaves it to the
/// workspace layer, so [`symbol_at`] is `None` and the single-file answer is
/// empty. That is what `performance.md` §7 caught — `documentHighlight`
/// answering nothing on an instantiated module and on a port connection while
/// `references` answered at the same positions, because `references` reads
/// this overlay and the highlight did not.
///
/// Two uses name the same declaration when they spell the same name *and* the
/// overlay gave them the same answer. Comparing the whole answer rather than
/// its first entry keeps two ambiguous uses together only when they are
/// ambiguous between the same declarations; an unanswered use — a module the
/// index does not hold — is left to the editor's own word highlighting, which
/// is the same contract the rest of this function keeps.
fn external_occurrences(doc: &Document, offset: u32) -> Vec<TextRange> {
let Some(id) = doc.semantics.reference_id_at(offset) else { return Vec::new() };
let Some(target) = doc.external.get(id) else { return Vec::new() };
if target.defs().is_empty() {
return Vec::new();
}
let Some(name) = doc.semantics.reference(id).map(|r| r.name.as_str()) else {
return Vec::new();
};
let mut spans: Vec<TextRange> = doc
.semantics
.references()
.iter()
.enumerate()
.filter(|(_, reference)| reference.name == name && !reference.name_span.is_empty())
.filter(|(at, _)| {
doc.external.get(vlog_semantic::ReferenceId(*at as u32)).map(ExternalTarget::defs)
== Some(target.defs())
})
.map(|(_, reference)| reference.name_span)
.collect();
spans.sort_by_key(|span| (span.start, span.end));
spans.dedup();
spans
}
/// The symbol at a position. The cursor may sit on a use or on the
/// declaration itself; both lead to the same symbol.
///
@@ -1270,6 +1315,178 @@ mod tests {
assert!(document_highlights(doc, 0).is_none(), "the `module` keyword");
}
/// `performance.md` §7, reproduced: `documentHighlight` answered nothing
/// at every opentitan position tried — an instantiated module's name, a
/// port connection — while `references` at the same positions answered.
/// Both names are declared in *another* file, which is the whole of what
/// the two handlers used to disagree about.
#[test]
fn a_cross_file_name_highlights_its_uses_in_this_file() {
let dir = temp_dir("highlight_cross");
fs::write(
dir.join("sub.sv"),
"module sub (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n",
)
.expect("write");
let top_path = dir.join("top.sv");
let top_text = "\
module top;
logic clk, rst;
sub u_0 (.clk_i(clk), .rst_ni(rst));
sub u_1 (.clk_i(clk), .rst_ni(rst));
endmodule
";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let doc = ws.document(&uri).expect("open");
// The module name at an instantiation: both instantiations, and
// nothing from the *other* module's file — this is one file's answer.
let module = at(top_text, "sub u_0");
assert_eq!(references(&ws, &uri, module, true).len(), 3, "premise: references answers");
let found = document_highlights(doc, module).expect("the instantiated module");
let lines: Vec<u32> = found.iter().map(|h| h.range.start.line).collect();
assert_eq!(lines, vec![2, 3], "both instantiations of `sub`");
assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT)));
// A port connection: the `.clk_i` of both instantiations, and not the
// `clk` they are wired to, which is a different symbol.
let port = at(top_text, ".clk_i") + 1;
assert!(!references(&ws, &uri, port, true).is_empty(), "premise: references answers");
let found = document_highlights(doc, port).expect("the connected port");
let starts: Vec<(u32, u32)> =
found.iter().map(|h| (h.range.start.line, h.range.start.character)).collect();
assert_eq!(starts, vec![(2, 12), (3, 12)], "both `.clk_i` connections");
let _ = fs::remove_dir_all(&dir);
}
/// QA (performance wave Lane B, 2026-08-28): an instantiated module whose
/// name two files declare is ambiguous at the workspace layer.
/// `references` gives up on an ambiguous external target outright
/// (`indexed_target` only ever builds one from `Definition::External([def])`
/// — exactly one candidate — so an ambiguous use never reaches
/// `indexed_references`, and `in_file_references` needs a *local* symbol,
/// which an external use does not have; the net result is an empty
/// answer, unchanged by this round). `document_highlights` does not
/// inherit that caution: `external_occurrences` groups by the overlay's
/// whole answer, ambiguous sets included, so it answers here where
/// `references` does not. Recorded rather than asserted as a bug — LSP
/// does not require the two to agree, and answering something reasonable
/// beats the editor's own word-highlighter falling back to nothing — but
/// it is a real divergence the lead should see before calling the two
/// "cross-checked".
#[test]
fn an_ambiguous_instantiation_highlights_where_references_gives_up() {
let dir = temp_dir("highlight_ambiguous");
let dup = "module dup (input logic clk_i);\nendmodule\n";
fs::write(dir.join("a.sv"), dup).expect("write");
fs::write(dir.join("b.sv"), dup).expect("write");
let top_path = dir.join("top.sv");
let top_text = "\
module top;
logic clk;
dup u_0 (.clk_i(clk));
dup u_1 (.clk_i(clk));
endmodule
";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let doc = ws.document(&uri).expect("open");
let module = at(top_text, "dup u_0");
assert!(leaves_this_file(&ws, doc, module), "dup is a unit the index holds");
assert!(
references(&ws, &uri, module, true).is_empty(),
"references declines an ambiguous external target rather than guessing"
);
let found = document_highlights(doc, module).expect("highlight groups the ambiguous use");
let lines: Vec<u32> = found.iter().map(|h| h.range.start.line).collect();
assert_eq!(lines, vec![2, 3], "both instantiations, grouped by the same ambiguous def set");
let _ = fs::remove_dir_all(&dir);
}
/// Two uses of the *same name* that are ambiguous between *different*
/// def sets must not be grouped into one highlight — the def-set
/// comparison in `external_occurrences`, not the name match alone, is
/// what keeps them apart. `dup_a` and `dup_b` are each declared in two
/// files (so a connection to either is ambiguous), and both happen to
/// export a port with the identical name `same_port` — so the two
/// connections below share one `reference.name` but must resolve against
/// disjoint ambiguous sets (`dup_a`'s two files vs. `dup_b`'s two files).
#[test]
fn two_uses_ambiguous_between_different_def_sets_do_not_group() {
let dir = temp_dir("highlight_ambiguous_disjoint");
let dup_a = "module dup_a (input logic same_port);\nendmodule\n";
let dup_b = "module dup_b (input logic same_port);\nendmodule\n";
fs::write(dir.join("a1.sv"), dup_a).expect("write");
fs::write(dir.join("a2.sv"), dup_a).expect("write");
fs::write(dir.join("b1.sv"), dup_b).expect("write");
fs::write(dir.join("b2.sv"), dup_b).expect("write");
let top_path = dir.join("top.sv");
let top_text = "\
module top;
logic clk;
dup_a u_a (.same_port(clk));
dup_b u_b (.same_port(clk));
endmodule
";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let doc = ws.document(&uri).expect("open");
let first = at(top_text, "same_port(clk));\n dup_b") + 1;
let second = at(top_text, "same_port(clk));\nendmodule") + 1;
// Premise: both connections are genuinely ambiguous externals (no
// local `same_port`, and the workspace really does hold two
// candidates for each), i.e. this exercises the def-set comparison
// and not some earlier decline.
let first_found =
document_highlights(doc, first).expect("dup_a's connection is ambiguous, not empty");
let second_found =
document_highlights(doc, second).expect("dup_b's connection is ambiguous, not empty");
let first_lines: Vec<u32> = first_found.iter().map(|h| h.range.start.line).collect();
let second_lines: Vec<u32> = second_found.iter().map(|h| h.range.start.line).collect();
assert_eq!(first_lines, vec![2], "dup_a's port only, despite sharing a name with dup_b's");
assert_eq!(second_lines, vec![3], "dup_b's port only, despite sharing a name with dup_a's");
let _ = fs::remove_dir_all(&dir);
}
/// A use the overlay never answered — its `defs()` is empty, e.g. a
/// package member the index does not hold — must decline like any other
/// unanswered position, not fall through to some other file's namesake.
#[test]
fn an_unanswered_external_use_declines_rather_than_guessing() {
let dir = temp_dir("highlight_unanswered");
let top_path = dir.join("top.sv");
// `missing_pkg` is never declared anywhere in the workspace, so the
// import itself is the only thing the index can say nothing about;
// `NOPE` is a member reference the overlay tries and fails to place.
let top_text = "module top;\n import missing_pkg::*;\n wire [NOPE-1:0] a;\nendmodule\n";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let doc = ws.document(&uri).expect("open");
let use_pos = at(top_text, "NOPE") + 1;
assert!(document_highlights(doc, use_pos).is_none(), "unresolved, so decline");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_package_import_resolves_into_the_packages_file() {
let dir = temp_dir("pkg");
+686
View File
@@ -501,3 +501,689 @@ fn looking_up_one_name_against_scanning_every_symbol() {
);
}
}
/// `cargo test --release -p lucisv_server perf::what_a_jump -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn what_a_jump_into_a_new_folder_costs_before_and_after() {
// The owner's opentitan report, on a workspace this repository generates
// for itself: many folders, browsed one jump at a time. Both shapes are
// measured in the same run over the same tree, so the pair is a real
// before/after and not two numbers from two days.
//
// * **before** — the whole rescan a widening `didOpen` used to run: every
// file of every folder reached so far, re-read, re-hashed and re-merged.
// It grows with every jump, which is the shape the report describes.
// * **after** — the widen: the files the opened folder brings in, folded
// into the index beside what is already there.
let (folders, each) = (40, 25);
let dir = std::env::temp_dir().join(format!("lucisv_perf_jump_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for folder in 0..folders {
let path = dir.join(format!("blk{folder:02}/rtl"));
std::fs::create_dir_all(&path).expect("folder");
for file in 0..each {
std::fs::write(
path.join(format!("f{file:02}.sv")),
generated_module(&format!("b{folder:02}_f{file:02}"), 200),
)
.expect("write");
}
}
// Two workspaces over the same tree, jumped through the same folders, so
// the only difference between the two columns is which path the widen
// took. Neither uses the persistent store: `cache_dir` answers `None` in
// this crate's tests unless a path is named, which is what keeps the
// measurement about the scan and not about a warm cache.
let mut whole = Workspace::default();
whole.adopt_roots(vec![dir.clone()]);
let mut incremental = Workspace::default();
incremental.adopt_roots(vec![dir.clone()]);
let mut rows: Vec<(usize, Duration, Duration, usize)> = Vec::new();
for jump in 0..6 {
let path = dir.join(format!("blk{jump:02}/rtl/f00.sv"));
let uri = path_to_uri(&path).expect("uri");
let text = std::fs::read_to_string(&path).expect("read");
whole.set_document(uri.clone(), text.clone());
let started = Instant::now();
black_box(whole.rebuild_index());
let rescan = started.elapsed();
let before = incremental.scope_dirs();
incremental.set_document(uri, text);
let added: Vec<PathBuf> =
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
let started = Instant::now();
let mut scan = incremental.begin_widen(&added, &mut |_| {});
while incremental.scan_step(&mut scan, &mut |_| {}) {}
black_box(incremental.finish_scan(scan));
let widen = started.elapsed();
assert_eq!(
whole.index().fingerprint(),
incremental.index().fingerprint(),
"the two columns must describe the same index, or the numbers mean nothing"
);
rows.push((jump, rescan, widen, incremental.index().files().len()));
}
eprintln!("a jump into a new folder, {folders} folders of {each} files of 200 lines:");
for (jump, rescan, widen, indexed) in rows {
eprintln!(
" jump {jump} ({indexed} files in scope after it): \
whole rescan {rescan:?}, incremental widen {widen:?}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// `cargo test --release -p lucisv_server perf::what_a_widen_that_subsumes -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn what_a_widen_that_subsumes_the_old_scope_costs() {
// `performance_take2.md` §5b, without opentitan: at the shipped
// `scopeDepth: 2` the first jump from a block's testbench into its own RTL
// raises the scope to the directory holding *every* block, which contains
// the one already in scope. The two things this prints are the two the
// report is about — how many files the widen actually reads (the new
// blocks, never the old one), and how long that takes against the whole
// rescan the same jump would otherwise cost.
let (blocks, rtl_each, dv_each) = (20, 25, 10);
let dir = std::env::temp_dir().join(format!("lucisv_perf_subsume_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for block in 0..blocks {
for (tag, folder, files) in [("r", "rtl", rtl_each), ("d", "dv/tb", dv_each)] {
let path = dir.join(format!("ip/blk{block:02}/{folder}"));
std::fs::create_dir_all(&path).expect("folder");
for file in 0..files {
// `corpus_file`, not `generated_module`: every name in it is
// the file's own, so the workspace-wide word table grows with
// the file count the way a real one does. That is the whole
// point of this shape — a widen's cost is dominated by what it
// does to tables the size of the workspace, not by the folder.
std::fs::write(
path.join(format!("f{file:02}.sv")),
corpus_file(&format!("b{block:02}{tag}_f{file:02}"), 200),
)
.expect("write");
}
}
}
let tb = dir.join("ip/blk00/dv/tb/f00.sv");
let rtl = dir.join("ip/blk00/rtl/f00.sv");
let open = |ws: &mut Workspace, path: &PathBuf| {
let uri = path_to_uri(path).expect("uri");
ws.set_document(uri, std::fs::read_to_string(path).expect("read"));
};
// The shipped rung: depth 2, clamped by a root above `ip/`.
let depth_two = |ws: &mut Workspace| {
ws.set_client_settings(crate::settings::ClientSettings {
index_scope_depth: 2,
..Default::default()
});
ws.adopt_roots(vec![dir.clone()]);
};
let mut whole = Workspace::default();
depth_two(&mut whole);
let mut incremental = Workspace::default();
depth_two(&mut incremental);
for ws in [&mut whole, &mut incremental] {
open(ws, &tb);
ws.rebuild_index();
}
let held = incremental.index().files().len();
open(&mut whole, &rtl);
let started = Instant::now();
black_box(whole.rebuild_index());
let rescan = started.elapsed();
let before = incremental.scope_dirs();
open(&mut incremental, &rtl);
let added: Vec<PathBuf> =
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
let mut read = 0usize;
let started = Instant::now();
let mut scan = incremental.begin_widen(&added, &mut |_| {});
while incremental.scan_step(&mut scan, &mut |_| read += 1) {}
// Split out because it is where the 2026-08-29 round's fix landed: folding
// a widen's words into the completion table used to move the table's tail
// once per new word, which is quadratic in the batch and was 40% of the
// whole cost on opentitan's `hw/ip`.
let landing = Instant::now();
black_box(incremental.finish_scan(scan));
let (finish, widen) = (landing.elapsed(), started.elapsed());
assert_eq!(
whole.index().fingerprint(),
incremental.index().fingerprint(),
"the two columns must describe the same index, or the numbers mean nothing"
);
eprintln!(
"a widen that subsumes the old scope, {blocks} blocks of {} files:\n \
scope {held} -> {} files; the widen read {read} of them \
(the {held} already indexed are not re-read)\n \
whole rescan {rescan:?}, subsuming widen {widen:?} (landing it: {finish:?})",
rtl_each + dv_each,
incremental.index().files().len(),
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The module-name families a completion prefix lands in, so a one-character
/// prefix names hundreds of modules and a five-character one names a handful —
/// the shape `performance.md`'s prefix table has on the real corpus.
const FAMILIES: [&str; 10] = [
"aes",
"prim",
"kmac",
"hmac",
"spi_device",
"otbn",
"flash_ctrl",
"rv_core",
"clkmgr",
"uart",
];
/// A workspace the size of the corpus `performance.md` measured against: one
/// module per file, named from [`FAMILIES`], each declaring names no other file
/// declares so the word table grows with the file count the way a real one does.
fn completion_corpus(dir: &std::path::Path, files: usize, body: usize) {
for n in 0..files {
let family = FAMILIES[n % FAMILIES.len()];
let name = format!("{family}_{n:04}");
std::fs::write(dir.join(format!("{name}.sv")), corpus_file(&name, body)).expect("write");
}
}
/// One corpus file: a package, then a module whose header is what a skeleton
/// reads and whose body is the several hundred lines a real RTL file carries
/// behind it.
fn corpus_file(name: &str, body: usize) -> String {
let mut text = format!(
"package {name}_pkg;\n localparam int {name}_WIDTH = 8;\n \
typedef logic [1:0] {name}_pair_t;\nendpackage\n\
module {name} #(\n parameter int WIDTH = 8\n) (\n \
input logic clk_i,\n input logic rst_ni,\n \
input logic [WIDTH-1:0] {name}_data_i,\n \
output logic [WIDTH-1:0] {name}_data_o\n);\n"
);
for n in 0..body / 4 {
text.push_str(&format!(
" wire [WIDTH-1:0] {name}_w{n};\n \
assign {name}_w{n} = {name}_data_i ^ {{WIDTH{{rst_ni}}}};\n \
reg [WIDTH-1:0] {name}_r{n};\n \
always_ff @(posedge clk_i) {name}_r{n} <= {name}_w{n};\n"
));
}
text.push_str(&format!(" assign {name}_data_o = {name}_data_i;\nendmodule\n"));
text
}
/// The buffer a completion is asked for in: a module body with `prefix` typed
/// on a fresh item line, and the same prefix inside an expression.
fn completion_buffer(prefix: &str, at_item: bool) -> (String, u32) {
let text = match at_item {
true => format!("module bench_top;\n {prefix}\nendmodule\n"),
false => format!("module bench_top;\n logic x;\n assign x = {prefix}\nendmodule\n"),
};
let cursor = text.find("\nendmodule").expect("the last line") as u32;
(text, cursor)
}
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server perf::completing_over_a_real -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
fn completing_over_a_real_project() {
// The same measurement as `completing_one_keystroke_at_a_time`, over
// whatever tree `LUCISV_PERF_CORPUS` names, with tier 0's bill broken out
// over the modules that tree really declares. A generated corpus has
// uniform files; a real one has a hundred-line header on one module and a
// two-thousand-line body on the next, and the difference between the two
// is worth being able to see. **Skipped when the variable is unset**, so
// this crate's tests never depend on a checkout nobody promised.
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
return;
};
let root = PathBuf::from(root);
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
});
let started = Instant::now();
ws.open_whole_workspace(vec![root.clone()]);
let scan = started.elapsed();
let buffer = root.join("lucisv_perf_buffer.sv");
let uri = path_to_uri(&buffer).expect("uri");
eprintln!(
"completion over {} indexed files of {} (scan {scan:?}), {} index names, {} words:",
ws.index().files().len(),
root.display(),
ws.candidates().units("").len(),
ws.candidates().words("").len()
);
for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_reg", "zzzz"] {
let (text, cursor) = completion_buffer(prefix, true);
ws.set_document(uri.clone(), text.clone());
let position = {
let doc = ws.document(&uri).expect("open");
doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start
};
let items = match crate::completion::completions(&ws, &uri, position, true) {
Some(lsp_types::CompletionResponse::List(list)) => list.items.len(),
_ => 0,
};
let took = mean(5, || {
black_box(crate::completion::completions(&ws, &uri, black_box(position), true));
});
// Tier 0's bill over this prefix's own candidates, stage by stage, so
// a slow row can be read rather than guessed at.
let names: Vec<String> =
ws.candidates().modules(prefix).iter().take(64).map(|n| n.to_string()).collect();
let (mut read, mut slice, mut plan) = (0u128, 0u128, 0u128);
let mut whole_files: Vec<&str> = Vec::new();
let mut bytes = 0usize;
for name in &names {
let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue };
let started = Instant::now();
let Some(text) = ws.text_of(path) else { continue };
read += started.elapsed().as_nanos();
bytes += text.len();
let started = Instant::now();
let header = crate::completion::module_header(ws.index(), name, &text);
slice += started.elapsed().as_nanos();
let source = match header.as_deref() {
Some(head) => head,
None => {
whole_files.push(name);
&text
}
};
let started = Instant::now();
black_box(vlog_refactor::instantiation_plan(name, source, None).ok());
plan += started.elapsed().as_nanos();
}
let each = names.len().max(1) as u128;
eprintln!(
" prefix {prefix:>9?}: {took:?} ({items} items); tier 0 over {} modules \
({} KB read, parsed whole: {whole_files:?}): read {:?}, slice {:?}, plan {:?} each",
names.len(),
bytes / 1000,
Duration::from_nanos((read / each) as u64),
Duration::from_nanos((slice / each) as u64),
Duration::from_nanos((plan / each) as u64),
);
}
}
/// `cargo test --release -p lucisv_server perf::completing_one -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn completing_one_keystroke_at_a_time() {
// `performance.md` §6d: completion cost tracks the *candidate* count before
// the 512-item cap, so it is worst at the empty prefix — exactly where
// every identifier starts. Two columns over the same workspace and the same
// prefixes: the cursor at module-item position, where every tier runs, and
// the cursor inside an expression, where the module-skeleton tier is gated
// off. The difference between them is what tier 0 costs.
let (files, body) = (4_000, 1_200);
let dir = std::env::temp_dir().join(format!("lucisv_perf_completion_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("scratch dir");
completion_corpus(&dir, files, body);
std::fs::write(dir.join("bench_top.sv"), "module bench_top;\nendmodule\n").expect("write");
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
});
let started = Instant::now();
ws.open_whole_workspace(vec![dir.clone()]);
let scan = started.elapsed();
let uri = path_to_uri(&dir.join("bench_top.sv")).expect("uri");
eprintln!(
"completion over {} indexed files (scan {scan:?}), \
{} index names, {} project words:",
ws.index().files().len(),
ws.candidates().units("").len(),
ws.candidates().words("").len()
);
for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_0001", "zzzz"] {
let mut row = String::new();
for at_item in [true, false] {
let (text, cursor) = completion_buffer(prefix, at_item);
ws.set_document(uri.clone(), text.clone());
let position = {
let doc = ws.document(&uri).expect("open");
doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start
};
let items = match crate::completion::completions(&ws, &uri, position, true) {
Some(lsp_types::CompletionResponse::List(list)) => list.items.len(),
_ => 0,
};
let took = mean(5, || {
black_box(crate::completion::completions(&ws, &uri, black_box(position), true));
});
let where_ = if at_item { "item" } else { "expr" };
row.push_str(&format!(" {where_} {took:?} ({items} items);"));
}
eprintln!(" prefix {prefix:>9?}:{row}");
}
// Tier 0's per-item bill, so the row above can be divided by 64.
let module = "aes_0000";
let path = dir.join(format!("{module}.sv"));
let text = ws.text_of(&path).expect("readable");
let read = mean(50, || {
black_box(ws.text_of(black_box(&path)));
});
let whole = mean(50, || {
black_box(
vlog_refactor::instantiation_plan(black_box(module), black_box(&text), None).ok(),
);
});
let header = crate::completion::module_header(ws.index(), module, &text).expect("a header");
let sliced = mean(50, || {
black_box(
vlog_refactor::instantiation_plan(black_box(module), black_box(&header), None).ok(),
);
});
let slicing = mean(50, || {
black_box(crate::completion::module_header(
ws.index(),
black_box(module),
black_box(&text),
));
});
eprintln!(
" one skeleton off a {}-line file: text_of {read:?}, \
instantiation_plan over the whole file {whole:?}, \
over its header alone {sliced:?} (slicing it: {slicing:?})",
text.lines().count()
);
let _ = std::fs::remove_dir_all(&dir);
}
/// `cargo test --release -p lucisv_server perf::what_the_scope_depth -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn what_the_scope_depth_default_costs() {
// What moving the shipped `lucisv.index.scopeDepth` from 0 to 2 buys and
// what it costs, on an opentitan-shaped tree this repository generates for
// itself: blocks of `rtl/` and `dv/tb/`, with the opened buffer three
// levels down — the layout `performance.md` §4 measured one indexed file
// in. Every rung of the ladder over the same tree, so the columns are
// comparable.
let (blocks, per_folder, lines) = (12, 20, 200);
let dir = std::env::temp_dir().join(format!("lucisv_perf_depth_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for block in 0..blocks {
for (folder, count) in [("rtl", per_folder), ("dv/tb", 1)] {
let path = dir.join(format!("hw/ip/blk{block:02}/{folder}"));
std::fs::create_dir_all(&path).expect("folder");
for file in 0..count {
let name = format!("b{block:02}_{}_{file:02}", folder.replace('/', "_"));
std::fs::write(path.join(format!("{name}.sv")), generated_module(&name, lines))
.expect("write");
}
}
}
let opened = dir.join("hw/ip/blk00/dv/tb/b00_dv_tb_00.sv");
let uri = path_to_uri(&opened).expect("uri");
let text = std::fs::read_to_string(&opened).expect("read");
eprintln!(
"scopeDepth over {blocks} blocks of {} files ({per_folder} rtl + 1 dv/tb each), \
buffer opened at hw/ip/blk00/dv/tb:",
per_folder + 1
);
for depth in [0u64, 1, 2, 3] {
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_scope_depth: depth,
..Default::default()
});
ws.adopt_roots(vec![dir.clone()]);
ws.set_document(uri.clone(), text.clone());
let started = Instant::now();
black_box(ws.rebuild_index());
let scan = started.elapsed();
eprintln!(
" depth {depth}: {} files indexed, {} index names, scan {scan:?}",
ws.index().files().len(),
ws.candidates().units("").len()
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// `cargo test --release -p lucisv_server perf::a_code_action -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn a_code_action_at_an_instantiation_before_and_after() {
// The owner's instrumented session, on a workspace this repository
// generates for itself: `textDocument/codeAction` answered in 3.1 s
// against 0.01–0.44 ms for every other request. VS Code sends one on
// nearly every cursor move, the server is single-threaded, so a cursor
// resting on an instantiation — where F12 leaves it — held up every
// definition and hover behind it.
//
// Three numbers over the same workspace and the same cursor:
//
// * **before** — the whole-workspace answer: `sources()` plus the engine
// over every file, which is what the handler did until 2026-08-28;
// * **after** — the same answer from the module's own fan-out;
// * **`sources()` alone** — the workspace read on its own, which is the
// floor the before column cannot go under, and the cost `rename` and
// `prepare_rename` still pay (the follow-up recorded in
// `docs/features/refactor-ports/README.md`).
let (files, lines) = (500, 200);
let dir = std::env::temp_dir().join(format!("lucisv_perf_action_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("scratch dir");
let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
std::fs::write(dir.join("sub.sv"), sub).expect("write");
// Three files instantiate `sub`; the rest have nothing to do with it.
for n in 0..3 {
std::fs::write(
dir.join(format!("top{n}.sv")),
format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"),
)
.expect("write");
}
for n in 0..files {
std::fs::write(
dir.join(format!("f{n:04}.sv")),
generated_module(&format!("f{n:04}"), lines),
)
.expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let path = dir.join("sub.sv");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), sub.to_string());
let offset = sub.find("input logic rst").expect("a port") as u32 + 12;
let before = mean(3, || {
let sources = ws.sources();
black_box(vlog_refactor::port_actions(&sources, black_box(&path), black_box(offset)));
});
let after = mean(20, || {
black_box(crate::ports::code_actions(&ws, &uri, black_box(offset)));
});
let read = mean(3, || {
black_box(ws.sources());
});
// What `textDocument/prepareRename` cost on the same workspace when this
// probe was written — the number the follow-up in the feature README was
// filed with, and the one `a_rename_before_and_after` below now closes.
let prepare = mean(3, || {
let sources = ws.sources();
let _ =
black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset)));
});
// A measurement of an answer that was not given is worthless.
assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1);
eprintln!(
"codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \
whole workspace {before:?}, fan-out {after:?} \
(`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})",
ws.index().files().len()
);
let _ = std::fs::remove_dir_all(&dir);
}
/// A workspace of `files` unrelated generated modules plus a `sub` module
/// instantiated by three tops — the shape both rename probes measure over.
/// Returns the directory, so the caller removes it.
fn rename_corpus(tag: &str, files: usize, lines: usize) -> (PathBuf, &'static str) {
let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
let dir = std::env::temp_dir().join(format!("lucisv_perf_{tag}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("scratch dir");
std::fs::write(dir.join("sub.sv"), sub).expect("write");
for n in 0..3 {
std::fs::write(
dir.join(format!("top{n}.sv")),
format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"),
)
.expect("write");
}
for n in 0..files {
std::fs::write(
dir.join(format!("f{n:04}.sv")),
generated_module(&format!("f{n:04}"), lines),
)
.expect("write");
}
(dir, sub)
}
/// `cargo test --release -p lucisv_server perf::a_rename -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn a_rename_before_and_after() {
// The owner's OpenTitan session: `prepareRename` 2.5–3.0 s and `rename`
// 3.6–8.7 s, both of them `ws.sources()` followed by an index build and an
// analysis over every in-scope file. `prepareRename` is what the rename
// key sends *before the box opens*, so those seconds are a frozen editor
// on a keypress that has committed to nothing.
//
// Four numbers over one workspace and one cursor:
//
// * **prepare, before** — `prepare_rename` over `sources()`;
// * **prepare, after** — the buffer's own analysis and the index, reading
// nothing;
// * **rename, before** — `rename` over `sources()`;
// * **rename, after** — `rename` over the symbol's fan-out.
let (files, lines) = (500, 200);
let (dir, sub) = rename_corpus("rename", files, lines);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let path = dir.join("sub.sv");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), sub.to_string());
// The module's own name, which fans out to the three files naming it.
let offset = sub.find("sub (").expect("the module name") as u32;
let prepare_before = mean(3, || {
let sources = ws.sources();
let _ =
black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset)));
});
let prepare_after = mean(2_000, || {
let _ = black_box(crate::rename::prepare(&ws, &uri, black_box(offset)));
});
let rename_before = mean(3, || {
let sources = ws.sources();
let _ = black_box(vlog_refactor::rename(&sources, &path, black_box(offset), "renamed"));
});
let rename_after = mean(20, || {
let _ = black_box(crate::rename::rename(&ws, &uri, black_box(offset), "renamed"));
});
let fan_out = ws.rename_sources(&path, "sub", Some("renamed")).len();
// Building the file set at all, and the one rung of it that is a linear
// walk over every file's records rather than a keyed lookup
// (`WorkspaceIndex::files_spelling`, the new name's dangling-use rung —
// `docs/features/refactor-rename/README.md`). Measured on its own because
// it is the only part of the set builder whose cost grows with the
// workspace rather than with the symbol.
let file_set = mean(2_000, || {
black_box(ws.rename_sources(black_box(&path), "sub", Some("renamed")));
});
let spelling_rung = mean(2_000, || {
black_box(ws.index().files_spelling(black_box("renamed")).count());
});
// A measurement of an answer that was not given is worthless.
assert!(crate::rename::prepare(&ws, &uri, offset).is_ok());
let (edit, _) = crate::rename::rename(&ws, &uri, offset, "renamed").expect("renames");
assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops");
eprintln!(
"rename of `sub`, instantiated in 3 of {} files ({lines} lines each), fan-out {fan_out} files:\n \
prepareRename: whole workspace {prepare_before:?} -> buffer+index {prepare_after:?}\n \
rename: whole workspace {rename_before:?} -> fan-out {rename_after:?}\n \
building the file set: {file_set:?}, of which `files_spelling`: {spelling_rung:?}",
ws.index().files().len()
);
let _ = std::fs::remove_dir_all(&dir);
}
/// `cargo test --release -p lucisv_server perf::a_will_rename -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn a_will_rename_before_and_after() {
// `workspace/willRenameFiles` read every in-scope file to ask each one
// "do you write an `include?" — a question the include graph already
// holds the answer to. Renaming any folder in the VS Code explorer sent
// it, so it is the same `sources()` shape as the two above.
let (files, lines) = (500, 200);
let (dir, _) = rename_corpus("willrename", files, lines);
std::fs::write(dir.join("defs.svh"), "`define W 8\n").expect("write");
std::fs::write(dir.join("includer.sv"), "`include \"defs.svh\"\nmodule includer;\nendmodule\n")
.expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri_of = |path: &std::path::Path| path_to_uri(path).expect("uri").as_str().to_string();
let renamed = vec![lsp_types::FileRename {
old_uri: uri_of(&dir.join("defs.svh")),
new_uri: uri_of(&dir.join("widths.svh")),
}];
let read_all = mean(3, || {
black_box(ws.sources());
});
let read_includers = mean(200, || {
black_box(ws.include_sources());
});
let after = mean(20, || {
black_box(crate::file_ops::will_rename(&ws, black_box(&renamed)));
});
let rewrite = crate::file_ops::will_rename(&ws, &renamed);
assert_eq!(
rewrite.edit.and_then(|edit| edit.changes.map(|c| c.len())),
Some(1),
"the one includer"
);
eprintln!(
"willRenameFiles over {} files, 1 of which includes anything:\n \
reading the scope {read_all:?} -> reading the includers {read_includers:?}\n \
whole answer, after: {after:?}",
ws.index().files().len()
);
let _ = std::fs::remove_dir_all(&dir);
}
+453 -8
View File
@@ -17,7 +17,7 @@
#![allow(clippy::mutable_key_type)]
use std::collections::HashMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit,
@@ -51,14 +51,17 @@ pub fn commands() -> Vec<String> {
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
let Some(path) = doc.path.clone() else { return Vec::new() };
// A code-action request arrives on every cursor move, and `sources()`
// reads the whole in-scope file set from disk. The engine's one-file
// question answers "there is nothing here" for almost every position
// without any of that.
if !vlog_refactor::may_have_port_action(&doc.text, offset) {
// A code-action request arrives on every cursor move, so neither half of
// this may walk the workspace. The engine's one-file question answers
// "there is nothing here" for almost every position — and where it does
// find something, it says which module, so the files handed to the engine
// are that module's own fan-out rather than every file in scope
// (`Workspace::module_sources`).
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
if modules.is_empty() {
return Vec::new();
}
let sources = ws.sources();
let sources = ws.module_sources(&path, &modules);
vlog_refactor::port_actions(&sources, &path, offset)
.into_iter()
.filter_map(|action| {
@@ -84,7 +87,6 @@ pub fn execute(
command: &str,
arguments: &[Value],
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let sources = ws.sources();
let refactoring = match command {
ADD_PORT => {
let (_, path) = target(ws, arguments.first())?;
@@ -93,10 +95,12 @@ pub fn execute(
})?;
match module_argument(arguments.get(1)) {
ModuleArgument::Name(name) => {
let sources = ws.module_sources(&path, std::slice::from_ref(&name));
vlog_refactor::add_port(&sources, ModuleRef::Name(&name), decl)?
}
ModuleArgument::Position(position) => {
let offset = offset_of(ws, arguments.first(), position)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::add_port(&sources, ModuleRef::At { file: &path, offset }, decl)?
}
ModuleArgument::Missing => {
@@ -109,11 +113,13 @@ pub fn execute(
REMOVE_PORT => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, REMOVE_PORT)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::remove_port(&sources, &path, offset)?
}
PROPAGATE_PORTS => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, PROPAGATE_PORTS)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::propagate_ports(&sources, &path, offset)?
}
other => return Err(format!("`{other}` is not a lucisv command.")),
@@ -121,6 +127,22 @@ pub fn execute(
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
}
/// The files a port refactoring **at a position** reads: the fan-out of every
/// module that position could name.
///
/// A command's position is looser than a code action's — `lucisv.addPort`
/// takes one anywhere in the module it adds to — so the module the cursor sits
/// *inside* is asked for as well as the ones its port element or its
/// instantiation names. Both questions are the engine's own
/// (`vlog_refactor`), so the set cannot drift from what the engine will then
/// go looking for.
fn sources_at(ws: &Workspace, path: &Path, offset: u32) -> Vec<(PathBuf, String)> {
let Some(text) = ws.text_of(path) else { return ws.module_sources(path, &[]) };
let mut modules = vlog_refactor::port_action_modules(&text, offset);
modules.extend(vlog_refactor::enclosing_module(&text, offset));
ws.module_sources(path, &modules)
}
/// What the second argument of `lucisv.addPort` said.
enum ModuleArgument {
Name(String),
@@ -357,6 +379,429 @@ mod tests {
assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma");
}
// ------------------------------------------------------------------
// the answer is the whole workspace's answer, computed over a subset
// ------------------------------------------------------------------
/// One action's title and the edits it carries, per file in path order.
type Shape = (String, Vec<(String, Vec<String>)>);
/// A code action as a comparable value: its title and every edit it
/// carries, per file in path order — the whole of what a client receives.
/// `WorkspaceEdit.changes` is a `HashMap`, so it is sorted here rather
/// than compared as it is stored.
fn shape(actions: &[CodeActionOrCommand]) -> Vec<Shape> {
actions
.iter()
.map(|action| {
let CodeActionOrCommand::CodeAction(action) = action else {
return ("a command".to_string(), Vec::new());
};
let mut changes: Vec<(String, Vec<String>)> = action
.edit
.as_ref()
.and_then(|edit| edit.changes.as_ref())
.map(|changes| {
changes
.iter()
.map(|(uri, edits)| {
let edits = edits
.iter()
.map(|edit| format!("{:?}{}", edit.range, edit.new_text))
.collect();
(uri.as_str().to_string(), edits)
})
.collect()
})
.unwrap_or_default();
changes.sort();
(action.title.clone(), changes)
})
.collect()
}
/// What `code_actions` used to compute: the same engine call over every
/// in-scope file. The equivalence tests below assert the new answer
/// against this one rather than against a transcription of it.
fn whole_workspace_at(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
let doc = ws.document(uri).expect("an open document");
let path = doc.path.clone().expect("a saved file");
let sources = ws.sources();
vlog_refactor::port_actions(&sources, &path, offset)
.into_iter()
.filter_map(|action| {
let edit = workspace_edit(ws, &action.edit).ok()?;
Some(CodeActionOrCommand::CodeAction(CodeAction {
title: action.title,
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
edit: Some(edit),
..Default::default()
}))
})
.collect()
}
/// A workspace of `noise` files that have nothing to do with `sub`, plus
/// `sub.sv` and three files that instantiate it.
fn crowded(tree: &Tree, noise: usize) -> Workspace {
tree.write("sub.sv", SUB);
for n in 0..3 {
tree.write(
&format!("top{n}.sv"),
&format!(
"module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"
),
);
}
for n in 0..noise {
tree.write(
&format!("noise{n}.sv"),
&format!("module noise{n};\n logic a;\n wire b;\n assign b = a;\nendmodule\n"),
);
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
ws
}
#[test]
fn a_code_action_answers_what_the_whole_workspace_would() {
let tree = Tree::new("equivalence");
let mut ws = crowded(&tree, 40);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let subset = code_actions(&ws, &sub_uri, offset);
assert_eq!(subset.len(), 1, "{subset:#?}");
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
assert_eq!(action.title, "lucisv: remove port `rst` (updates 3 instantiations)");
assert_eq!(
shape(&subset),
shape(&whole_workspace_at(&ws, &sub_uri, offset)),
"the subset must answer exactly what every file would have"
);
}
#[test]
fn the_files_a_code_action_reads_are_the_modules_own_fan_out() {
let tree = Tree::new("fanout");
let mut ws = crowded(&tree, 40);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
assert_eq!(ws.sources().len(), 44, "the whole workspace");
let read = ws.module_sources(&sub, &["sub".to_string()]);
let mut names: Vec<String> = read
.iter()
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
.collect();
names.sort();
assert_eq!(names, ["sub.sv", "top0.sv", "top1.sv", "top2.sv"], "and not one noise file");
}
#[test]
fn an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen() {
let tree = Tree::new("unsaved");
let mut ws = crowded(&tree, 20);
// A file the index knows as instantiating nothing, whose buffer now
// instantiates `sub`. No save, so no edge in the index.
let extra = tree.path.join("noise0.sv");
let extra_uri = path_to_uri(&extra).expect("uri");
let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n";
ws.set_document(extra_uri.clone(), typed.to_string());
assert!(
ws.index()
.instantiations_of("sub")
.iter()
.all(|edge| ws.index().path(edge.file) != Some(extra.as_path())),
"the index has not seen the unsaved instantiation"
);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let subset = code_actions(&ws, &sub_uri, offset);
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
assert_eq!(action.title, "lucisv: remove port `rst` (updates 4 instantiations)");
let edit = action.edit.as_ref().expect("an edit");
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
assert_eq!(shape(&subset), shape(&whole_workspace_at(&ws, &sub_uri, offset)));
}
#[test]
fn a_module_declared_twice_is_refused_through_the_subset_as_well() {
let tree = Tree::new("ambiguous");
let mut ws = crowded(&tree, 10);
// A second declaration of `sub`, in a file nothing else names.
tree.write("clone.sv", SUB);
ws.rebuild_index();
assert_eq!(ws.index().units("sub").len(), 2, "two declarations");
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
// Both definers are in the set, so the engine sees the ambiguity and
// refuses — which is no action, exactly as over the whole workspace.
assert!(ws
.module_sources(&sub, &["sub".to_string()])
.iter()
.any(|(path, _)| path.ends_with("clone.sv")));
assert!(code_actions(&ws, &sub_uri, offset).is_empty());
assert!(whole_workspace_at(&ws, &sub_uri, offset).is_empty());
}
#[test]
fn a_command_computes_over_the_subset_and_answers_the_same() {
let tree = Tree::new("command");
let mut ws = crowded(&tree, 40);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let arguments = vec![
serde_json::to_value(&sub_uri).expect("uri"),
Value::String("sub".into()),
Value::String("input logic cfg".into()),
];
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
let whole =
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
.expect("adds");
assert_eq!(warnings, whole.warnings);
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
assert_eq!(edit.changes.as_ref().expect("changes").len(), 4, "sub.sv and its three tops");
}
#[test]
fn qa_file_scope_instantiation_lands_in_the_subset() {
let tree = Tree::new("qa_filescope");
let mut ws = crowded(&tree, 20);
// A file-scope (owner-less) instantiation of `sub` — illegal SV, but
// a tolerant parse still produces an Instantiation item, and the old
// whole-workspace engine would still edit it (collect_instantiations
// walks tree.items directly). It records no InstantiationEdge (edges_of
// requires an owner), so only the references_to half of rung 3 can
// possibly find it.
let filescope_path = tree.write("filescope.sv", "sub u_fs (.clk(c), .rst(r));\n");
ws.rebuild_index();
assert!(
ws.index()
.instantiations_of("sub")
.iter()
.all(|edge| ws.index().path(edge.file) != Some(filescope_path.as_path())),
"file-scope site records no edge, as documented"
);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let read = ws.module_sources(&sub, &["sub".to_string()]);
let names: Vec<String> = read
.iter()
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
.collect();
assert!(
names.contains(&"filescope.sv".to_string()),
"file-scope instantiation site must be in the subset: {names:?}"
);
// And the whole-workspace engine really would have edited it, so
// omitting it from the subset would be a real divergence.
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let whole = whole_workspace_at(&ws, &sub_uri, offset);
let CodeActionOrCommand::CodeAction(action) = &whole[0] else { panic!("an action") };
let edit = action.edit.as_ref().expect("an edit");
let fs_uri = path_to_uri(&filescope_path).expect("uri");
assert_eq!(
edits_for(edit, &fs_uri).len(),
2,
"the whole-workspace answer edits the file-scope site"
);
let subset = code_actions(&ws, &sub_uri, offset);
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
}
#[test]
fn qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption() {
// The subset builder trusts the index for rungs 2/3, so a file that
// changed on disk with nothing telling the server (no rebuild_index,
// no didChange) is invisible to it — unlike the old `sources()` path,
// which re-reads the directory fresh every call. Attack: write a
// *second* definer of `sub` straight to disk, do NOT reindex, and
// fire a code action. Judged against invariant 1 (never corrupt), not
// against freshness: an answer that goes stale (or a refusal) is
// fine; an edit that is not internally verified would not be.
let tree = Tree::new("qa_stale_dup");
let mut ws = crowded(&tree, 10);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
// Sanity: before the duplicate exists anywhere, the subset offers the
// action normally.
assert_eq!(code_actions(&ws, &sub_uri, offset).len(), 1);
// Write a duplicate declaration straight to disk, bypassing the
// server entirely (no rebuild_index, no set_document for this path).
tree.write("dupe.sv", SUB);
// The index still knows only one definer, so the subset the server
// computes is unaware of the ambiguity and still offers the action.
assert_eq!(ws.index().units("sub").len(), 1, "the index has not been told");
let subset = code_actions(&ws, &sub_uri, offset);
assert_eq!(subset.len(), 1, "stale, but not refused — the index has not seen dupe.sv");
// The critical assertion: whatever it produced must still be an
// honest, self-consistent, verified edit over the files it actually
// read — not corruption of a file it never looked at. `dupe.sv`
// itself must be untouched (never read, never in the edit) and the
// edit that *was* produced must still verify against what changed.
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
let dupe_uri = path_to_uri(&tree.path.join("dupe.sv")).expect("uri");
let edit = action.edit.as_ref().expect("an edit");
assert!(
edit.changes.as_ref().is_none_or(|c| !c.contains_key(&dupe_uri)),
"the unindexed duplicate must not be touched: {edit:?}"
);
// Once the index is told (rebuild_index, exactly what the watcher
// does on a save it's told about), parity is restored: the subset
// now sees the duplicate and refuses, exactly like the whole
// workspace always would have.
ws.rebuild_index();
assert_eq!(ws.index().units("sub").len(), 2, "now indexed");
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "refuses once told");
}
#[test]
fn qa_generate_block_instantiation_lands_in_the_subset() {
let tree = Tree::new("qa_generate");
let mut ws = crowded(&tree, 20);
let gen_path = tree.write(
"gen.sv",
"module gen;\n genvar i;\n generate\n for (i = 0; i < 2; i = i + 1) begin : g\n logic c, r;\n sub u_g (.clk(c), .rst(r));\n end\n endgenerate\nendmodule\n",
);
ws.rebuild_index();
assert!(
ws.index()
.instantiations_of("sub")
.iter()
.any(|edge| ws.index().path(edge.file) == Some(gen_path.as_path())),
"the generate-for body instantiation is a real edge"
);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let read = ws.module_sources(&sub, &["sub".to_string()]);
let names: Vec<String> = read
.iter()
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
.collect();
assert!(names.contains(&"gen.sv".to_string()), "{names:?}");
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let subset = code_actions(&ws, &sub_uri, offset);
let whole = whole_workspace_at(&ws, &sub_uri, offset);
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
}
#[test]
fn qa_escaped_module_name_instantiation_parity_with_whole_workspace() {
// Not a subset-specific question: does an escaped-identifier
// instantiation (`\sub$weird u1 (...)`) even resolve to the module it
// names, workspace-index-wise, so the subset builder's `units`/
// `instantiations_of`/`references_to` lookups have anything to find?
// Attacking whether the *subset* diverges from the *whole-workspace*
// answer here, not whether escaped identifiers work at all (a
// pre-existing question this round did not touch).
let tree = Tree::new("qa_escaped");
tree.write("esc.sv", "module esc;\n \\sub u_esc (.clk(c), .rst(r));\nendmodule\n");
let mut ws = crowded(&tree, 10);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let subset = code_actions(&ws, &sub_uri, offset);
let whole = whole_workspace_at(&ws, &sub_uri, offset);
// Whichever way the parser/binder treats the escaped identifier
// `\sub ` (as `sub`, or as a distinct name), the subset and the
// whole-workspace computation must agree either way.
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
}
#[test]
fn qa_add_port_by_position_still_fans_out_to_instantiation_files() {
// `a_command_computes_over_the_subset_and_answers_the_same` (the
// dev's own equivalence test) drives `lucisv.addPort` with a
// *module-name* argument. The *Position* argument takes a completely
// different path to the module (`sources_at` → `port_action_modules`
// + `enclosing_module`, rather than `module_sources` fed the name
// directly) and is exactly the code action's own code path
// (`ModuleArgument::Position` mirrors `ModuleRef::At`). Confirm it
// still reaches every instantiating file, not just the declaring one.
let tree = Tree::new("qa_add_by_position");
let mut ws = crowded(&tree, 30);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let arguments = vec![
serde_json::to_value(&sub_uri).expect("uri"),
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
Value::String("input logic cfg".into()),
];
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
assert_eq!(warnings.len(), 3, "one TODO warning per instantiating top: {warnings:?}");
let changes = edit.changes.as_ref().expect("changes");
assert_eq!(changes.len(), 4, "sub.sv and its three instantiating tops: {changes:?}");
for n in 0..3 {
let top_uri = path_to_uri(&tree.path.join(format!("top{n}.sv"))).expect("uri");
assert_eq!(edits_for(&edit, &top_uri).len(), 1, "top{n}.sv must gain the connection");
}
let whole =
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
.expect("adds");
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
}
#[test]
fn qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled() {
// A module the index has never seen at all — not stale, genuinely
// absent, e.g. a brand-new buffer the user has not saved yet. Rung 2
// (`index.units`) has nothing; only rung 1 (the request's own file)
// can supply it. The cursor sits in that same new buffer, so rung 1
// must be enough on its own — and it must not panic or silently
// return no action just because the index is empty for this name.
let tree = Tree::new("qa_unsaved_new_module");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.index().units("brandnew").is_empty(), "the index has never heard of it");
let text = "module brandnew (\n input logic a,\n input logic b\n);\nendmodule\n";
let new_path = tree.path.join("brandnew.sv"); // never written to disk
let new_uri = path_to_uri(&new_path).expect("uri");
ws.set_document(new_uri.clone(), text.to_string());
let offset = text.find("input logic b").expect("b") as u32 + 12;
let subset = code_actions(&ws, &new_uri, offset);
assert_eq!(subset.len(), 1, "{subset:#?}");
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
assert_eq!(action.title, "lucisv: remove port `b` (no instantiation in scope)");
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
}
#[test]
fn an_unknown_command_is_declined() {
let tree = Tree::new("unknown");
+634 -4
View File
@@ -24,10 +24,20 @@ use crate::uri::path_to_uri;
/// The identifier at `offset` and its current name, or the reason it cannot
/// be renamed. Returning the reason — rather than `null` — is what puts the
/// engine's sentence in the editor's rename box instead of a shrug.
///
/// Answered from the buffer's own analysis and the index alone: no file is
/// read, nothing is parsed. This request is what the rename key sends before
/// the rename box even opens, and reading the workspace for it froze the whole
/// server for 2.5–3.0 s on OpenTitan. Which refusals that costs — and which of
/// them `rename` then delivers instead — is the table in
/// `docs/features/refactor-rename/README.md`.
pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameResponse, String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?;
if doc.path.is_none() {
return Err(UNSAVED.to_string());
}
let target =
vlog_refactor::prepare_rename_here(&doc.semantics, &doc.external, ws.index(), offset)?;
Ok(PrepareRenameResponse::RangeWithPlaceholder {
range: doc.positions().range(target.range),
placeholder: target.name,
@@ -44,7 +54,16 @@ pub fn rename(
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
let refactoring = vlog_refactor::rename(&ws.sources(), &path, offset, new_name)?;
// The name the cursor sits on, read off the buffer, is what the index is
// asked for the fan-out. No refusal is taken here: `vlog_refactor::rename`
// is the one voice that decides, and it decides over the files below. A
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
// the engine will say so, and saying it is cheap either way.
let sources = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(&path, &name, Some(new_name)),
None => ws.sources(),
};
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
for (path, edits) in &refactoring.edits {
@@ -80,7 +99,7 @@ const UNSAVED: &str = "lucisv can only rename inside a saved file.";
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::str::FromStr;
/// A scratch workspace root. Removed on drop.
@@ -206,6 +225,617 @@ mod tests {
assert_eq!(edits[0].range.start.character, 7);
}
// ------------------------------------------------------------------
// The fan-out equivalence suite
// ------------------------------------------------------------------
//
// `rename` is handed the symbol's fan-out through the index instead of
// every in-scope file. A rename that edits fewer files than the truth is
// corruption (CLAUDE.md invariant 1), and a refusal the narrow set cannot
// reach is a refusal the user never sees — so every case below asks the
// engine the same question twice, over the subset and over the whole
// workspace, and asserts the two answers are the same bytes and the same
// sentences. The sufficiency argument they are the evidence for is in
// `docs/features/refactor-rename/README.md`.
/// The file set the server would hand `rename` for a cursor at `offset`.
fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec<PathBuf> {
let doc = ws.document_for_path(path).expect("the request's file is open");
match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
None => ws.sources(),
}
.into_iter()
.map(|(path, _)| path)
.collect()
}
/// Ask the engine over the fan-out and over the whole workspace, and
/// assert the two answers are indistinguishable. Returns the answer, so a
/// caller can also assert *what* it was.
fn same_answer(
ws: &Workspace,
path: &Path,
offset: u32,
new_name: &str,
) -> Result<vlog_refactor::RefactorEdit, String> {
let everything = ws.sources();
let doc = ws.document_for_path(path).expect("the request's file is open");
let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
None => everything.clone(),
};
for (path, text) in &subset {
let found = everything.iter().find(|(held, _)| held == path);
assert_eq!(
found.map(|(_, text)| text),
Some(text),
"{} is in the fan-out with text the whole scope does not have",
path.display()
);
}
let whole = vlog_refactor::rename(&everything, path, offset, new_name);
let narrow = vlog_refactor::rename(&subset, path, offset, new_name);
match (&whole, &narrow) {
(Ok(whole), Ok(narrow)) => {
assert_eq!(whole.edits, narrow.edits, "the fan-out edited different bytes");
assert_eq!(whole.warnings, narrow.warnings, "the fan-out warned differently");
}
(Err(whole), Err(narrow)) => {
assert_eq!(whole, narrow, "the fan-out refused in different words");
}
(Ok(whole), Err(narrow)) => panic!(
"the fan-out invented a refusal: {narrow}, where the workspace edited {} files",
whole.file_count()
),
(Err(whole), Ok(narrow)) => panic!(
"the fan-out lost the refusal `{whole}` and edited {} files instead",
narrow.file_count()
),
}
narrow
}
/// A workspace of `files`, every one of them also opened as a buffer when
/// `open` names it, with the first named file's URI returned.
fn tree_with(tree: &Tree, files: &[(&str, &str)], open: &[&str]) -> (Workspace, Vec<PathBuf>) {
let paths: Vec<PathBuf> = files.iter().map(|(name, text)| tree.write(name, text)).collect();
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
for name in open {
let path = tree.path.join(name);
let text = fs::read_to_string(&path).expect("written above");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri, text);
}
(ws, paths)
}
const MOD: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n";
const ONE: &str = "module one;\n logic c, d;\n sub u_a (.clk(c), .q(d));\nendmodule\n";
const TWO: &str =
"module two;\n logic c, d;\n sub #(.W(3)) u_b (.clk(c), .q(d));\nendmodule\n";
const GEN: &str = "module three;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_c (.clk(1'b0), .q());\n end\n endgenerate\nendmodule\n";
const QUIET: &str = "module quiet;\n wire unrelated;\n assign unrelated = 1'b0;\nendmodule\n";
#[test]
fn the_fan_out_answers_a_cross_file_module_rename_exactly_as_the_workspace_does() {
let tree = Tree::new("fanout_module");
let files = [
("sub.sv", MOD),
("one.sv", ONE),
("two.sv", TWO),
("three.sv", GEN),
("quiet.sv", QUIET),
];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let at = at(ONE, "sub u_a");
let edit = same_answer(&ws, &path, at, "child").expect("renames");
assert_eq!(edit.file_count(), 4, "the declaration and the three files naming it");
// And the narrowing is real: the file that never spells the name is
// not read at all.
let fan = fan_out(&ws, &path, at, "child");
assert!(!fan.contains(&tree.path.join("quiet.sv")), "{fan:?}");
assert!(fan.contains(&tree.path.join("three.sv")), "the generate-block site: {fan:?}");
}
#[test]
fn the_fan_out_keeps_the_end_label_and_the_declaration_together() {
let tree = Tree::new("fanout_endlabel");
let (ws, _) = tree_with(&tree, &[("sub.sv", MOD), ("one.sv", ONE)], &["sub.sv"]);
let path = tree.path.join("sub.sv");
let edit = same_answer(&ws, &path, at(MOD, "sub #"), "child").expect("renames");
let own = edit.edits_for(&path);
assert_eq!(own.len(), 2, "the header name and the `endmodule : sub` label");
}
#[test]
fn the_fan_out_carries_a_port_rename_to_every_connection() {
let tree = Tree::new("fanout_port");
let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", TWO), ("quiet.sv", QUIET)];
let (ws, _) = tree_with(&tree, &files, &["sub.sv"]);
let path = tree.path.join("sub.sv");
let edit = same_answer(&ws, &path, at(MOD, "clk,"), "clock").expect("renames");
assert_eq!(edit.file_count(), 3, "the module and both files connecting `.clk`");
}
#[test]
fn the_fan_out_carries_a_package_member_rename_to_every_importer() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const IMPORTER: &str =
"module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
const QUALIFIER: &str =
"module qualifier;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n";
let tree = Tree::new("fanout_pkg");
let files =
[("pkg.sv", PKG), ("reader.sv", IMPORTER), ("qual.sv", QUALIFIER), ("quiet.sv", QUIET)];
let (ws, _) = tree_with(&tree, &files, &["reader.sv"]);
let path = tree.path.join("reader.sv");
let edit = same_answer(&ws, &path, at(IMPORTER, "DEPTH;"), "SIZE").expect("renames");
assert_eq!(edit.file_count(), 3, "the package and both files reading it");
}
#[test]
fn the_fan_out_sees_a_reference_only_an_unsaved_buffer_has() {
let tree = Tree::new("fanout_unsaved");
// On disk `two.sv` says nothing about `sub`; the buffer instantiates
// it. The index has never seen the buffer's text.
let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", QUIET)];
let (mut ws, _) = tree_with(&tree, &files, &["one.sv"]);
let two = tree.path.join("two.sv");
ws.set_document(path_to_uri(&two).expect("uri"), TWO.to_string());
assert!(
ws.index().instantiations_of("sub").len() < 2,
"premise: the index has not seen the buffer's instantiation"
);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(!edit.edits_for(&two).is_empty(), "the unsaved instantiation is renamed too");
}
#[test]
fn the_fan_out_refuses_a_name_the_workspace_declares_twice_in_the_same_words() {
let tree = Tree::new("fanout_dup");
let files = [("sub.sv", MOD), ("copy.sv", MOD), ("one.sv", ONE)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let refusal =
same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect_err("declared twice");
assert!(refusal.contains("more than one indexed file"), "{refusal}");
}
#[test]
fn the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere() {
// `three.sv` names `sub`; `taken.sv` declares the module the rename
// wants to become. Renaming `sub` to `taken` makes every `sub` site
// ambiguous — a file the postings for `sub` alone would never name.
const TAKEN: &str = "module taken;\nendmodule\n";
const USES_TAKEN: &str = "module holder;\n taken u_t ();\nendmodule\n";
let tree = Tree::new("fanout_capture");
let files =
[("sub.sv", MOD), ("one.sv", ONE), ("taken.sv", TAKEN), ("uses.sv", USES_TAKEN)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let refusal =
same_answer(&ws, &path, at(ONE, "sub u_a"), "taken").expect_err("would capture");
assert!(refusal.contains("would change what"), "{refusal}");
let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "taken");
assert!(fan.contains(&tree.path.join("uses.sv")), "the new name's own fan-out: {fan:?}");
}
/// The two `` `define`` warnings come from files the index's own define
/// tables name, so both survive the narrowing: a macro *called* the name,
/// and a macro whose **body** spells it, each in a file that has nothing
/// else to do with the symbol.
#[test]
fn the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read() {
const NAMED: &str = "`define sub 1\nmodule named_holder;\nendmodule\n";
const BODY: &str = "`define WRAP(x) sub x\nmodule body_holder;\n wire w;\nendmodule\n";
let tree = Tree::new("fanout_macro");
let files = [
("sub.sv", MOD),
("one.sv", ONE),
("named.sv", NAMED),
("body.svh", BODY),
("quiet.sv", QUIET),
];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(
edit.warnings.iter().any(|w| w.contains("is also a macro defined")),
"{:?}",
edit.warnings
);
assert!(
edit.warnings.iter().any(|w| w.contains("in the body of macro `WRAP`")),
"{:?}",
edit.warnings
);
let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "child");
assert!(fan.contains(&tree.path.join("named.sv")), "the macro's own name: {fan:?}");
assert!(fan.contains(&tree.path.join("body.svh")), "the macro's body: {fan:?}");
assert!(!fan.contains(&tree.path.join("quiet.sv")), "and nothing else: {fan:?}");
}
#[test]
fn every_file_the_workspace_rename_edits_is_in_the_fan_out() {
// The invariant-1 assertion, made directly rather than through an
// equality: whatever the whole workspace would rewrite, the narrow set
// must contain — otherwise a rename edits fewer files than the truth.
let tree = Tree::new("fanout_covers");
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const IMPORTER: &str = "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\n sub u (.clk(1'b0), .q());\nendmodule\n";
let files = [
("sub.sv", MOD),
("one.sv", ONE),
("two.sv", TWO),
("three.sv", GEN),
("pkg.sv", PKG),
("reader.sv", IMPORTER),
("quiet.sv", QUIET),
];
let (ws, _) = tree_with(&tree, &files, &["reader.sv"]);
let path = tree.path.join("reader.sv");
let everything = ws.sources();
let text = fs::read_to_string(&path).expect("written");
for offset in 0..=text.len() as u32 {
let Ok(whole) = vlog_refactor::rename(&everything, &path, offset, "renamed_thing")
else {
continue;
};
let fan = fan_out(&ws, &path, offset, "renamed_thing");
for (edited, _) in &whole.edits {
assert!(
fan.contains(edited),
"byte {offset} renames {} and the fan-out does not hold it: {fan:?}",
edited.display()
);
}
let _ = same_answer(&ws, &path, offset, "renamed_thing");
}
}
/// QA, 2026-08-28 attack: an instantiation spelled with an escaped
/// identifier (`` \sub ``) is a *different* name from `sub` to
/// `vlog_semantic` today (a pre-existing simplification, noted in this
/// feature's own 2026-08-24 QA round for a declaration, not an
/// instantiation) — it resolves to nothing, so it is renamed by neither
/// path. The question this pins is narrower: does narrowing the file set
/// change that answer? It must not, since both paths call the identical
/// engine; the risk would be the fan-out *dropping* the file outright
/// while the whole-workspace run still watches it (`\sub` contains the
/// word `sub`, so `contains_word` — and hence `watched_files` — still
/// picks it up in the whole run). `same_answer` checks the observable
/// output only (edits, warnings, or refusal), which is what must agree.
#[test]
fn an_escaped_identifier_instantiation_does_not_break_fan_out_parity() {
const ESCAPED: &str = "module holder;\n \\sub u_weird (.clk(1'b0), .q());\nendmodule\n";
let tree = Tree::new("fanout_escaped");
let files = [("sub.sv", MOD), ("one.sv", ONE), ("escaped.sv", ESCAPED)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(
edit.edits_for(&tree.path.join("escaped.sv")).is_empty(),
"the escaped spelling is a different name to vlog_semantic and must stay untouched"
);
}
/// QA, 2026-08-28 attack: a same-spelling but *different* symbol (a
/// module unit named `sub` vs. a port/member also named `sub` in an
/// unrelated module) must not cross-contaminate the fan-out — renaming
/// the unit must not touch the member's own declaration or its file.
#[test]
fn a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out() {
const OTHER_MODULE_WITH_A_PORT_NAMED_SUB: &str =
"module other;\n wire sub;\n assign sub = 1'b0;\nendmodule\n";
let tree = Tree::new("fanout_same_spelling_different_symbol");
let files =
[("sub.sv", MOD), ("one.sv", ONE), ("other.sv", OTHER_MODULE_WITH_A_PORT_NAMED_SUB)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(
edit.edits_for(&tree.path.join("other.sv")).is_empty(),
"the unrelated wire named `sub` must not be touched: {:?}",
edit.edits_for(&tree.path.join("other.sv"))
);
// other.sv may legitimately be *watched* by the whole-word text
// search (it spells "sub"), but it must never be *edited* — checked
// above — nor must its own local wire's meaning change, which
// `same_answer`'s byte-identical edits/warnings assertion already
// confirmed by passing at all.
}
/// QA, 2026-08-28 attack: the escape hatch (refusal 10 / ambiguous
/// posting) must fire even when the ambiguity is on the **new** name,
/// discovered on the second spelling `fan_out_of` walks, not the first.
/// `Workspace::rename_sources` iterates `[name, new_name]` in that order
/// and bails to `sources()` on the first ambiguous hit — this attacks the
/// case where the *old* name's rung is completely unambiguous and only
/// the second iteration finds the problem, to check the early return
/// doesn't leak a partially-built (too-narrow) `wanted` set instead of
/// truly falling back to the whole scope.
#[test]
fn the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous() {
const A: &str = "package taken_pkg;\n parameter int DEPTH = 1;\nendpackage\n";
const B: &str = "package taken_pkg;\n parameter int DEPTH = 2;\nendpackage\n";
const READER: &str =
"module reader;\n import taken_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
let tree = Tree::new("fanout_ambig_on_new_name");
let files =
[("sub.sv", MOD), ("one.sv", ONE), ("a.sv", A), ("b.sv", B), ("reader.sv", READER)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let at = at(ONE, "sub u_a");
// `sub` (the old name) has an unambiguous, tiny fan-out on its own.
let fan = fan_out(&ws, &path, at, "taken_pkg");
assert_eq!(
fan.len(),
ws.sources().len(),
"the new name's own ambiguity must still hand back the whole scope: {fan:?}"
);
same_answer(&ws, &path, at, "taken_pkg").expect_err("ambiguous new name");
}
#[test]
fn an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope() {
// Two files declare the *same* package, so `cfg_pkg::DEPTH` names
// either declaration equally. The index records that the declarations
// are ambiguously referenced but not which file does it, so the
// fan-out refuses to narrow at all — which is how the refusal
// survives.
const A: &str = "package cfg_pkg;\n parameter int DEPTH = 1;\nendpackage\n";
const B: &str = "package cfg_pkg;\n parameter int DEPTH = 2;\nendpackage\n";
const READER: &str =
"module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
let tree = Tree::new("fanout_ambig");
let files = [("a.sv", A), ("b.sv", B), ("reader.sv", READER), ("quiet.sv", QUIET)];
let (ws, _) = tree_with(&tree, &files, &["a.sv"]);
let path = tree.path.join("a.sv");
let at = at(A, "DEPTH =");
let fan = fan_out(&ws, &path, at, "SIZE");
assert_eq!(
fan.len(),
ws.sources().len(),
"an ambiguous posting hands back the whole scope: {fan:?}"
);
same_answer(&ws, &path, at, "SIZE").expect_err("ambiguous");
}
/// Found by QA on 2026-08-28 as a **lost refusal**, and closed by the
/// sixth rung the lead ruled for the same day; kept as the regression
/// test for it, now asserting parity rather than pinning the divergence.
///
/// A file whose only mention of the **new** name is a bare use that
/// resolves to nothing today — `import taken_pkg::*` of a package nobody
/// declares yet — declares nothing, references nothing under the *old*
/// name, instantiates nothing and defines no macro, so the first five
/// rungs of the fan-out cannot see it. The rename is exactly what gives
/// that import a meaning, which is what capture rule 12 refuses over, so
/// the narrow path used to answer `Ok` where the whole workspace refused
/// — a materially weaker answer, not a lost warning.
/// `WorkspaceIndex::files_spelling` is the rung that finds it: the
/// per-file records keep every external use under the name it spells,
/// including the ones that resolved to nothing.
#[test]
fn a_dangling_import_of_the_new_name_is_refused_by_both_paths() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const STRAY_IMPORT: &str = "module strayer;\n import taken_pkg::*;\nendmodule\n";
let tree = Tree::new("fanout_dangling_import");
let files = [("pkg.sv", PKG), ("stray.sv", STRAY_IMPORT)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
let at = at(PKG, "cfg_pkg;");
let fan = fan_out(&ws, &path, at, "taken_pkg");
assert!(
fan.contains(&tree.path.join("stray.sv")),
"the dangling import's file is in the fan-out through `files_spelling`: {fan:?}"
);
let refusal =
same_answer(&ws, &path, at, "taken_pkg").expect_err("would capture the import");
assert!(refusal.contains("would change what"), "{refusal}");
assert!(refusal.contains("taken_pkg"), "{refusal}");
}
/// The other half of the ruling: the **old** name needs no such rung, and
/// this is the case that would expose it if it did. `stray.sv`'s only tie
/// to the rename is an `import cfg_pkg::*`-shaped use of a name that
/// resolves to nothing — spelled with the name being renamed *away*.
/// A rename only ever removes declarations of the old name, so a lookup
/// that failed before still fails after; the answer cannot move, and both
/// paths agree without `stray.sv` being read.
#[test]
fn a_dangling_use_of_the_old_name_needs_no_rung_of_its_own() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
// `absent_pkg` is declared nowhere, and is what the rename renames to
// nothing: the file's only spelling of it stays unresolved throughout.
const STRAY: &str = "module strayer;\n import absent_pkg::*;\nendmodule\n";
let tree = Tree::new("fanout_dangling_old");
let files = [("pkg.sv", PKG), ("stray.sv", STRAY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
// Rename the *package* to `absent_pkg` — the new-name rung must pull
// `stray.sv` in and both paths must refuse …
let package = at(PKG, "cfg_pkg;");
same_answer(&ws, &path, package, "absent_pkg").expect_err("would capture the import");
// … while a rename whose *old* name is the dangling one has nothing to
// capture: renaming `DEPTH`, which `stray.sv` never spells, leaves it
// out of the set and both paths agree.
let depth = at(PKG, "DEPTH =");
let edit = same_answer(&ws, &path, depth, "SIZE").expect("renames");
assert_eq!(edit.file_count(), 1, "only the package's own file");
let fan = fan_out(&ws, &path, depth, "SIZE");
assert!(!fan.contains(&tree.path.join("stray.sv")), "{fan:?}");
}
// ------------------------------------------------------------------
// QA, 2026-08-29: re-verification of rung 6 (files_spelling) after the
// lead-authorized fix for the dangling-import residue.
// ------------------------------------------------------------------
/// Attack on rung 6's completeness: the new name spelled **only** as the
/// base of an `extends` clause the workspace does not (yet) declare. This
/// goes through `Target::Unit`, not `Target::Package` — a different
/// resolution path than the import case rung 6 was built for — so it is
/// worth checking on its own rather than trusting the same mechanism
/// covers it by analogy.
#[test]
fn a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const STRAY_EXTENDS: &str =
"class derived extends taken_base;\n function void go();\n endfunction\nendclass\n";
let tree = Tree::new("fanout_extends_base");
let files = [("pkg.sv", PKG), ("stray.sv", STRAY_EXTENDS)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
let at = at(PKG, "cfg_pkg;");
let fan = fan_out(&ws, &path, at, "taken_base");
assert!(
fan.contains(&tree.path.join("stray.sv")),
"the extends base is a Target::Unit miss, always non-empty paths: {fan:?}"
);
let refusal =
same_answer(&ws, &path, at, "taken_base").expect_err("would give the base a meaning");
assert!(refusal.contains("would change what"), "{refusal}");
}
/// Attack on rung 6's completeness: a bare, unqualified reference to the
/// new name written inside a class that `extends` an **existing,
/// unrelated** base, with no import in scope — the one shape that
/// produces `Resolution::InheritedCandidate` with genuinely **empty**
/// paths (`miss()`'s branch when `nearest_extends` finds a base but no
/// import supplied anything), which `files_spelling` cannot see (it reads
/// only facts with non-empty paths). The argument this pins: such a
/// reference is resolved *purely* from the file's own unedited text and
/// never depends on the workspace (`resolve_external` never even tries
/// `follow_paths` against an empty list), so it cannot change meaning
/// under any rename — excluding the file costs nothing, on this rung or
/// the whole-workspace path alike.
#[test]
fn an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const EXISTING_BASE: &str = "class existing_base;\nendclass\n";
// No import anywhere in `stray.sv`, so the lexical miss on
// `taken_member` inside `derived` (which extends `existing_base`)
// collects an empty `external` list and becomes an `InheritedCandidate`
// with `paths: []` — recorded nowhere, per `facts_from_analysis`.
const STRAY: &str = "class derived extends existing_base;\n function void go();\n taken_member = 1;\n endfunction\nendclass\n";
let tree = Tree::new("fanout_inherited_empty_paths");
let files = [("pkg.sv", PKG), ("base.sv", EXISTING_BASE), ("stray.sv", STRAY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
let at = at(PKG, "cfg_pkg;");
let fan = fan_out(&ws, &path, at, "taken_member");
assert!(
!fan.contains(&tree.path.join("stray.sv")),
"an empty-paths InheritedCandidate is invisible to files_spelling by design: {fan:?}"
);
// Parity must still hold: excluding the file must not change the
// answer, because the reference inside it can never resolve
// differently regardless of what `cfg_pkg` becomes.
same_answer(&ws, &path, at, "taken_member").expect("renames, no capture possible");
}
/// Attack on rung 6's soundness: a **local-only** symbol in a third file
/// that happens to share the new name's spelling must not trigger a
/// bogus refusal. `files_spelling` explicitly excludes `ReferenceFact::Local`
/// facts (a local declaration/use resolves inside its own file and the
/// workspace was never consulted), so the file should not even be pulled
/// in — and if it were, the rename must still succeed, since no capture is
/// possible against a symbol nothing outside that file can see.
#[test]
fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const LOCAL_ONLY: &str =
"module unrelated;\n wire taken_local;\n assign taken_local = 1'b0;\nendmodule\n";
let tree = Tree::new("fanout_local_only");
let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
let at = at(PKG, "cfg_pkg;");
let fan = fan_out(&ws, &path, at, "taken_local");
assert!(
!fan.contains(&tree.path.join("local.sv")),
"a purely local declaration/use is not an external fact: {fan:?}"
);
let edit =
same_answer(&ws, &path, at, "taken_local").expect("renames, no capture possible");
assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty());
}
/// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two
/// packages, `p_pkg` and `q_pkg`, both export a member spelled the same
/// (`shared_name`); a third file imports both, `p_pkg` first, so
/// "first-written import wins" resolves `shared_name` to `p_pkg`'s
/// declaration. Renaming *away* `p_pkg::shared_name` removes the winning
/// candidate, so the same reference should fall through to `q_pkg`'s
/// pre-existing, completely unrelated declaration — a meaning change the
/// whole-workspace verifier must refuse over (rule 12, in the direction
/// "an existing use is captured by nothing new — it silently rebinds to
/// another *existing* declaration"). The old-name argument says this
/// cannot be missed because rung 1 walks *every* declaration named
/// `shared_name` (both `p_pkg`'s and `q_pkg`'s, not just the target's),
/// so the importer is pulled in via `references_to` of `p_pkg`'s
/// declaration regardless.
#[test]
fn removing_the_old_names_winning_declaration_does_not_escape_the_fan_out() {
const P: &str = "package p_pkg;\n parameter int shared_name = 1;\nendpackage\n";
const Q: &str = "package q_pkg;\n parameter int shared_name = 2;\nendpackage\n";
const USER: &str = "module user;\n import p_pkg::*;\n import q_pkg::*;\n localparam int X = shared_name;\nendmodule\n";
let tree = Tree::new("fanout_shadow_unmask");
let files = [("p.sv", P), ("q.sv", Q), ("user.sv", USER)];
let (ws, _) = tree_with(&tree, &files, &["p.sv"]);
let path = tree.path.join("p.sv");
let at = at(P, "shared_name =");
let fan = fan_out(&ws, &path, at, "renamed_thing");
assert!(
fan.contains(&tree.path.join("user.sv")),
"the importer is posted against p_pkg's declaration today: {fan:?}"
);
assert!(
fan.contains(&tree.path.join("q.sv")),
"rung 1 walks every declaration named `shared_name`, not only the target's: {fan:?}"
);
// Whichever way the whole-workspace path answers this (refuse, since
// `user.sv`'s meaning silently moves from p_pkg to q_pkg; or edit,
// if some other rule intervenes first), the subset must answer
// identically — that is the property under attack, not a specific
// outcome.
// The hunt comes up empty, and reading why is the point: `user.sv`'s
// `shared_name` currently resolves to `p_pkg`'s declaration — the
// rename target itself — so it is not a bystander a removal could
// silently unmask, it is an *edit site*: the rename rewrites it to
// `renamed_thing` along with the declaration, so the text never says
// `shared_name` again for `follow_paths` to re-resolve against
// `q_pkg`. A reference can only be affected by a name's removal by
// spelling that exact name, and by the Lemma any such reference
// either resolves to the target (edited away, as here) or to some
// *other* declaration of the same name (already covered by rung 1/2's
// sweep over every declarer, not only the target's) — there is no
// third case for the old name to fall into.
let edit = same_answer(&ws, &path, at, "renamed_thing").expect("renames");
assert_eq!(edit.file_count(), 2, "the declaration and the importer's edited reference");
assert!(
edit.edits_for(&tree.path.join("q.sv")).is_empty(),
"q_pkg's own unrelated declaration is never touched"
);
}
#[test]
fn an_open_buffer_beats_disk_when_the_rename_is_computed() {
let tree = Tree::new("buffer");
+558 -17
View File
@@ -68,9 +68,9 @@ use serde_json::Value;
use crate::settings::ClientSettings;
use crate::state::{IndexEvent, Scan, Workspace};
use crate::{
code_action, completion, diagnostics, file_ops, folding, format, hierarchy, hover, includes,
inlay, inline, large, lens, linked, nav, on_type, pairs, ports, rename, selection, settings,
signature, symbols, sync, tokens, type_def, type_hierarchy, watch,
code_action, completion, design_hierarchy, diagnostics, file_ops, folding, format, hierarchy,
hover, includes, inlay, inline, large, lens, linked, nav, on_type, pairs, ports, rename,
selection, settings, signature, symbols, sync, tokens, type_def, type_hierarchy, watch,
};
/// What the client said it can do, read once at `initialize` because that is
@@ -112,6 +112,9 @@ pub struct ClientAbilities {
/// which error code declines `semanticTokens/full` on a large buffer —
/// see `docs/features/large-file-mode/README.md`.
pub token_server_cancel: bool,
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
/// a notification whenever the installed workspace index changes.
pub hierarchy_view: bool,
}
/// Everything the server owns.
@@ -142,6 +145,8 @@ pub struct Server {
/// buffer's text, and the workspace index. It is the whole of a
/// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`.
generation: u64,
/// Revision of the completed index exposed to the custom hierarchy view.
hierarchy_revision: u64,
/// The last full-or-delta semantic-token answer for each open buffer —
/// what a delta is computed *against*. Dropped on `didClose`, so this
/// only ever holds what the editor is showing. See
@@ -188,6 +193,11 @@ pub struct Server {
/// [`Server::must_wait`] — this is the order contract, not a queue of its
/// own.
held: Vec<Message>,
/// `--verbose`: whether every operation says how long it took, in the
/// client's log channel. Off is the shipped state and the whole of what it
/// costs is the branch that reads this field — see
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
verbose: bool,
}
/// How long a burst of `didChange` notifications may sit unanalyzed once the
@@ -255,6 +265,7 @@ impl Server {
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
storage: Option<std::path::PathBuf>,
verbose: bool,
) -> Server {
Server::started(
connection,
@@ -262,6 +273,7 @@ impl Server {
abilities,
ClientSettings::default(),
storage,
verbose,
Vec::new(),
)
}
@@ -283,6 +295,7 @@ impl Server {
abilities: ClientAbilities,
client: ClientSettings,
storage: Option<std::path::PathBuf>,
verbose: bool,
queued: Vec<Message>,
) -> Server {
// Started before the first scan, not in `run`: the scan below answers
@@ -302,6 +315,7 @@ impl Server {
request_ids: 0,
pending: HashMap::new(),
generation: 0,
hierarchy_revision: 0,
tokens: HashMap::new(),
token_results: 0,
indexings: 0,
@@ -312,6 +326,7 @@ impl Server {
answering_a_rescan: false,
stopped: false,
held: Vec::new(),
verbose,
};
// Nothing has been built yet, so there is no rebuild to owe: the
// `true` this returns for a non-default `client` is the rebuild that
@@ -338,6 +353,7 @@ impl Server {
if server.stopped {
return server;
}
server.hierarchy_index_changed();
// A buffer can now be *opened* during the startup scan, and what was
// published for it then was computed against a half-built index. This
// is the same debt a rescan pays at the end of `reindex`, owed here
@@ -447,6 +463,7 @@ impl Server {
// `shutdown` included, because a request sent before a shutdown
// is a request the client is still owed an answer to.
if self.must_wait() && matches!(message, Message::Request(_)) {
self.say_held(&message);
// The cancels this burst carried were consumed on the way
// here, and `cancelled_in` runs again over the held batch — so
// they go back in front of what they cancel rather than being
@@ -517,11 +534,47 @@ impl Server {
self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty()
}
/// Whether the installed index covers the whole scope with no indexing
/// work outstanding — what the hierarchy snapshot reports as `complete`.
///
/// **Both clauses, not just `scanning`.** `!self.scanning` alone would be
/// answering "is a scan running *this instant*", and a snapshot taken
/// between a finished scan and a rescan already asked for would call a
/// stale index complete. Today [`Server::must_wait`] makes that
/// unreachable — a request arriving with `rescan_wanted` set or anything
/// `held` is set aside rather than answered, so a snapshot only ever
/// reaches this function when both are already clear, and `rescan_wanted`
/// is in any case only ever set while `scanning` is true. Saying it here
/// anyway costs nothing and means the honesty of the flag does not depend
/// on a scheduling invariant two hundred lines away staying true; a
/// hypothetical future exemption from `must_wait` would degrade the flag,
/// not break it. Pinned by
/// `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`.
fn index_is_complete(&self) -> bool {
!self.scanning && !self.must_wait()
}
// ------------------------------------------------------------------
// requests
// ------------------------------------------------------------------
/// Answer one request, timing it when `--verbose` asked.
///
/// **The line goes out before the response it describes.** The dispatch is
/// here and the response is sent by the caller, so a wrapper can only
/// speak first — which is also what keeps the measurement to exactly the
/// handler, with none of the transport in it. Nothing keys off the order:
/// a `window/logMessage` carries no id, and a client pairs the response
/// with its request by id whatever arrived in between.
fn request(&mut self, request: Request) -> Response {
let Some(started) = self.timer() else { return self.answer_request(request) };
let method = request.method.clone();
let response = self.answer_request(request);
self.timing(format!("{method} answered in {}", ms(started)));
response
}
fn answer_request(&mut self, request: Request) -> Response {
// A request answers from a buffer's analysis, so any change the client
// has already sent is in effect before it is answered — the order
// contract the loop has always promised. Here is also where a typing
@@ -726,6 +779,11 @@ impl Server {
None => Ok(Value::Null),
}
}),
design_hierarchy::METHOD => to_value(design_hierarchy::snapshot(
&self.workspace,
self.hierarchy_revision,
self.index_is_complete(),
)),
// A rename the engine declines comes back as a request error
// carrying its own sentence, which is what an editor shows in the
// rename box. `prepareRename` declines the same way, so the box
@@ -1378,7 +1436,17 @@ impl Server {
// notifications
// ------------------------------------------------------------------
/// Handle one notification, timing it when `--verbose` asked. A
/// notification has no response, so there is no ordering question here:
/// the line follows the work.
fn notification(&mut self, notification: Notification) {
let Some(started) = self.timer() else { return self.handle_notification(notification) };
let method = notification.method.clone();
self.handle_notification(notification);
self.timing(format!("{method} handled in {}", ms(started)));
}
fn handle_notification(&mut self, notification: Notification) {
let method = notification.method.clone();
// A closing buffer's pending text is dropped *before* the flush, not
// in the `didClose` arm below it: the flush would otherwise analyze
@@ -1403,12 +1471,18 @@ impl Server {
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
let uri = p.text_document.uri;
// Opening a file in a folder the index does not cover
// *widens the scope*, so the whole index is rebuilt; the
// rebuild rides the same bar and the same generation bump
// *widens the scope*, so the folders it added are indexed
// and folded into the index beside what is already there;
// the widen rides the same bar and the same generation bump
// every other rescan trigger does. Opening one the scope
// already covers changes nothing about which files exist,
// and the save path still owns rebuilding.
//
// Only a *pure add* takes the cheap path, and `widen_of` is
// where that is decided: anything else — a scope directory
// that left, which nothing does today — falls back to the
// whole rescan (`docs/features/index-scope/README.md`).
//
// This is the rootless rule from before 2026-08-27,
// generalized: rung 3 is now the default rung with a root
// too, so "did this file widen the scope" is the one test,
@@ -1416,10 +1490,10 @@ impl Server {
// rungs, which an open buffer cannot widen.
let before = self.workspace.scope_dirs();
self.set_document(uri.clone(), p.text_document.text);
if self.workspace.scope_dirs() == before {
self.publish(&uri);
} else {
self.reindex();
match widen_of(&before, &self.workspace.scope_dirs()) {
Widen::Nothing => self.publish(&uri),
Widen::Added(dirs) => self.reindex_widened(dirs),
Widen::Whole => self.reindex(),
}
}
}
@@ -1759,17 +1833,89 @@ impl Server {
self.rescan_wanted = true;
return true;
}
let started = self.timer();
if !self.workspace.update_one(path) {
// No line: nothing was reindexed, and the caller is about to
// rebuild the whole index — which times itself.
return false;
}
self.refresh_code_lenses();
self.hierarchy_index_changed();
self.generation += 1;
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
true
}
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
/// the scope: index those folders and fold them in, leaving every file
/// already indexed exactly as it is.
///
/// Everything after the scan is what a whole rescan does, for the same
/// reasons — the widen changes which names exist, so lenses, the
/// diagnostics generation and every open buffer's publish all move with it.
///
/// **Mid-scan this defers to one whole rescan rather than widening.** A
/// scan already running holds a work list taken from the *old* scope, and
/// folding a widen into it would mean two answers to "which files exist"
/// inside one scan; the follow-up scan the flag asks for reads the
/// persistent store for everything the running scan already parsed, so it
/// is the cheap kind. This is the same flag every other mid-scan trigger
/// sets, and it is what keeps the coalescing rule one rule
/// (`docs/features/scan-interleave/README.md`).
fn reindex_widened(&mut self, added: Vec<std::path::PathBuf>) {
if self.scanning {
self.rescan_wanted = true;
return;
}
let started = self.timer();
if started.is_some() {
// The folders by name: which folder a jump widened into is the one
// thing the file log below it does not say in one line.
let paths: Vec<String> = added.iter().map(|p| p.display().to_string()).collect();
let folders = added.len();
self.timing(format!(
"widen started: {folders} folder{} added: {}",
plural(folders),
paths.join(", ")
));
}
let bar = self.begin_indexing();
let mut scan =
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
let total = scan.total();
// No drain between the files: a widen is a rescan a message asked for,
// and `must_wait` would hold every request queued behind it anyway. It
// is also the point of the round that there is no longer a wait worth
// interleaving — a widen indexes one folder, not the whole scope.
loop {
let step = |workspace: &mut Workspace, watch: &mut dyn FnMut(IndexEvent)| {
workspace.scan_step(&mut scan, watch)
};
if !self.watching(bar.as_ref(), step) {
break;
}
}
let (skipped, cached) = (scan.skipped(), scan.cached());
let warnings = self.workspace.finish_scan(scan);
self.end_indexing(bar, skipped, cached);
self.timed(started, |took| {
format!(
"widen finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
plural(total)
)
});
self.refresh_code_lenses();
self.hierarchy_index_changed();
self.generation += 1;
self.report_scope(warnings);
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
}
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
/// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk,
@@ -1791,6 +1937,7 @@ impl Server {
// the bar names the scan, and everything after it is work done on the
// scan's result.
self.refresh_code_lenses();
self.hierarchy_index_changed();
// Every open buffer's diagnostics are computed against the index, so a
// pulling client's cached answers are all stale from here.
self.generation += 1;
@@ -1839,18 +1986,38 @@ impl Server {
/// they are written through per file — so the next session resumes from
/// them, exactly as it does after any other half-done scan.
fn scan_once(&mut self) -> Vec<String> {
// Before the bar and before the work list is built: resolving the
// scope and walking it is part of what a scan costs, and a number that
// left it out would be the wrong answer to "why was that slow?".
let started = self.timer();
let bar = self.begin_indexing();
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
let interleave = scan.total() > INTERLEAVE_ABOVE;
let total = scan.total();
if started.is_some() {
// Whether it interleaves is said here because it is decided here,
// and because it is the answer to "why did my hover wait?" — a
// scan that does not interleave answers nothing until it is done.
let interleaving = if interleave { ", interleaved" } else { "" };
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
}
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
{
if interleave && self.answer_what_is_waiting(&mut scan) {
// Nothing after this may speak to a client that has gone, the
// timing line included.
return Vec::new();
}
}
let (skipped, cached) = (scan.skipped(), scan.cached());
let warnings = self.workspace.finish_scan(scan);
self.end_indexing(bar, skipped, cached);
self.timed(started, |took| {
format!(
"scan finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
plural(total)
)
});
warnings
}
@@ -1992,6 +2159,19 @@ impl Server {
self.send_request(CodeLensRefresh::METHOD, ());
}
/// Publish a new completed hierarchy revision after any index mutation.
fn hierarchy_index_changed(&mut self) {
self.hierarchy_revision = self.hierarchy_revision.saturating_add(1);
if !self.abilities.hierarchy_view {
return;
}
notify_on(
&self.connection,
design_hierarchy::CHANGED_METHOD,
serde_json::json!({ "revision": self.hierarchy_revision }),
);
}
/// One `$/progress` notification for a token the client already knows.
fn progress(&self, token: ProgressToken, value: WorkDoneProgress) {
progress_on(&self.connection, &token, value);
@@ -2055,10 +2235,15 @@ impl Server {
if self.dirty.is_empty() {
return;
}
let started = self.timer();
let buffers = self.dirty.len();
for (uri, text) in std::mem::take(&mut self.dirty) {
self.set_document(uri.clone(), text);
self.publish(&uri);
}
self.timed(started, |took| {
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
});
}
/// Say once, in the output channel, that a buffer is on the large-file
@@ -2127,12 +2312,82 @@ impl Server {
notify_on(&self.connection, method, params);
}
// ------------------------------------------------------------------
// timing (`--verbose`)
// ------------------------------------------------------------------
/// The clock a timing line reads, started **only** when `--verbose` asked
/// for one.
///
/// `None` is the whole of what verbose-off costs: one branch here, and
/// then no clock read, no `format!` and no notification anywhere below.
/// Every timing site starts with this.
fn timer(&self) -> Option<std::time::Instant> {
self.verbose.then(std::time::Instant::now)
}
/// One timing line for work that was being timed — and nothing at all,
/// closure included, for work that was not.
fn timed(&self, started: Option<std::time::Instant>, line: impl FnOnce(&str) -> String) {
let Some(started) = started else { return };
self.timing(line(&ms(started)));
}
/// One `timing:` line in the client's output channel.
///
/// `MessageType::LOG` and the same `window/logMessage` the per-file index
/// log uses — the channel is already this server's, and the one-word
/// prefix is what lets a reader (or a `grep`) pick these out of it. Sent
/// straight down the writer thread like every other notification, so it
/// cannot block on anything the loop is holding.
fn timing(&self, line: String) {
self.notify(
LogMessage::METHOD,
LogMessageParams { typ: MessageType::LOG, message: format!("timing: {line}") },
);
}
/// One line for a request the order contract makes wait, naming which of
/// [`Server::must_wait`]'s three clauses held it.
///
/// The question this answers is the one a slow-looking editor raises:
/// "was that request slow, or was it never started?". Silent for anything
/// that is not a request — nothing else waits.
fn say_held(&self, message: &Message) {
if !self.verbose {
return;
}
let Message::Request(request) = message else { return };
self.timing(format!(
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
request.method,
self.answering_a_rescan,
self.rescan_wanted,
self.held.len()
));
}
/// The byte offset an LSP position names in an open document.
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
}
}
/// How long ago, in milliseconds — the one unit every timing line is written
/// in, to two decimals so that a sub-millisecond answer is still a number.
fn ms(started: std::time::Instant) -> String {
format!("{:.2} ms", started.elapsed().as_secs_f64() * 1_000.0)
}
/// The `s` a count needs, or nothing. One file is not "1 files".
fn plural(count: usize) -> &'static str {
if count == 1 {
""
} else {
"s"
}
}
// ----------------------------------------------------------------------
// watching an index rebuild
// ----------------------------------------------------------------------
@@ -2391,6 +2646,55 @@ fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect()
}
/// What a `didOpen` did to the index scope, and therefore which of the three
/// answers it is owed.
#[derive(Debug, PartialEq, Eq)]
enum Widen {
/// The scope did not move: the file is in a folder already covered, or the
/// rung in force is one an open buffer cannot widen (a filelist, or the
/// whole-workspace walk). Publish and index nothing.
Nothing,
/// Folders were added and nothing else changed — the cheap path, indexing
/// only what the added folders bring in
/// ([`Server::reindex_widened`]).
Added(Vec<std::path::PathBuf>),
/// Anything else. The whole rescan, which is always a correct answer.
Whole,
}
/// Which of the three [`Widen`] answers a move from `before` to `after` is.
///
/// **The chooser, and it is deliberately narrow**: only a scope that grew and
/// lost nothing takes the incremental path, because that is the only shape
/// whose result is the whole rescan's by construction — a directory that left
/// the scope can take files out of the index, and working out *which* files is
/// the walk the widen exists not to do. Nothing in the server takes a directory
/// out of the folder scope today (`opened_dirs` only grows, and a `didClose`
/// costs no rescan at all), so the third arm is a rule kept rather than a case
/// reached; a future shrink gets a correct answer instead of a subtle one.
///
/// **A directory that subsumes one already in scope is an add** (2026-08-29,
/// `docs/features/index-scope/README.md`). At `scopeDepth: 2` the second file a
/// user opens routinely raises to a *parent* of the directory the first one
/// raised to — opentitan's `hw/ip/aes` then `hw/ip`. That is still a pure add
/// here, because every opened directory is raised on its own and the list keeps
/// them all: the contained directory is in `after` beside the containing one,
/// and nothing was lost. The overlap is not re-read either, because
/// `Workspace::begin_widen`'s work list is diffed **by file against what the
/// index holds** rather than by folder against the old walk.
///
/// Both lists come from `Workspace::scope_dirs`, which sorts and dedups, so
/// equality is set equality and `contains` is over a handful of directories.
fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBuf]) -> Widen {
if before == after {
return Widen::Nothing;
}
if before.iter().any(|dir| !after.contains(dir)) {
return Widen::Whole;
}
Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect())
}
/// The files a burst opened, in the order the client opened them.
///
/// Read off the raw messages rather than off the workspace afterwards,
@@ -2635,8 +2939,12 @@ mod tests {
storage: Option<PathBuf>,
) -> Session {
let (server_end, client) = Connection::memory();
// Verbose off, which is how the server ships: every assertion in
// this module counts the messages a session produces, and the
// timing lines are tested where they are observable as protocol
// traffic — `tests/e2e.rs`, against the real binary and its flag.
let server =
Server::started(server_end, roots, abilities, settings, storage, Vec::new());
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
Session { server, client }
}
@@ -2663,7 +2971,8 @@ mod tests {
for message in on_the_wire {
client.sender.send(message).expect("the client's wire traffic");
}
let server = Server::started(server_end, roots, abilities, settings, None, queued);
let server =
Server::started(server_end, roots, abilities, settings, None, false, queued);
Session { server, client }
}
@@ -3951,7 +4260,16 @@ mod tests {
let tree = Tree::new("scoperescan");
tree.package("rtl/a.sv", "a");
tree.package("include/defs.sv", "defs_pkg");
let scoped = |scope: &str, depth: u32| {
serde_json::json!({
"settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } }
})
};
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
// The shipped depth is 2 since 2026-08-28, which already reaches the
// sibling folder — so the narrow premise this test raises the depth
// *from* is asked for out loud.
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 0));
let uri = session.open(
&tree.path.join("rtl/a.sv"),
"package a;\n localparam K = 1;\n\
@@ -3960,12 +4278,6 @@ mod tests {
let _ = (uri, session.drain());
assert_eq!(indexed(&session, "defs_pkg"), 0, "premise: the sibling folder is out of scope");
let scoped = |scope: &str, depth: u32| {
serde_json::json!({
"settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } }
})
};
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
assert_eq!(session.progress().len(), 5, "create, begin, two reports, end");
assert_eq!(indexed(&session, "defs_pkg"), 1, "one level up reaches the sibling folder");
@@ -5158,6 +5470,103 @@ mod tests {
assert!(session.requests().is_empty(), "silence, on every rescan path");
}
#[test]
fn the_hierarchy_view_gets_a_snapshot_and_one_notification_per_completed_index() {
let tree = Tree::new("hierarchyviewrefresh");
tree.write("sub.sv", "module sub; endmodule\n");
tree.write("top.sv", "module top; sub u (); endmodule\n");
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
let started: Vec<Value> = session
.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(notification)
if notification.method == design_hierarchy::CHANGED_METHOD =>
{
Some(notification.params)
}
_ => None,
})
.collect();
assert_eq!(started, [serde_json::json!({ "revision": 1 })]);
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
assert_eq!(snapshot["revision"], 1);
assert_eq!(snapshot["complete"], true);
assert_eq!(snapshot["modules"].as_array().expect("modules").len(), 2);
tree.write("top.sv", "module top; sub renamed (); endmodule\n");
session.watched(&[tree.path.join("top.sv")]);
let changed: Vec<Value> = session
.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(notification)
if notification.method == design_hierarchy::CHANGED_METHOD =>
{
Some(notification.params)
}
_ => None,
})
.collect();
assert_eq!(changed, [serde_json::json!({ "revision": 2 })]);
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
assert_eq!(snapshot["revision"], 2);
let top = snapshot["modules"]
.as_array()
.expect("modules")
.iter()
.find(|module| module["moduleName"] == "top")
.expect("top");
assert_eq!(top["instances"][0]["instanceName"], "renamed");
}
/// `complete` says "this is the whole workspace", and the window it has to
/// be honest about is the one between a finished scan and a rescan already
/// asked for — where `scanning` alone is false over an index that is about
/// to be rebuilt. Two answers, both pinned here: the flag itself is false,
/// and the request does not reach it at all, because `must_wait` sets a
/// request owed a rescan aside instead of answering it.
#[test]
fn a_snapshot_is_never_answered_complete_while_a_rescan_is_owed() {
let tree = Tree::new("hierarchycomplete");
tree.write("top.sv", "module top; endmodule\n");
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
session.drain();
assert!(session.server.index_is_complete(), "settled: nothing is owed");
assert_eq!(
session.result(design_hierarchy::METHOD, serde_json::json!({}))["complete"],
true
);
session.server.rescan_wanted = true;
assert!(!session.server.scanning, "premise: no scan is running this instant");
assert!(!session.server.index_is_complete(), "but one is owed, so nothing is complete");
let request = Message::Request(Request::new(
RequestId::from(99),
design_hierarchy::METHOD.to_string(),
serde_json::json!({}),
));
assert!(!session.batch(vec![request]));
assert_eq!(session.server.held.len(), 1, "the snapshot waits for the rescan");
assert!(session.answers().is_empty(), "nothing was answered off the stale index");
}
#[test]
fn a_client_without_the_hierarchy_view_gets_no_custom_notifications() {
let tree = Tree::new("nohierarchyviewrefresh");
tree.write("top.sv", "module top; endmodule\n");
let session = Session::wide(vec![tree.path.clone()], false);
assert!(session.drain().into_iter().all(|message| {
!matches!(message, Message::Notification(notification)
if notification.method == design_hierarchy::CHANGED_METHOD)
}));
}
#[test]
fn the_refresh_rides_after_the_indexing_bar_comes_down() {
// The documented order: the bar names the scan, and the refresh is
@@ -7206,6 +7615,138 @@ mod tests {
);
}
#[test]
fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
// The chooser, as a table. Everything but "grew and lost nothing"
// falls back to the whole rescan, which is always a correct answer.
let a = PathBuf::from("/w/a");
let b = PathBuf::from("/w/b");
let c = PathBuf::from("/w/c");
let all = [a.clone(), b.clone(), c.clone()];
assert_eq!(widen_of(&[], &[]), Widen::Nothing, "a scope that never moved");
assert_eq!(
widen_of(&all, &all),
Widen::Nothing,
"and one an open buffer could not widen — a filelist or the wide rung, both empty"
);
assert_eq!(
widen_of(std::slice::from_ref(&a), &[a.clone(), b.clone()]),
Widen::Added(vec![b.clone()]),
"one folder added: only that folder is indexed"
);
assert_eq!(
widen_of(&[], &all),
Widen::Added(all.to_vec()),
"the first open of a session adds every directory it has"
);
assert_eq!(
widen_of(std::slice::from_ref(&b), &[a.clone(), b.clone(), c.clone()]),
Widen::Added(vec![a.clone(), c.clone()]),
"two added around one held: both, and never the held one"
);
// The `scopeDepth: 2` shape `performance_take2.md` §5b measured: the
// newly opened file raises to a directory that *contains* one already
// in scope. The contained directory is still in `after` — every opened
// directory is raised on its own and none of them is ever dropped — so
// this is an add like any other, and the widen's own file diff is what
// stops the overlap being read twice
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
let ip = PathBuf::from("/w");
assert_eq!(
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
Widen::Added(vec![ip]),
"a folder that subsumes the old scope is an add, not a removal"
);
assert_eq!(
widen_of(&[a.clone(), b.clone()], std::slice::from_ref(&a)),
Widen::Whole,
"a directory that left is not an add: the whole rescan settles what went with it"
);
assert_eq!(
widen_of(&[a.clone(), b.clone()], &[a, c]),
Widen::Whole,
"and a swap is a removal too, however many arrived beside it"
);
}
#[test]
fn a_didopen_widen_leaves_the_index_a_whole_rescan_would_have_left() {
// The round's claim, through the real dispatch: two jumps into two new
// folders, each answered by indexing only that folder, and the tables
// that come out are the ones a whole rescan produces — asked by
// running that rescan afterwards and comparing.
let tree = Tree::new("didopenwidenequal");
tree.package("rtl/a.sv", "a");
tree.package("rtl/a2.sv", "a2");
tree.package("lib/b.sv", "b");
tree.package("lib/b2.sv", "b2");
tree.package("tb/c.sv", "c");
let mut session = Session::new(vec![tree.path.clone()], false);
let _ = session
.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
let _ = session
.open(&tree.path.join("lib/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
let _ = session
.open(&tree.path.join("tb/c.sv"), "package c;\n localparam K = 1;\nendpackage\n");
assert_eq!(session.server.workspace.index().files().len(), 5, "all three folders");
assert_eq!(indexed(&session, "b2"), 1, "including files nobody opened");
let widened = session.server.workspace.index().fingerprint();
let words = session.server.workspace.candidates().words("").to_vec();
let includes = session.server.workspace.includes().fingerprint();
session.server.workspace.rebuild_index();
assert_eq!(widened, session.server.workspace.index().fingerprint(), "index");
assert_eq!(words, session.server.workspace.candidates().words(""), "completion words");
assert_eq!(includes, session.server.workspace.includes().fingerprint(), "include graph");
}
#[test]
fn a_widen_asked_for_mid_scan_defers_to_one_whole_rescan_behind_it() {
// A widen answered while a scan runs cannot fold itself in: that scan
// holds a work list taken from the *old* scope, so folding a widen
// into it would make "which files exist" mean two things inside one
// scan. It sets the same `rescan_wanted` flag every other mid-scan
// trigger sets — one more whole scan after this one, coalesced with
// whatever else asked (`docs/features/scan-interleave/README.md`).
//
// Driven directly rather than over the wire, because the wire cannot
// reach it in one step: a widen itself never drains the queue, and the
// startup scan under the folder scope indexes nothing and so never
// interleaves. The reachable route is a `didOpen` answered inside a
// long *whole* rescan, which is this flag and this call.
let tree = Tree::new("widenmidscan");
tree.package("rtl/a.sv", "a");
tree.package("lib/late.sv", "late");
let mut session = Session::new(vec![tree.path.clone()], false);
// The shipped depth is 2 since 2026-08-28, which would have `lib/` in
// scope before the widen this test is about — so the premise names the
// narrow depth rather than assuming it.
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "index": { "scopeDepth": 0 } } } }),
);
let _ = session
.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
assert_eq!(indexed(&session, "a"), 1, "premise: the first folder is in scope");
session.server.scanning = true;
session.server.reindex_widened(vec![tree.path.join("lib")]);
assert!(session.server.rescan_wanted, "the widen was deferred, not run inside the scan");
assert_eq!(indexed(&session, "late"), 0, "and nothing was folded into the running scan");
// What the running scan's own loop then does with the flag.
session.server.scanning = false;
let warnings = session.server.scan_until_settled(true);
assert!(warnings.is_empty(), "{warnings:?}");
assert!(!session.server.rescan_wanted, "one more scan is all it was owed");
// Not indexed, and correctly so: the deferred rescan is a *whole* one
// over the scope as it now stands, and `lib/` entered that scope only
// because a buffer was opened from it — which this test never did.
assert_eq!(indexed(&session, "late"), 0, "the scope itself did not move");
}
#[test]
fn a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol() {
// The whole point: "Add Folder to Workspace" used to change nothing
+71 -11
View File
@@ -41,6 +41,25 @@ pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;
/// `docs/features/large-file-mode/README.md`.
pub const DEFAULT_LARGE_FILE_THRESHOLD: u64 = 4 * 1024 * 1024;
/// `lucisv.index.scopeDepth`'s default: 2 levels above the open file's own
/// folder, clamped at the workspace root that contains it.
///
/// **Changed from 0 on 2026-08-28**, and it is a behaviour change, not a
/// tuning one. At 0 the folder scope indexed the opened file's directory and
/// nothing else, and the measurement that forced the change is in
/// `performance.md` §4: opening `hw/ip/aes/dv/tb/tb.sv` in opentitan gave an
/// index of **one file**, so definition, hover, references, `workspace/symbol`
/// and signature help all answered *nothing* until some later jump widened the
/// scope. A user's first experience of the server was silence.
///
/// Two levels is the smallest raise that turns a `dv/tb` or an `rtl` file into
/// the IP block it belongs to — `hw/ip/aes`, a few hundred files — which is
/// the unit an engineer actually works in. What keeps the cost bounded is
/// everything the scope ladder already has: the size cap, the persistent
/// cache, the interleaved scan and the incremental widen. See
/// `docs/features/index-scope/README.md`.
pub const DEFAULT_SCOPE_DEPTH: u64 = 2;
/// What `lucisv.index.scope` chooses: how wide the workspace walk goes.
///
/// The default is deliberately the narrow one. A large project is the case
@@ -115,9 +134,9 @@ pub struct ClientSettings {
pub index_scope: IndexScope,
/// `lucisv.index.scopeDepth`: how many directory levels above an open
/// file's own folder the folder scope starts, clamped so it never climbs
/// out of the workspace folder containing it. `0` — the default — is the
/// file's own folder. Ignored when `index_scope` is
/// [`IndexScope::Workspace`] or when a filelist defines the scope.
/// out of the workspace folder containing it. `0` is the file's own folder
/// and the default is [`DEFAULT_SCOPE_DEPTH`]. Ignored when `index_scope`
/// is [`IndexScope::Workspace`] or when a filelist defines the scope.
pub index_scope_depth: u64,
/// `lucisv.index.persist`: whether what a scan parsed is written to disk
/// so the next session can skip parsing the files that have not changed.
@@ -156,7 +175,7 @@ impl Default for ClientSettings {
max_file_size: DEFAULT_MAX_FILE_SIZE,
log_files: true,
index_scope: IndexScope::Folder,
index_scope_depth: 0,
index_scope_depth: DEFAULT_SCOPE_DEPTH,
index_persist: true,
index_cache_path: None,
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
@@ -210,7 +229,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// silently costs a user minutes of scanning is the wrong one to
// guess in.
index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(),
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth"))).unwrap_or(0),
// A junk depth leaves the shipped default standing, like every
// other setting here: an unreadable value must never be the reason a
// user's index is narrower than the server promised.
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth")))
.unwrap_or(DEFAULT_SCOPE_DEPTH),
// A wrong-typed `persist` leaves the cache on. The direction that
// costs something is turning it *off* by accident — a user who never
// touched the setting would silently pay for every parse again — and
@@ -345,7 +368,7 @@ mod tests {
"formatOnSave": false,
"index": {
"maxFileSize": 1048576, "logFiles": true,
"scope": "folder", "scopeDepth": 0
"scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH
}
}
})
@@ -380,7 +403,7 @@ mod tests {
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored");
assert!(found.log_files, "and so is its logFiles");
assert_eq!(found.index_scope, IndexScope::Folder, "and its scope");
assert_eq!(found.index_scope_depth, 0, "and its scopeDepth");
assert_eq!(found.index_scope_depth, DEFAULT_SCOPE_DEPTH, "and its scopeDepth");
}
}
@@ -480,11 +503,22 @@ mod tests {
}
#[test]
fn the_scope_depth_is_zero_until_a_client_raises_it() {
assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, 0);
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope_depth, 0);
fn the_scope_depth_is_two_until_a_client_says_otherwise() {
// Two, not zero, since 2026-08-28: `performance.md` §4 measured the
// file's-own-folder default indexing exactly one file in opentitan's
// `dv/tb` layout, so every cross-file answer was empty until some
// later jump widened the scope. See [`DEFAULT_SCOPE_DEPTH`].
assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, DEFAULT_SCOPE_DEPTH);
assert_eq!(
settings(json!({ "lucisv": { "index": {} } })).index_scope_depth,
DEFAULT_SCOPE_DEPTH
);
let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } }));
assert_eq!(raised.index_scope_depth, 3);
// Zero is still exactly what it always was — the file's own folder and
// nothing above it — and asking for it still gets it.
let narrow = settings(json!({ "lucisv": { "index": { "scopeDepth": 0 } } }));
assert_eq!(narrow.index_scope_depth, 0, "an explicit 0 is honoured, not defaulted");
// No upper bound here: the clamp is structural — `state.rs` stops at
// the workspace root — so an absurd number is not wrong, just fully
// clamped.
@@ -492,7 +526,10 @@ mod tests {
assert_eq!(absurd.index_scope_depth, 9999);
for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] {
let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } }));
assert_eq!(found.index_scope_depth, 0, "scopeDepth {bad} must be ignored");
assert_eq!(
found.index_scope_depth, DEFAULT_SCOPE_DEPTH,
"scopeDepth {bad} must be ignored"
);
}
}
@@ -519,6 +556,29 @@ mod tests {
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
}
/// [`vscode_payload`] above is a hand-written copy of what the extension
/// declares, and a copy that drifts proves nothing. The extension's own
/// `package.json` is the thing a user's settings UI reads, so the two
/// defaults that are not "no opinion" are checked against it directly.
#[test]
fn the_extensions_declared_defaults_are_the_ones_this_module_ships() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: Value = serde_json::from_str(&text).expect("valid json");
let properties = &manifest["contributes"]["configuration"]["properties"];
assert_eq!(
properties["lucisv.index.scopeDepth"]["default"],
json!(DEFAULT_SCOPE_DEPTH),
"the settings UI and the server must ship the same scope depth"
);
assert_eq!(
properties["lucisv.index.maxFileSize"]["default"],
json!(DEFAULT_MAX_FILE_SIZE),
"and the same size cap"
);
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
File diff suppressed because it is too large. Load diff
+633 -2
View File
@@ -95,7 +95,17 @@ fn temp_dir(name: &str) -> PathBuf {
/// processes the messages in order and exits on `exit`, so stdout closes and
/// the read terminates on its own.
fn talk(session: &str) -> Vec<serde_json::Value> {
talk_with(&[], session)
}
/// [`talk`] with arguments on the spawn.
///
/// The no-argument spawn above is the contract every editor uses and
/// `smoke.js` drives; this is for the one argument the server takes,
/// `--verbose` (`docs/features/verbose-timing/README.md`).
fn talk_with(args: &[&str], session: &str) -> Vec<serde_json::Value> {
let mut child = server_command()
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -1241,7 +1251,13 @@ fn with_no_workspace_folder_the_open_files_own_directory_is_indexed() {
};
assert_eq!(hits(2), 0, "premise: nothing is indexed before a file is open");
assert_eq!(hits(3), 1, "the neighbour of the open file is indexed");
assert_eq!(hits(4), 0, "but the walk does not descend — this is one directory");
// Changed 2026-08-28 with the shipped `scopeDepth` of 2. A rootless
// session still does not *climb* — there is no workspace root to clamp a
// climb against, so `raised` leaves the buffer's own directory alone — but
// a non-zero depth still asks for a walk rather than a flat read, so the
// subtree under that one directory is now indexed. Bounded by the
// directory the user opened a file from, and no wider.
assert_eq!(hits(4), 1, "the depth asks for a walk of that one directory");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -2008,6 +2024,16 @@ fn cross_file_references_folding_and_highlights_round_trip_over_the_wire() {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":8}}}}}}"#
)),
// `performance.md` §7: documentHighlight answered `null` at every
// opentitan position tried — an instantiated module's name and a port
// connection — while `references` (id 2 above, same position)
// answered. Both are names declared in the *other* file.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":2}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":12}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
@@ -2068,6 +2094,23 @@ fn cross_file_references_folding_and_highlights_round_trip_over_the_wire() {
);
assert!(highlights.iter().all(|h| h["kind"] == 1), "DocumentHighlightKind.Text");
// The two positions `performance.md` reported as answering nothing.
let starts = |id: u32| -> Vec<(u64, u64)> {
response(id)["result"]
.as_array()
.unwrap_or_else(|| panic!("response {id} answered nothing: {:#?}", response(id)))
.iter()
.map(|h| {
(
h["range"]["start"]["line"].as_u64().expect("line"),
h["range"]["start"]["character"].as_u64().expect("character"),
)
})
.collect()
};
assert_eq!(starts(6), vec![(2, 2)], "the instantiated module's name, declared in sub.sv");
assert_eq!(starts(7), vec![(2, 12)], "the `.clk` port name, declared in sub.sv");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -3622,6 +3665,86 @@ fn a_flood_of_requests_and_cancels_is_answered_exactly_once_each() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The same flood, `--verbose` this time: the timing notify shares the
/// writer channel with every response, so this is where a reordering or an
/// interleaving in the byte stream would show up first.
///
/// **What a cancelled request's timing line looks like: none.** `request`
/// (the timing wrapper) is never reached for an id `process_batch` already
/// answered from the cancelled set — cancellation is resolved before
/// `self.request(request)` is called — so a cancelled id contributes no
/// `answered in` line at all. That is deliberate (there is nothing to time:
/// the handler never ran) and this test is what pins it, since neither the
/// feature README nor `tests/e2e.rs` said so before this round's QA pass
/// (`docs/features/verbose-timing/README.md`, QA log 2026-08-29).
#[test]
fn a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing() {
let dir = temp_dir("cancelflood_verbose");
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}}}}}"#
)));
}
}
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_with(&["--verbose"], &session.concat());
// Every id still answered exactly once — a corrupted or reordered byte
// stream would show up here first, as a missing or duplicated answer.
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:#?}");
if answers[0].get("error").is_some() {
honoured += 1;
}
}
let shutdown = messages.iter().find(|m| m["id"] == 9).expect("a shutdown response");
assert!(shutdown.get("error").is_none(), "shutdown succeeded: {messages:#?}");
// And the timing lines agree with what actually ran: one
// `textDocument/formatting answered in` line per request that was NOT
// served from the cancelled set — never one for a cancelled id, which
// never reaches the timed wrapper at all.
let lines = timing_lines(&messages);
let answered_formatting = lines
.iter()
.filter(|l| l.starts_with("timing: textDocument/formatting answered in"))
.count();
let not_cancelled = 20 - honoured;
assert_eq!(
answered_formatting, not_cancelled,
"one timing line per request the handler actually ran, none for a cancelled one: {lines:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
const TYPEDEF_PKG: &str = "\
package e2e_tdp;
typedef enum logic [1:0] { IDLE, RUN } state_t;
@@ -4337,6 +4460,98 @@ fn the_configuration_pull_round_trips_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// index-scope (2026-08-28): the *shipped* `scopeDepth`, over the real wire.
///
/// `performance.md` §4 measured the old default of 0 indexing exactly one file
/// when opening `hw/ip/aes/dv/tb/tb.sv` in opentitan — `dv/tb/` holds only
/// `tb.sv` — so definition, hover, references and `workspace/symbol` all
/// answered nothing until some later jump widened the scope. The default is 2
/// now, and this pins all three rungs of that decision on the same tree: what
/// the shipped depth reaches, that the climb clamps at the workspace root, and
/// that an explicit `0` is still exactly what it always was.
#[test]
fn the_shipped_scope_depth_reaches_the_block_a_file_belongs_to() {
let dir = temp_dir("scopedepthdefault");
let outside = temp_dir("scopedepthoutside");
let package = |path: PathBuf, name: &str| {
std::fs::create_dir_all(path.parent().expect("a parent")).expect("dirs");
std::fs::write(&path, format!("package {name};\n localparam WIDTH = 8;\nendpackage\n"))
.expect("write");
};
// The opentitan shape: a block with its RTL and its testbench two folders
// apart, a *second* block beside it, and a file at the workspace root.
package(dir.join("hw/ip/aes/rtl/aes.sv"), "aes_pkg");
package(dir.join("hw/ip/kmac/rtl/kmac.sv"), "kmac_pkg");
package(dir.join("root.sv"), "root_pkg");
package(outside.join("outside.sv"), "outside_pkg");
let tb = dir.join("hw/ip/aes/dv/tb/tb.sv");
let tb_text = "module tb;\n localparam W = aes_pkg::WIDTH;\nendmodule\n";
std::fs::create_dir_all(tb.parent().expect("a parent")).expect("dirs");
std::fs::write(&tb, tb_text).expect("write");
let root = format!("file://{}", dir.display());
let tb_uri = format!("file://{}", tb.display());
let query = |id: u32, name: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"#
))
};
let depth = |n: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"index":{{"scopeDepth":{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":"{tb_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(tb_text).expect("json")
)),
// Nothing has been widened and no setting has been touched: this is
// what a user gets the moment they open a testbench.
query(2, "aes_pkg"),
query(3, "kmac_pkg"),
// The block, not the world — so the definition in the buffer resolves.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{tb_uri}"}},"position":{{"line":1,"character":27}}}}}}"#
)),
// An explicit 0 is the old behaviour, unchanged: `dv/tb/` alone, which
// holds nothing but the open buffer.
depth(0),
query(5, "aes_pkg"),
// And the climb clamps at the workspace root however high it is asked
// to go — the root's own file is reached, and nothing outside it is.
depth(99),
query(6, "root_pkg"),
query(7, "outside_pkg"),
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 hits = |id: u32| -> usize {
let response = messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"));
response["result"].as_array().map_or(0, |a| a.len())
};
assert_eq!(hits(2), 1, "two levels up from dv/tb is the aes block, rtl and all");
assert_eq!(hits(3), 0, "and stops there: the block beside it is not in scope");
assert_eq!(hits(4), 1, "so the testbench's reference into the RTL resolves at once");
assert_eq!(hits(5), 0, "an explicit 0 is the file's own folder, exactly as before");
assert_eq!(hits(6), 1, "a depth of 99 climbs to the workspace root");
assert_eq!(hits(7), 0, "and no further: nothing outside the root is indexed");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&outside);
}
/// index-scope (2026-08-27): the default folder scope over the real wire.
///
/// What only an e2e test can settle: that the narrowing is what a *client*
@@ -4379,6 +4594,13 @@ fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() {
));
let _ = live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
// `scopeDepth: 0` — the narrowest rung, and the shipped default until
// 2026-08-28. Asked for out loud so this test stays about the *widen*;
// what the shipped depth covers is
// `the_shipped_scope_depth_reaches_the_block_a_file_belongs_to`.
live.send(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scopeDepth":0}}}}}"#,
);
live.send(&open(&top_uri, top_text));
live.send(&definition(2));
@@ -4386,7 +4608,7 @@ fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() {
assert_eq!(
narrow["result"].as_array().map(Vec::len),
Some(0),
"the package is in a sibling folder, which the default scope does not cover: {narrow:#?}"
"the package is in a sibling folder, which depth 0 does not cover: {narrow:#?}"
);
// Opening the other file widens the scope and rebuilds — no save, no
@@ -4921,3 +5143,412 @@ fn a_hover_issued_during_the_initial_scan_is_answered_during_it() {
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A generated many-folder workspace: `folders` directories of `each` files,
/// every one declaring a package named after where it lives.
///
/// The shape the owner's report is about — a project too big to walk, browsed
/// one folder at a time — without depending on any checkout being present.
fn many_folders(name: &str, folders: usize, each: usize) -> PathBuf {
let dir = temp_dir(name);
for folder in 0..folders {
let path = dir.join(format!("blk{folder:02}/rtl"));
std::fs::create_dir_all(&path).expect("folder");
for file in 0..each {
std::fs::write(
path.join(format!("f{file:02}.sv")),
format!(
"package b{folder:02}_f{file:02};\n localparam WIDTH = {file};\nendpackage\n"
),
)
.expect("write");
}
}
dir
}
/// What each indexing bar read, split by where it came from: the files it read
/// off **disk** (`indexing:`), and the open buffers it took from the analysis
/// they already held (`analyzed:`). Paths are shortened to their last three
/// components, which is `<folder>/rtl/<file>` in this fixture.
///
/// The honest wire-level answer to "what did that scan actually do?": the
/// per-file log is `lucisv.index.logFiles`, on by default, and it names one
/// line per file the scan took.
fn work_per_bar(messages: &[serde_json::Value]) -> Vec<(Vec<String>, Vec<String>)> {
let mut bars: Vec<(Vec<String>, Vec<String>)> = Vec::new();
let tail = |path: &str| {
let mut parts: Vec<&str> = path.rsplit('/').take(3).collect();
parts.reverse();
parts.join("/")
};
for message in messages {
let kind = message["params"]["value"]["kind"].as_str();
if message["method"] == "$/progress" && kind == Some("begin") {
bars.push((Vec::new(), Vec::new()));
}
if message["method"] == "window/logMessage" {
let Some(line) = message["params"]["message"].as_str() else { continue };
let Some(bar) = bars.last_mut() else { continue };
if let Some(path) = line.strip_prefix("indexing: ") {
bar.0.push(tail(path));
} else if let Some(path) = line.strip_prefix("analyzed: ") {
bar.1.push(tail(path));
}
}
}
bars
}
#[test]
fn a_jump_into_a_new_folder_indexes_that_folder_and_not_the_ones_before_it() {
// The owner's opentitan report, in miniature and with no opentitan: 24
// folders of 20 files, browsed one jump at a time. Every widening
// `didOpen` must read the folder it opened and **nothing else** — the log
// is what says so, file by file — while the answers stay exactly what the
// whole-rescan widen gave.
let dir = many_folders("widenfolders", 24, 20);
let root = format!("file://{}", dir.display());
let file = |folder: usize, n: usize| dir.join(format!("blk{folder:02}/rtl/f{n:02}.sv"));
let uri = |folder: usize, n: usize| format!("file://{}", file(folder, n).display());
let text = |folder: usize, n: usize| std::fs::read_to_string(file(folder, n)).expect("read");
let open = |folder: usize, n: usize| {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
uri(folder, n),
serde_json::to_string(&text(folder, n)).expect("json")
)
};
// The cursor on `WIDTH` of the reference this file makes into another
// folder's package.
let jump = |id: u32, folder: usize, n: usize| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"b{folder:02}_f{n:02}"}}}}"#
)
};
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":{}}"#),
// `scopeDepth: 0`, asked for out loud: at the shipped depth of 2 the
// first `didOpen` in `blk00/rtl/` would raise to the workspace root
// and index all 24 folders at once, which is a test of the clamp
// rather than of the widen this one is about.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scopeDepth":0}}}}}"#,
),
frame(&open(0, 0)),
frame(&open(1, 0)),
frame(&open(2, 0)),
// A second file in a folder already reached: no bar at all.
frame(&open(2, 5)),
frame(&jump(2, 1, 7)),
frame(&jump(3, 23, 7)),
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 bars = work_per_bar(&messages);
// Five bars: the empty startup scan, the equally empty rescan the
// `scopeDepth` push asks for, then one per widening `didOpen`. The fourth
// `didOpen` is in a folder already covered and asks for none.
assert_eq!(bars.len(), 5, "one bar per widen and no more: {bars:#?}");
assert_eq!(
bars[..2],
[(vec![], vec![]), (vec![], vec![])],
"neither the startup scan nor the settings rescan indexes anything: nothing is open"
);
for (folder, (read, reused)) in bars[2..].iter().enumerate() {
// **The round, on the wire.** Each jump reads the 19 disk files of the
// folder it opened — `f00.sv` there is the buffer, so it is reused
// rather than read — and never the 19, 38 or 57 of the folders reached
// before it, which is what every one of these bars re-read until now.
let mine: Vec<String> = (1..20).map(|n| format!("blk{folder:02}/rtl/f{n:02}.sv")).collect();
assert_eq!(read, &mine, "bar {} read the wrong files", folder + 1);
// And every open buffer is refreshed from the analysis it holds, which
// is what carries an unsaved edit across a widen.
let buffers: Vec<String> = (0..=folder).map(|b| format!("blk{b:02}/rtl/f00.sv")).collect();
assert_eq!(reused, &buffers, "bar {} reused the wrong buffers", folder + 1);
}
// And the answers are the whole-rescan ones: a package in a folder that
// has been jumped into resolves, one in a folder that has not does not.
let reached = messages.iter().find(|m| m["id"] == 2).expect("a symbol response");
assert_eq!(
reached["result"].as_array().map(Vec::len),
Some(1),
"a package in a folder the scope has reached: {reached:#?}"
);
let unreached = messages.iter().find(|m| m["id"] == 3).expect("a symbol response");
assert_eq!(
unreached["result"].as_array().map(Vec::len),
Some(0),
"and scope semantics are unchanged: an unopened folder is still invisible: {unreached:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// `--verbose` — per-operation timing, over the wire
// ----------------------------------------------------------------------
/// Every `timing:` line the server said, in the order it said them.
///
/// They arrive as `window/logMessage` at `MessageType::LOG` (5), which is the
/// channel the per-file index log already uses — a client that shows one shows
/// both. The prefix is the whole of what tells them apart.
fn timing_lines(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.filter(|line| line.starts_with("timing: "))
.map(str::to_string)
.collect()
}
/// A whole session over one small buffer: open it, type in it, ask two
/// questions about it, save it, shut down. Every kind of timing line but the
/// held one comes out of this, and nothing in it takes long enough to make an
/// assertion timing-dependent.
fn timed_session(dir: &Path) -> String {
let file = dir.join("top.sv");
let source = "module top;\n wire a;\n initial a = 1;\nendmodule\n// c\n";
std::fs::write(&file, source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
[
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")
)),
// One keystroke inside the trailing comment: the buffer goes dirty,
// and the request behind it is what flushes it.
frame(&keystroke(&uri, 2, 4, 4)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentSymbol","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
// A save of a file the index already holds: the incremental path, not
// a whole rebuild.
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":10}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat()
}
#[test]
fn the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel() {
let dir = temp_dir("verbose_on");
let messages = talk_with(&["--verbose"], &timed_session(&dir));
let lines = timing_lines(&messages);
assert!(!lines.is_empty(), "`--verbose` must say something: {messages:#?}");
// A line per request, and the wording is the contract: the owner has read
// these for two diagnostic builds, and a `grep timing:` over an output
// channel is how this feature is used.
let answered = |method: &str| {
lines.iter().any(|line| {
line.starts_with(&format!("timing: {method} answered in ")) && line.ends_with(" ms")
})
};
assert!(answered("textDocument/documentSymbol"), "{lines:#?}");
assert!(answered("textDocument/hover"), "{lines:#?}");
// `shutdown` is deliberately absent: `handle_shutdown` answers it in the
// loop, ahead of the dispatch, so it never reaches the timed wrapper.
// Nothing measurable happens there, and a line for it would mean moving
// the handshake through code that has no business timing it.
assert!(!answered("shutdown"), "{lines:#?}");
// A line per notification, in the same shape with the other verb.
assert!(
lines.iter().any(|line| {
line.starts_with("timing: textDocument/didOpen handled in ") && line.ends_with(" ms")
}),
"{lines:#?}"
);
// And the scan lifecycle, both ends of it. This session's workspace is one
// file, so the counts are the small ones — what is pinned is the wording
// and that both ends arrive.
assert!(lines.iter().any(|line| line.starts_with("timing: scan started: ")), "{lines:#?}");
assert!(
lines.iter().any(|line| {
line.starts_with("timing: scan finished: ")
&& line.contains(" skipped, ")
&& line.contains(" from cache) in ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// And the widen lifecycle, which this session reaches by opening a file:
// the folder it added is named, because "which folder did that jump cost
// me?" is the question the line exists to answer
// (`docs/features/index-scope/README.md`).
assert!(
lines.iter().any(|line| {
line.starts_with("timing: widen started: 1 folder added: ")
&& line.ends_with(&dir.display().to_string())
}),
"{lines:#?}"
);
assert!(
lines.iter().any(|line| {
line.starts_with("timing: widen finished: ")
&& line.contains(" from cache) in ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// The two lines that name work nobody asked for by message: the flush of
// what was typed, and the one-file reindex a save costs.
assert!(
lines.iter().any(|line| {
line.starts_with("timing: flush of 1 dirty buffer took ") && line.ends_with(" ms")
}),
"{lines:#?}"
);
assert!(
lines.iter().any(|line| {
line.starts_with(&format!("timing: reindex_one({}", dir.join("top.sv").display()))
&& line.contains(") took ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// The stated ordering: a request's timing line goes out **before** the
// response it describes. Nothing keys off that — a `window/logMessage`
// carries no id — but it is the contract this round wrote down, and the
// only way to notice it change is to pin it.
let line_at = messages
.iter()
.position(|m| {
m["params"]["message"]
.as_str()
.is_some_and(|line| line.starts_with("timing: textDocument/hover answered in "))
})
.expect("the hover's timing line");
let response_at = messages.iter().position(|m| m["id"] == 3).expect("the hover's response");
assert!(
line_at < response_at,
"the line describes the response that follows it: {messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn without_the_flag_not_one_timing_line_is_ever_sent() {
// The other half, and the one that matters: the shipped spawn — no
// arguments, which is what `smoke.js` and every editor use — must be
// byte-for-byte as quiet as it was before this feature existed.
let dir = temp_dir("verbose_off");
let messages = talk(&timed_session(&dir));
assert_eq!(timing_lines(&messages), Vec::<String>::new(), "{messages:#?}");
// And it is the same session, really answered: a server that failed to
// start would also say nothing.
assert!(messages.iter().any(|m| m["id"] == 2), "the symbols were answered: {messages:#?}");
assert!(messages.iter().any(|m| m["id"] == 9), "and the shutdown: {messages:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_request_queued_behind_a_rescan_says_it_was_held() {
// The line the owner asked for by name, and the one a "why is my editor
// slow?" session is about: the request was not slow, it had not started.
//
// Driven through the real mid-scan machinery: a filelist of 100 files is
// the startup scan's work list — over `INTERLEAVE_ABOVE`, so the scan
// answers messages between its files — and the whole session is already on
// the wire when it begins. The settings push it drains asks for a rescan,
// which mid-scan is the `rescan_wanted` flag; every request behind it is
// owed that rescan's effect, so it waits. See
// `docs/features/scan-interleave/README.md`.
let dir = temp_dir("verbose_held");
let files = 100usize;
let mut list = String::new();
for n in 0..files {
let name = format!("m{n}.sv");
std::fs::write(dir.join(&name), generated_module(&format!("m{n}"), 200)).expect("write");
list.push_str(&format!("{name}\n"));
}
std::fs::write(dir.join("files.f"), &list).expect("write");
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write");
let root = format!("file://{}", dir.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":{}}"#),
// Changes which files exist, so it asks for a rebuild — the one thing
// a request behind it must not be answered ahead of.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"exclude":["no-such-directory"]}}}}"#,
),
frame(r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"m7"}}"#),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk_with(&["--verbose"], &session);
let lines = timing_lines(&messages);
let held: Vec<&String> = lines.iter().filter(|line| line.contains(" HELD ")).collect();
assert!(
held.iter().any(|line| {
line.starts_with("timing: workspace/symbol HELD behind a rescan (answering=")
&& line.contains(", wanted=")
&& line.contains(", already held=")
}),
"the symbol request must say it waited: {lines:#?}"
);
// Held is not dropped: the order contract answers it once the rescan it
// was queued behind has run.
let answered = messages.iter().find(|m| m["id"] == 2).expect("the symbol response");
assert!(answered["error"].is_null(), "{answered:#?}");
assert!(
lines.iter().any(|line| line.starts_with("timing: workspace/symbol answered in ")),
"and it is timed like any other request: {lines:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_argument_the_server_does_not_take_is_refused_rather_than_ignored() {
// The spawn contract's new edge: no arguments and `--verbose` start a
// server, anything else exits 2 with one line on stderr. A client that
// misspelled the flag learns it here rather than wondering for a whole
// session why nothing is logged.
let refused = server_command()
.args(["--verbos"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("the server binary starts");
assert_eq!(refused.status.code(), Some(2), "{refused:?}");
let said = String::from_utf8_lossy(&refused.stderr);
assert!(said.contains("unknown option: --verbos"), "{said}");
assert!(said.contains("usage: lucisv-server [--verbose]"), "{said}");
assert!(refused.stdout.is_empty(), "nothing LSP-shaped on stdout: {refused:?}");
}
+62
View File
@@ -46,6 +46,30 @@ impl LineIndex {
(line as u32, offset - self.line_starts[line - 1] + 1)
}
/// The **0-based** line and **UTF-16** column of a byte offset — the units
/// a language-server `Position` counts in, as opposed to
/// [`line_col`](Self::line_col)'s 1-based bytes. `text` must be the text
/// this index was built from.
///
/// An offset inside a multi-byte character is floored to that character's
/// start, and the `\r` of a CRLF line ending is not part of its line's
/// content. It lives here, beside the table it reads, because two callers
/// need the same answer: a server converting a span for the wire, and the
/// semantic index recording a declaration's position so no one has to.
pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32) {
let mut floored = (offset as usize).min(text.len());
while floored > 0 && !text.is_char_boundary(floored) {
floored -= 1;
}
let (line, _) = self.line_col(floored as u32);
let start = self.line_range(line).map_or(0, |r| r.start) as usize;
let slice = text.get(start..floored).unwrap_or("");
// LSP line content excludes the whole `\r\n`; this index keeps the
// `\r` as an ordinary byte of its line, so drop it here.
let slice = slice.strip_suffix('\r').unwrap_or(slice);
(line - 1, utf16_len(slice))
}
/// The byte offset of a 1-based line and column, or `None` if the text
/// has no such line. A column past the end of its line is clamped to the
/// line's end, so the result never lands on another line.
@@ -77,6 +101,17 @@ impl LineIndex {
}
}
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
///
/// ASCII is answered by the length, which is what source text almost always
/// is; the decoding loop is for the rest.
fn utf16_len(s: &str) -> u32 {
if s.is_ascii() {
return s.len() as u32;
}
s.chars().map(|c| c.len_utf16() as u32).sum()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -141,6 +176,33 @@ mod tests {
}
}
#[test]
fn utf16_positions_are_zero_based_and_count_code_units() {
let src = "module m;\n// 🎉 é\nendmodule";
let idx = LineIndex::new(src);
assert_eq!(idx.utf16_position(src, 0), (0, 0));
assert_eq!(idx.utf16_position(src, 7), (0, 7));
assert_eq!(idx.utf16_position(src, 10), (1, 0));
let party = src.find('🎉').unwrap() as u32;
assert_eq!(idx.utf16_position(src, party), (1, 3));
// Four UTF-8 bytes, two UTF-16 units — the surrogate pair.
assert_eq!(idx.utf16_position(src, party + 4), (1, 5));
// An offset inside the pair floors to its start.
for inside in 1..4 {
assert_eq!(idx.utf16_position(src, party + inside), (1, 3));
}
assert_eq!(idx.utf16_position(src, src.len() as u32 + 99), (2, 9));
}
#[test]
fn a_crlf_is_not_part_of_its_lines_utf16_content() {
let src = "ab\r\ncd\r\n";
let idx = LineIndex::new(src);
assert_eq!(idx.utf16_position(src, 2), (0, 2), "at the `\\r`");
assert_eq!(idx.utf16_position(src, 3), (0, 2), "at the `\\n`, past the `\\r`");
assert_eq!(idx.utf16_position(src, 4), (1, 0));
}
#[test]
fn out_of_range_positions_are_clamped() {
let src = "abc\nde";
+5 -3
View File
@@ -40,10 +40,12 @@ pub use instantiate::{
PlanPort, Site,
};
pub use ports::{
add_port, may_have_port_action, port_actions, propagate_ports, remove_port, ModuleRef,
PortAction,
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
propagate_ports, remove_port, ModuleRef, PortAction,
};
pub use rename::{
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
};
pub use rename::{prepare_rename, rename, RenameTarget};
use std::path::PathBuf;
+52 -11
View File
@@ -155,29 +155,70 @@ pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Ve
/// microseconds. It never says `false` where a refactoring would have
/// succeeded: every one of the three starts by locating exactly one of these
/// three constructs.
///
/// Exactly [`port_action_modules`] asked for emptiness — one walk, two
/// readers, so the gate and the fan-out cannot come to disagree about which
/// positions carry an action.
pub fn may_have_port_action(text: &str, offset: u32) -> bool {
!port_action_modules(text, offset).is_empty()
}
/// Every module name a port refactoring at this position could act on: the
/// module an instantiation under the cursor names, or the module whose port
/// the cursor sits on.
///
/// [`may_have_port_action`]'s own walk, saying *which* module it found rather
/// than only that it found one — which is what lets a server hand
/// [`port_actions`] the handful of files that module fans out to instead of
/// the whole workspace. Empty for exactly the positions the gate refuses.
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
let (tree, _) = parse_source_tolerant(text);
let mut instantiations = Vec::new();
collect_instantiations(&tree.items, &mut instantiations);
let at_instantiation = instantiations.iter().any(|instantiation| {
instantiation.module_span.contains(offset)
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
});
if at_instantiation {
return true;
let named: Vec<String> = instantiations
.iter()
.filter(|instantiation| {
instantiation.module_span.contains(offset)
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
})
.map(|instantiation| instantiation.module.clone())
.collect();
if !named.is_empty() {
return named;
}
let mut module = None;
module_at(&tree.items, offset, &mut module);
let Some((module, _)) = module.and_then(|name| find_module(&tree, &name)) else {
return false;
let Some((name, (module, _))) =
module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?)))
else {
return Vec::new();
};
if declared_ports(module).iter().any(|port| port.span.contains(offset)) {
return true;
return vec![name];
}
module.items.iter().any(|item| match &item.kind {
let on_body_declaration = module.items.iter().any(|item| match &item.kind {
ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)),
_ => false,
})
});
match on_body_declaration {
true => vec![name],
false => Vec::new(),
}
}
/// The module whose declaration covers this offset — what
/// `ModuleRef::At { file, offset }` will resolve to.
///
/// The fan-out question for the *command* path, which takes a position
/// anywhere in a module rather than on one of its ports: `lucisv.addPort` with
/// a `Position` names the module the cursor is inside, and a server working
/// out which files that refactoring needs has to name it the same way
/// `locate_module` will.
pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
let (tree, _) = parse_source_tolerant(text);
let mut module = None;
module_at(&tree.items, offset, &mut module);
module
}
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
+308 -16
View File
@@ -15,7 +15,7 @@ use vlog_parser::token::{is_keyword, TokenKind};
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
use vlog_semantic::{
analyze, resolve_external, Def, ExternalResolutions, ExternalTarget, FileId, ReferenceId,
Resolution, Semantics, SymbolId, WorkspaceIndex,
Resolution, Semantics, Symbol, SymbolId, WorkspaceIndex,
};
use crate::{check, RefactorEdit, TextEdit};
@@ -44,6 +44,93 @@ pub fn prepare_rename(
Ok(RenameTarget { range: target.cursor, name: target.name })
}
/// [`prepare_rename`] answered from one buffer's finished analysis and the
/// workspace index, reading no file at all.
///
/// `textDocument/prepareRename` fires the instant the rename key is pressed,
/// and its whole answer — the identifier's range and its placeholder — is in
/// the buffer already. Answering it through [`prepare_rename`] meant reading,
/// parsing and indexing every in-scope file first: 2.5–3.0 s on OpenTitan, on
/// a keypress that has committed to nothing, with a single-threaded server
/// answering nothing else meanwhile.
///
/// Every refusal [`prepare_rename`] can reach without the *declaring file's*
/// own text is reached here too, in the same words. The ones that need that
/// text are deferred to [`rename`], which reads it — LSP allows an optimistic
/// `prepareRename` whose rename then refuses, and never the other way round.
/// The refusal-by-refusal table is in `docs/features/refactor-rename/README.md`.
pub fn prepare_rename_here(
semantics: &Semantics,
external: &ExternalResolutions,
index: &WorkspaceIndex,
offset: u32,
) -> Result<RenameTarget, String> {
let found =
semantics.reference_id_at(offset).and_then(|id| Some((id, semantics.reference(id)?)));
let Some((id, reference)) = found else {
// The cursor is on a declaration, or on nothing at all.
let here = semantics.symbol_at(offset).and_then(|symbol| semantics.symbol(symbol));
let Some(declaration) = here else { return Err(NOTHING_HERE.to_string()) };
renameable_here(semantics, index, declaration)?;
return Ok(RenameTarget { range: declaration.name_span, name: declaration.name.clone() });
};
let cursor = reference.name_span;
match &reference.resolution {
Resolution::Resolved(symbol) => {
let Some(declaration) = semantics.symbol(*symbol) else {
return Err(NOTHING_HERE.to_string());
};
renameable_here(semantics, index, declaration)?;
Ok(RenameTarget { range: cursor, name: declaration.name.clone() })
}
Resolution::NotFound => Err(unresolved(&reference.name)),
Resolution::InheritedCandidate { base, .. } => Err(from_base(&reference.name, base)),
// The overlay is `resolve_external` against this very index, which is
// the same call `Scope::declaration_across_files` makes — so which
// declaration the use names, and whether several do, is settled here.
// What is *not* settled is anything about that declaration's own file.
Resolution::ExternalCandidate { .. } => match external.get(id) {
Some(ExternalTarget::Resolved(_)) => {
Ok(RenameTarget { range: cursor, name: reference.name.clone() })
}
Some(ExternalTarget::Ambiguous(_)) => Err(ambiguous(&reference.name)),
_ => Err(declared_outside(&reference.name)),
},
}
}
/// The two refusals [`Scope::declaration`] applies to a declaration written in
/// the file the request named, asked of that buffer and the index.
fn renameable_here(
semantics: &Semantics,
index: &WorkspaceIndex,
declaration: &Symbol,
) -> Result<(), String> {
if declaration.name_span.is_empty() {
return Err(unspelled(&declaration.name));
}
if declaration.scope == semantics.file_scope() && index.units(&declaration.name).len() > 1 {
return Err(ambiguous(&declaration.name));
}
Ok(())
}
/// The identifier a rename at `offset` would act on, read from one buffer's
/// analysis alone: the name, with no opinion on whether it may be renamed.
///
/// What the server needs to ask the index for the rename's fan-out. Every
/// refusal stays with [`rename`], which is the call that sees the files — a
/// second opinion here could only disagree with it.
pub fn rename_name_at(semantics: &Semantics, offset: u32) -> Option<String> {
match semantics.reference_id_at(offset).and_then(|id| semantics.reference(id)) {
Some(reference) => Some(reference.name.clone()),
None => semantics
.symbol_at(offset)
.and_then(|symbol| semantics.symbol(symbol))
.map(|declaration| declaration.name.clone()),
}
}
/// Rename the symbol at `offset` in `file` to `new_name`, across every file in
/// `files`.
///
@@ -230,12 +317,10 @@ impl<'a> Scope<'a> {
let (name, cursor) = (reference.name.clone(), reference.name_span);
match &reference.resolution {
Resolution::Resolved(symbol) => Found::Here(*symbol, cursor),
Resolution::NotFound => return Err(format!(
"`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean."
)),
Resolution::InheritedCandidate { base, .. } => return Err(format!(
"`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess."
)),
Resolution::NotFound => return Err(unresolved(&name)),
Resolution::InheritedCandidate { base, .. } => {
return Err(from_base(&name, base))
}
Resolution::ExternalCandidate { .. } => {
Found::Elsewhere(name, cursor, analysis.external.get(id).cloned())
}
@@ -282,9 +367,7 @@ impl<'a> Scope<'a> {
)
};
if name_span.is_empty() {
return Err(format!(
"lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it."
));
return Err(unspelled(&name));
}
if at_file_scope && self.index.units(&name).len() > 1 {
return Err(ambiguous(&name));
@@ -302,11 +385,7 @@ impl<'a> Scope<'a> {
let def = match target {
Some(ExternalTarget::Resolved(def)) => def,
Some(ExternalTarget::Ambiguous(_)) => return Err(ambiguous(name)),
_ => {
return Err(format!(
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
))
}
_ => return Err(declared_outside(name)),
};
let Some(file) = self.index.path(def.file).and_then(|p| self.index_of(p)) else {
return Err(format!("`{name}`'s declaring file is not in scope."));
@@ -631,12 +710,41 @@ pub(crate) struct ArgumentSite {
const NOTHING_HERE: &str = "there is no symbol to rename at this position.";
// The refusal sentences, each written once. Two callers reach four of them
// now: the whole-workspace `Scope::locate` and the buffer-and-index
// `prepare_rename_here`, which must refuse in exactly the same words or the
// user gets two different explanations for one situation.
fn ambiguous(name: &str) -> String {
format!(
"`{name}` is declared in more than one indexed file; lucisv will not guess which declaration this rename means."
)
}
fn unresolved(name: &str) -> String {
format!(
"`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean."
)
}
fn from_base(name: &str, base: &str) -> String {
format!(
"`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess."
)
}
fn declared_outside(name: &str) -> String {
format!(
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
)
}
fn unspelled(name: &str) -> String {
format!(
"lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it."
)
}
/// Why an identifier spelling the name is not a reference lucisv can edit,
/// read off its neighbours in the token stream. Naming the actual construct
/// is the difference between a warning the user can act on and one they have
@@ -679,7 +787,12 @@ pub(crate) fn display(path: &Path) -> String {
/// True when `needle` occurs in `haystack` as a whole identifier — the test
/// macro text and the verification pass's file filter get, where there is no
/// token stream to consult (or where the token is opaque).
pub(crate) fn contains_word(haystack: &str, needle: &str) -> bool {
///
/// Public because the server asks the same question of a `` `define`` body it
/// reads out of the index, to put that macro's file in a rename's fan-out:
/// [`Scope::define_sites`] decides with this function, so the fan-out must
/// decide with it too or the two disagree about which files carry a warning.
pub fn contains_word(haystack: &str, needle: &str) -> bool {
if needle.is_empty() {
return false;
}
@@ -719,6 +832,185 @@ mod tests {
assert!(check_new_name("a ").is_err(), "trailing space");
}
/// A `(path, text)` list from `(name, text)` pairs, the shape both entry
/// points take.
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (PathBuf::from(name), (*text).to_string())).collect()
}
/// [`prepare_rename_here`] and [`prepare_rename`] asked the same question
/// at **every byte** of one file, with the parity contract asserted at
/// each: a refusal is never invented and never reworded, and an answer is
/// never a different answer. The one asymmetry the contract allows is the
/// deferral — the cheap path saying yes where the whole-workspace path
/// refuses for a reason only the declaring file's own text carries.
///
/// Returns how many offsets were deferrals, so a test can assert it found
/// the case it was built to find.
fn parity_at_every_offset(files: &[(&str, &str)], file: &str) -> usize {
let sources = workspace(files);
let path = PathBuf::from(file);
let text = sources
.iter()
.find(|(p, _)| *p == path)
.map(|(_, text)| text.clone())
.expect("the file is in the workspace");
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
let semantics = analyze(&parse_source_tolerant(&text).0, &text);
let external = resolve_external(&semantics, &index);
let mut deferred = 0usize;
for offset in 0..=text.len() as u32 {
let whole = prepare_rename(&sources, &path, offset);
let here = prepare_rename_here(&semantics, &external, &index, offset);
match (&whole, &here) {
(Ok(whole), Ok(here)) => {
assert_eq!(whole, here, "at byte {offset} of {file}");
}
(Err(whole), Err(here)) => {
assert_eq!(whole, here, "refusal reworded at byte {offset} of {file}");
}
// Allowed, and only in this direction: the buffer said yes,
// the workspace refused for something only the declaring
// file's own analysis knows. `rename` still delivers it.
(Err(_), Ok(_)) => deferred += 1,
(Ok(whole), Err(here)) => panic!(
"a refusal was invented at byte {offset} of {file}: the workspace answered {whole:?}, the buffer refused with {here:?}"
),
}
}
deferred
}
const SUB: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n";
const TOP: &str = "module top;\n logic c, d;\n sub #(.W(2)) u_sub (.clk(c), .q(d));\n sub u_two (.clk(c), .q(d));\nendmodule\n";
const PKG: &str =
"package cfg_pkg;\n parameter int DEPTH = 4;\n typedef logic [1:0] mode_t;\nendpackage\n";
const USER: &str = "module user;\n import cfg_pkg::*;\n cfg_pkg::mode_t m;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n";
#[test]
fn the_buffer_answers_a_prepare_exactly_as_the_workspace_does() {
let files = [("sub.sv", SUB), ("top.sv", TOP)];
parity_at_every_offset(&files, "top.sv");
parity_at_every_offset(&files, "sub.sv");
}
#[test]
fn a_prepare_over_packages_and_qualified_names_keeps_parity() {
let files = [("pkg.sv", PKG), ("user.sv", USER)];
parity_at_every_offset(&files, "user.sv");
parity_at_every_offset(&files, "pkg.sv");
}
#[test]
fn a_prepare_keeps_parity_where_the_workspace_declares_a_name_twice() {
// Two modules called `sub`, so every route to that declaration must
// refuse — from the use in `top.sv`, and from either declaration.
let files =
[("a.sv", SUB), ("b.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)];
parity_at_every_offset(&files, "top.sv");
parity_at_every_offset(&files, "a.sv");
let sources = workspace(&files);
let path = PathBuf::from("top.sv");
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
let semantics = analyze(&parse_source_tolerant(TOP).0, TOP);
let external = resolve_external(&semantics, &index);
let at = TOP.find("sub #").expect("the instantiation") as u32;
let refusal =
prepare_rename_here(&semantics, &external, &index, at).expect_err("declared twice");
assert_eq!(refusal, ambiguous("sub"), "the index-shaped refusal, in its own words");
assert_eq!(refusal, prepare_rename(&sources, &path, at).expect_err("declared twice"));
}
#[test]
fn a_prepare_keeps_parity_where_nothing_resolves() {
// `missing` is instantiated and declared nowhere; `base_t` comes from
// a base class this workspace does not hold.
const STRAY: &str = "class kid extends absent_base;\n function void go();\n inherited_thing = 1;\n endfunction\nendclass\nmodule holder;\n missing u_missing (.a(b));\nendmodule\n";
parity_at_every_offset(&[("stray.sv", STRAY), ("sub.sv", SUB)], "stray.sv");
}
#[test]
fn a_prepare_keeps_parity_through_generate_blocks_and_macros() {
const GEN: &str = "`define BUMP(x) x + 1\n`define WIDTH 8\nmodule gen_holder;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_lane (.clk(1'b0), .q());\n end\n endgenerate\n wire [`WIDTH-1:0] w;\n assign w = `BUMP(sub);\nendmodule\n";
parity_at_every_offset(&[("gen.sv", GEN), ("sub.sv", SUB)], "gen.sv");
}
#[test]
fn a_prepare_on_an_unparseable_buffer_keeps_parity() {
const BROKEN: &str =
"module broken (input logic clk;\n wire a\n assign a = clk\nendmodule\n";
parity_at_every_offset(&[("broken.sv", BROKEN), ("sub.sv", SUB)], "broken.sv");
}
// ------------------------------------------------------------------
// QA, 2026-08-28: prepare parity fuzz beyond the dev's six buffers
// ------------------------------------------------------------------
//
// Same contract, hostile shapes the dev's suite didn't try: a valid head
// followed by garbage (as opposed to garbage throughout), CRLF line
// endings (byte offsets a naive line-based tool would get wrong), and
// multi-byte UTF-8 text sitting before the identifiers being probed.
#[test]
fn a_prepare_keeps_parity_with_a_valid_head_and_an_unparseable_tail() {
const HEAD_THEN_GARBAGE: &str = "module ok_head;\n wire a;\n assign a = 1'b0;\nendmodule\n\n)}]224$@#(garbage tail not even lexable as verilog{{{\n";
parity_at_every_offset(&[("tail.sv", HEAD_THEN_GARBAGE), ("sub.sv", SUB)], "tail.sv");
}
#[test]
fn a_prepare_keeps_parity_over_crlf_line_endings() {
const CRLF: &str = "module crlf_mod;\r\n wire local_net;\r\n sub u_inst (.clk(1'b0), .q());\r\n assign local_net = 1'b0;\r\nendmodule\r\n";
parity_at_every_offset(&[("crlf.sv", CRLF), ("sub.sv", SUB)], "crlf.sv");
}
#[test]
fn a_prepare_keeps_parity_with_multi_byte_text_before_the_identifiers() {
const MULTI_BYTE: &str = "// \u{00e9}\u{00e9} \u{1f389} a comment with accents and an emoji before anything else\nmodule multi_byte_mod;\n // \u{4e2d}\u{6587}\u{6ce8}\u{91ca} more non-ascii, mid-file\n wire local_net;\n sub u_inst (.clk(1'b0), .q());\n assign local_net = 1'b0;\nendmodule\n";
parity_at_every_offset(&[("multibyte.sv", MULTI_BYTE), ("sub.sv", SUB)], "multibyte.sv");
}
#[test]
fn a_prepare_keeps_parity_over_a_macro_heavy_buffer() {
const MACRO_HEAVY: &str = "`define WIDTH 8\n`define BUMP(x) x = x + 1\n`ifdef NEVER_DEFINED\n `define shadow_sub sub\n`else\n module macro_heavy;\n wire [`WIDTH-1:0] w;\n sub u_real (.clk(1'b0), .q());\n initial `BUMP(w);\n endmodule\n`endif\n";
parity_at_every_offset(&[("macro.sv", MACRO_HEAVY), ("sub.sv", SUB)], "macro.sv");
}
#[test]
fn the_cheap_prepare_reads_nothing_but_the_buffer_and_the_index() {
// The declaring file is *not* in the index, so nothing about it can be
// consulted — and the answer is still the refusal that says so.
let sources = workspace(&[("top.sv", TOP)]);
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
let semantics = analyze(&parse_source_tolerant(TOP).0, TOP);
let external = resolve_external(&semantics, &index);
let at = TOP.find("sub #").expect("the instantiation") as u32;
assert_eq!(
prepare_rename_here(&semantics, &external, &index, at).expect_err("not indexed"),
declared_outside("sub")
);
}
#[test]
fn the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on() {
let files = [("sub.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)];
let sources = workspace(&files);
for (path, text) in &sources {
let semantics = analyze(&parse_source_tolerant(text).0, text);
for offset in 0..=text.len() as u32 {
let Ok(target) = prepare_rename(&sources, path, offset) else { continue };
assert_eq!(
rename_name_at(&semantics, offset).as_deref(),
Some(target.name.as_str()),
"at byte {offset} of {}",
path.display()
);
}
}
}
#[test]
fn whole_word_search_ignores_substrings() {
assert!(contains_word("a + WIDTH - 1", "WIDTH"));
+35
View File
@@ -642,6 +642,41 @@ fn the_cheap_pre_check_says_yes_exactly_where_an_action_could_be_offered() {
assert!(may_have_port_action(non_ansi, at(non_ansi, "input a") + 6), "a non-ANSI declaration");
}
#[test]
fn the_pre_check_names_the_module_whose_files_the_action_will_need() {
use vlog_refactor::{may_have_port_action, port_action_modules};
let text = "module sub (\n input a,\n input b\n);\n wire c;\n assign c = a;\n other u1 (.x(c));\nendmodule\n";
// On a port of `sub`, the module whose signature would change; on the
// instantiation, the module instantiated — never the one it is written in.
assert_eq!(port_action_modules(text, at(text, "input b") + 6), ["sub"]);
assert_eq!(port_action_modules(text, at(text, "u1")), ["other"]);
assert_eq!(port_action_modules(text, at(text, "other")), ["other"]);
assert!(port_action_modules(text, at(text, "assign")).is_empty());
let non_ansi = "module sub (a);\n input a;\nendmodule\n";
assert_eq!(port_action_modules(non_ansi, at(non_ansi, "input a") + 6), ["sub"]);
// The gate is this walk asked for emptiness, at every byte of the file.
for offset in 0..text.len() as u32 {
assert_eq!(
may_have_port_action(text, offset),
!port_action_modules(text, offset).is_empty(),
"at byte {offset}"
);
}
}
#[test]
fn the_enclosing_module_is_the_one_a_position_would_add_a_port_to() {
use vlog_refactor::enclosing_module;
let text = "module sub (input a);\n wire c;\nendmodule\n\nmodule top;\n sub u1 (.a(c));\nendmodule\n";
// A position `lucisv.addPort` would take: inside the module, nowhere near
// a port element — which is exactly where `port_action_modules` is empty.
assert_eq!(enclosing_module(text, at(text, "wire c")).as_deref(), Some("sub"));
assert_eq!(enclosing_module(text, at(text, "sub u1")).as_deref(), Some("top"));
assert_eq!(enclosing_module(text, at(text, "\n\nmodule top") + 1), None, "between modules");
}
// ----------------------------------------------------------------------
// what the preprocessor owns
// ----------------------------------------------------------------------
+68 -7
View File
@@ -20,13 +20,16 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use crate::model::SymbolKind;
use crate::workspace::{Decl, DeclLines, DeclSite, FileFacts, ReferenceFact, SiteFact};
use crate::workspace::{
Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, ReferenceFact,
SiteFact, Utf16Pos, Utf16Range,
};
/// The version of the encoding below. Bump it on **any** change to what a
/// record holds or to how it is written: a store stamped with another number
/// is discarded whole, which is the only way a reader can be sure it is not
/// reading last month's field order as this month's.
pub const FACTS_FORMAT: u32 = 4;
pub const FACTS_FORMAT: u32 = 5;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
@@ -47,6 +50,10 @@ impl FileFacts {
out.tag("U", self.units.len());
for decl in &self.units {
out.decl(decl);
// Only the `U` group carries client positions, so the `M` group
// below stays exactly as wide as it was — see
// `vlog_semantic::DeclPositions` for why members are left out.
out.positions(&decl.lines.positions.unwrap_or_default());
}
out.tag("M", self.members.len());
for (unit, decl) in &self.members {
@@ -58,6 +65,14 @@ impl FileFacts {
out.text(module);
out.site(&site.owner);
out.range(site.site_span);
out.num(site.instances.len() as u32);
for instance in &site.instances {
out.text(&instance.name);
out.range(instance.name_span);
out.range(instance.span);
out.utf16(instance.name_positions);
out.utf16(instance.positions);
}
}
out.tag("S", self.subclasses.len());
for (base, subclass) in &self.subclasses {
@@ -89,7 +104,9 @@ impl FileFacts {
}
let mut units = Vec::new();
for _ in 0..input.tag("U")? {
units.push(input.decl()?);
let mut decl = input.decl()?;
decl.lines.positions = Some(input.positions()?);
units.push(decl);
}
let mut members = Vec::new();
for _ in 0..input.tag("M")? {
@@ -99,7 +116,18 @@ impl FileFacts {
for _ in 0..input.tag("I")? {
let module = input.text()?;
let owner = input.site()?;
instantiations.push((module, SiteFact { owner, site_span: input.range()? }));
let site_span = input.range()?;
let mut instances = Vec::new();
for _ in 0..input.num()? {
instances.push(InstanceOccurrence {
name: input.text()?,
name_span: input.range()?,
span: input.range()?,
name_positions: input.utf16()?,
positions: input.utf16()?,
});
}
instantiations.push((module, SiteFact { owner, site_span, instances }));
}
let mut subclasses = Vec::new();
for _ in 0..input.tag("S")? {
@@ -185,6 +213,7 @@ impl Writer {
self.field();
self.out.push_str(kind_name(decl.kind));
self.range(decl.name_span);
self.range(decl.decl_span);
// The detail span is written unconditionally — `0 0` for the `None`
// every ordinary declaration has — so the stream stays flat. Adding it
// changed what a record holds, so `FACTS_FORMAT` is bumped and a store
@@ -206,6 +235,20 @@ impl Writer {
self.num(decl.lines.detail.unwrap_or(0));
}
/// One [`Utf16Range`]: four numbers, in the order a reader takes them.
fn utf16(&mut self, range: Utf16Range) {
self.num(range.start.line);
self.num(range.start.character);
self.num(range.end.line);
self.num(range.end.character);
}
/// A file-scope declaration's two client ranges, written after its decl.
fn positions(&mut self, positions: &DeclPositions) {
self.utf16(positions.name);
self.utf16(positions.decl);
}
fn site(&mut self, site: &DeclSite) {
self.text(&site.name);
self.range(site.name_span);
@@ -318,6 +361,7 @@ impl<'a> Reader<'a> {
let name = self.text()?;
let kind = kind_of(self.next()?)?;
let name_span = self.range()?;
let decl_span = self.range()?;
// The mirror of the encoder's unconditional pair: `(0, 0)` is the
// `None`, and a real span can never be, because a declaration's span
// is never empty.
@@ -329,9 +373,26 @@ impl<'a> Reader<'a> {
// this format always agrees with.
let name_line = self.num()?;
let detail_line = self.num()?;
let lines =
DeclLines { name: name_line, detail: (detail_line != 0).then_some(detail_line) };
Some(Decl { name, name_span, kind, detail_span, lines })
// Client positions are not one of a declaration's shared fields: a
// caller reading the `U` group takes them from `positions()` next, and
// a member has none at all (`vlog_semantic::DeclPositions`).
let lines = DeclLines {
name: name_line,
detail: (detail_line != 0).then_some(detail_line),
positions: None,
};
Some(Decl { name, name_span, decl_span, kind, detail_span, lines })
}
fn utf16(&mut self) -> Option<Utf16Range> {
Some(Utf16Range {
start: Utf16Pos { line: self.num()?, character: self.num()? },
end: Utf16Pos { line: self.num()?, character: self.num()? },
})
}
fn positions(&mut self) -> Option<DeclPositions> {
Some(DeclPositions { name: self.utf16()?, decl: self.utf16()? })
}
fn site(&mut self) -> Option<DeclSite> {
+4 -3
View File
@@ -31,9 +31,10 @@ pub use model::{
SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, DeclLines, DeclSite, Def, Definition, DefinitionKey,
ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts,
InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
DefinitionKey, ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder,
IndexCounts, InheritanceEdge, InstanceOccurrence, InstantiationEdge, ReferenceSite, Utf16Pos,
Utf16Range, WorkspaceIndex, WorkspaceSymbol,
};
use std::collections::HashMap;
+190 -13
View File
@@ -35,6 +35,8 @@ pub struct Def {
pub file: FileId,
/// Byte range of the declared name inside that file.
pub name_span: TextRange,
/// Byte range of the complete construct that declares the name.
pub decl_span: TextRange,
/// What kind of declaration it is, for an icon and for hover text.
pub kind: SymbolKind,
/// Where the declaration is *completed* when not at `name_span` — a
@@ -60,6 +62,7 @@ pub struct Def {
/// own lines here; a column, or a rendered preview, is another field written
/// beside these two — plus the [`crate::FACTS_FORMAT`] bump any change to a
/// record owes — and not a second table to keep in step with this one.
/// [`DeclPositions`] is the first of those added fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeclLines {
/// 1-based line the declared name is on.
@@ -67,6 +70,9 @@ pub struct DeclLines {
/// 1-based line the `detail_span` starts on, `None` exactly when there is
/// no detail span.
pub detail: Option<u32>,
/// The same two spans as a *client* counts positions — `Some` for a
/// file-scope declaration, `None` for a member. See [`DeclPositions`].
pub positions: Option<DeclPositions>,
}
impl DeclLines {
@@ -77,10 +83,62 @@ impl DeclLines {
DeclLines {
name: lines.line_col(name_span.start).0,
detail: detail_span.map(|span| lines.line_col(span.start).0),
positions: None,
}
}
}
/// One position as a language-server client counts one: a **0-based** line and
/// **UTF-16 code units** into it — not [`LineIndex`]'s 1-based bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
pub struct Utf16Pos {
/// 0-based line.
pub line: u32,
/// UTF-16 code units from the start of that line's content.
pub character: u32,
}
/// A byte [`TextRange`] as a client sees it, both ends converted once when the
/// file was scanned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
pub struct Utf16Range {
pub start: Utf16Pos,
pub end: Utf16Pos,
}
impl Utf16Range {
/// A span's two ends, converted through the file's own line index.
pub(crate) fn of(src: &str, lines: &LineIndex, span: TextRange) -> Utf16Range {
Utf16Range { start: pos(src, lines, span.start), end: pos(src, lines, span.end) }
}
}
fn pos(src: &str, lines: &LineIndex, offset: u32) -> Utf16Pos {
let (line, character) = lines.utf16_position(src, offset);
Utf16Pos { line, character }
}
/// Where a **file-scope** declaration sits in its file, in the units a client
/// speaks — so pointing an editor at a module declared in a file nobody has
/// open costs no read of that file at all.
///
/// **Why only file-scope declarations carry this.** A member — a port, a
/// parameter, a class field — is a [`Decl`] exactly as a unit is, and there are
/// two orders of magnitude more of them: on opentitan, 1 544 modules against
/// hundreds of thousands of members, so giving every declaration eight more
/// numbers would have roughly doubled the persistent store to serve a caller
/// that does not exist. The units and the members are written in two separate
/// groups of a record, so "units carry positions, members do not" costs a
/// member no field at all — and the day a member wants them, it is the same
/// eight fields in the other group plus the [`crate::FACTS_FORMAT`] bump.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeclPositions {
/// The declared name's own range — an editor's selection range.
pub name: Utf16Range,
/// The whole declaring construct's range.
pub decl: Utf16Range,
}
/// Stable identity of one indexed declaration inside the current index.
///
/// A [`FileId`] may move when a file is added or removed, so this key survives
@@ -154,6 +212,30 @@ pub struct InstantiationEdge {
pub owner: DeclSite,
/// Byte range of the instantiated module's name at the site.
pub site_span: TextRange,
/// The individual instances the statement declares, in source order.
///
/// The edge itself deliberately remains one-per-statement: call hierarchy
/// and code lenses have always treated `sub u1 (), u2 ();` as one written
/// call site. Instance-oriented clients can flatten this list without
/// changing that census.
pub instances: Vec<InstanceOccurrence>,
}
/// One named instance inside an [`InstantiationEdge`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstanceOccurrence {
/// Instance name as written (`u_fifo`).
pub name: String,
/// Byte range of the instance name.
pub name_span: TextRange,
/// Byte range of the whole instance, including dimensions and connections.
pub span: TextRange,
/// `name_span` as a client counts positions, converted when the file was
/// scanned — the same reason [`DeclPositions`] exists, for the other half
/// of what a design-hierarchy row points at.
pub name_positions: Utf16Range,
/// `span` likewise.
pub positions: Utf16Range,
}
/// One class that extends another.
@@ -333,6 +415,37 @@ impl WorkspaceIndex {
self.ambiguous_references.contains(&DefinitionKey::of(def))
}
/// Every file holding a use spelled `name` that this index had to look
/// **outside that file** to answer — whether or not it found anything.
///
/// [`WorkspaceIndex::references_to`] is keyed by the declaration a use
/// landed on, so a use that landed on nothing is in no posting at all.
/// That is the right shape for "who refers to this declaration" and the
/// wrong shape for "which files would notice if this name suddenly
/// started meaning something" — the question a rename has to ask about
/// the name it is renaming *to*, because an `import p::*` of a package
/// that does not exist yet changes meaning the moment a package `p`
/// appears. Answered from the per-file records, which keep every external
/// reference by its spelled name; a resolved one is here too, since a use
/// that already means something can equally start meaning something else.
///
/// A linear walk over the records, in [`FileId`] order and deduplicated:
/// no source is read and nothing is parsed. See
/// `docs/features/refactor-rename/README.md` for the rename's use of it
/// and the measurement.
pub fn files_spelling(&self, name: &str) -> impl Iterator<Item = FileId> + '_ {
let name = name.to_string();
self.facts.iter().enumerate().filter_map(move |(id, facts)| {
let spelled = facts.references.iter().any(|reference| match reference {
ReferenceFact::External { name: spelled, .. } => *spelled == name,
// A local fact resolved inside its own file, so that file
// declares the name and every caller already has it.
ReferenceFact::Local { .. } => false,
});
spelled.then_some(FileId(id as u32))
})
}
/// Every indexed name containing `query`, case-insensitively — LSP's
/// `workspace/symbol`. An empty query matches everything; the result is
/// sorted by name and is not truncated, so a caller with a result limit
@@ -366,6 +479,22 @@ impl WorkspaceIndex {
out
}
/// Every file-scope declaration of one kind, under its name, in name
/// order.
///
/// The cheap half of [`WorkspaceIndex::workspace_symbols`] for a caller
/// that wants units and never members: it walks the unit table alone and
/// sorts nothing, where `workspace_symbols("")` walks every member of every
/// unit and sorts the lot. On opentitan that is 1 544 modules out of
/// hundreds of thousands of declarations, and the difference is 15 ms per
/// call (`docs/features/vscode-hierarchy-sidebar/README.md`).
pub fn units_of(&self, kind: SymbolKind) -> impl Iterator<Item = (&str, &Def)> {
self.units
.iter()
.flat_map(|(name, defs)| defs.iter().map(move |def| (name.as_str(), def)))
.filter(move |(_, def)| def.kind == kind)
}
/// How many unit names and member names are indexed.
pub fn counts(&self) -> IndexCounts {
IndexCounts {
@@ -525,15 +654,18 @@ impl WorkspaceIndex {
}
for symbol in self.workspace_symbols("") {
out.push_str(&format!(
"sym {} in {:?} {:?} {}:{}..{} line={} detail={:?}\n",
"sym {} in {:?} {:?} {}:{}..{} decl={}..{} line={} detail={:?} at={:?}\n",
symbol.name,
symbol.container,
symbol.def.kind,
symbol.def.file.0,
symbol.def.name_span.start,
symbol.def.name_span.end,
symbol.def.decl_span.start,
symbol.def.decl_span.end,
symbol.def.lines.name,
symbol.def.lines.detail
symbol.def.lines.detail,
symbol.def.lines.positions
));
}
for (definition, sites) in &self.reference_sites {
@@ -568,6 +700,18 @@ impl WorkspaceIndex {
edge.site_span.start,
edge.site_span.end
));
for instance in &edge.instances {
out.push_str(&format!(
" instance {} name {}..{} span {}..{} at {:?} {:?}\n",
instance.name,
instance.name_span.start,
instance.name_span.end,
instance.span.start,
instance.span.end,
instance.name_positions,
instance.positions
));
}
}
}
for (name, edges) in self.subclasses() {
@@ -645,6 +789,7 @@ impl WorkspaceIndex {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
instances: edge.instances.clone(),
});
}
for (base, subclass) in &facts.subclasses {
@@ -745,26 +890,42 @@ impl Affected {
pub(crate) struct Decl {
pub(crate) name: String,
pub(crate) name_span: TextRange,
pub(crate) decl_span: TextRange,
pub(crate) kind: SymbolKind,
pub(crate) detail_span: Option<TextRange>,
pub(crate) lines: DeclLines,
}
impl Decl {
fn of(symbol: &Symbol, lines: &LineIndex) -> Decl {
/// A member's declaration: lines only, no client positions — see
/// [`DeclPositions`] for why the cheap half is the only half a member gets.
fn member(symbol: &Symbol, lines: &LineIndex) -> Decl {
Decl {
name: symbol.name.clone(),
name_span: symbol.name_span,
decl_span: symbol.decl_span,
kind: symbol.kind,
detail_span: symbol.detail_span,
lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span),
}
}
/// A file-scope declaration: the same, plus the two ranges a client is
/// pointed at, converted here so no one converts them later.
fn unit(symbol: &Symbol, src: &str, lines: &LineIndex) -> Decl {
let mut decl = Decl::member(symbol, lines);
decl.lines.positions = Some(DeclPositions {
name: Utf16Range::of(src, lines, symbol.name_span),
decl: Utf16Range::of(src, lines, symbol.decl_span),
});
decl
}
fn def(&self, file: FileId) -> Def {
Def {
file,
name_span: self.name_span,
decl_span: self.decl_span,
kind: self.kind,
detail_span: self.detail_span,
lines: self.lines,
@@ -778,6 +939,7 @@ impl Decl {
pub(crate) struct SiteFact {
pub(crate) owner: DeclSite,
pub(crate) site_span: TextRange,
pub(crate) instances: Vec<InstanceOccurrence>,
}
/// Everything one file contributes to an index: read while the file is parsed,
@@ -854,18 +1016,20 @@ impl FileFacts {
/// promises is only that `tree`, `defines`, `sem` and `lines` all describe
/// the text `path` currently holds.
///
/// `lines` is asked for rather than built here because a caller with a
/// finished analysis in hand — a server holding an open buffer — already
/// has one, and because a record now carries each declaration's line
/// ([`DeclLines`]).
/// `src` and `lines` are asked for rather than built here because a caller
/// with a finished analysis in hand — a server holding an open buffer —
/// already has both, and because a record now carries each declaration's
/// line ([`DeclLines`]) and each file-scope declaration's client position
/// ([`DeclPositions`]), neither of which can be read off a tree alone.
pub fn from_analysis(
path: PathBuf,
tree: &SourceFile,
defines: &DefineTable,
sem: &Semantics,
src: &str,
lines: &LineIndex,
) -> FileFacts {
facts_from_analysis(path, tree, defines.clone(), sem, lines)
facts_from_analysis(path, tree, defines.clone(), sem, src, lines)
}
/// The file these facts were read from.
@@ -882,7 +1046,7 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
// given its line without anyone reading the file again later. It is a
// percent of the parse it sits beside (`docs/perf/README.md`).
let lines = LineIndex::new(src);
facts_from_analysis(path, &tree, defines, &sem, &lines)
facts_from_analysis(path, &tree, defines, &sem, src, &lines)
}
/// Read off what one file contributes, from its finished analysis.
@@ -891,6 +1055,7 @@ fn facts_from_analysis(
tree: &SourceFile,
defines: DefineTable,
sem: &Semantics,
src: &str,
lines: &LineIndex,
) -> FileFacts {
let mut facts = FileFacts {
@@ -898,7 +1063,7 @@ fn facts_from_analysis(
defines,
units: Vec::new(),
members: Vec::new(),
instantiations: edges_of(tree),
instantiations: edges_of(tree, src, lines),
subclasses: inheritance_of(tree),
references: Vec::new(),
};
@@ -912,7 +1077,7 @@ fn facts_from_analysis(
if !is_unit(unit.kind) || unit.name_span.is_empty() {
continue;
}
facts.units.push(Decl::of(unit, lines));
facts.units.push(Decl::unit(unit, src, lines));
collect_members(sem, unit, lines, &mut facts.members);
}
let exported: HashSet<(u32, u32)> = facts
@@ -955,7 +1120,7 @@ fn facts_from_analysis(
/// hierarchy reads a buffer with — so the workspace-wide census and the
/// per-file one cannot disagree. A site written at file scope has no
/// instantiating module and is not an edge.
fn edges_of(tree: &SourceFile) -> Vec<(String, SiteFact)> {
fn edges_of(tree: &SourceFile, src: &str, lines: &LineIndex) -> Vec<(String, SiteFact)> {
instantiations::sites(&tree.items)
.into_iter()
.filter_map(|site| {
@@ -969,6 +1134,18 @@ fn edges_of(tree: &SourceFile) -> Vec<(String, SiteFact)> {
span: owner.span,
},
site_span: site.inst.module_span,
instances: site
.inst
.instances
.iter()
.map(|instance| InstanceOccurrence {
name: instance.name.clone(),
name_span: instance.name_span,
span: instance.span,
name_positions: Utf16Range::of(src, lines, instance.name_span),
positions: Utf16Range::of(src, lines, instance.span),
})
.collect(),
},
))
})
@@ -1010,7 +1187,7 @@ fn collect_members(
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
continue;
}
out.push((unit.name.clone(), Decl::of(member, lines)));
out.push((unit.name.clone(), Decl::member(member, lines)));
// A class nested in a package (the dominant UVM shape) is not a unit,
// but an external `cls::x` candidate looks its members up under the
// *class's* name — register them there too. The scope tree is acyclic,
+170 -20
View File
@@ -6,7 +6,7 @@ use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
use vlog_semantic::{
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
Semantics, SymbolKind, WorkspaceIndex,
Semantics, SymbolKind, Utf16Pos, WorkspaceIndex,
};
/// Build an index from `(path, source)` literals, as a server would from disk.
@@ -790,6 +790,37 @@ fn reference_postings_point_from_a_declaration_to_every_cross_file_use() {
assert!(!ws.references_are_ambiguous(definition));
}
/// `files_spelling` is the postings table asked the other question: not "who
/// refers to this declaration" but "who would notice if this name started
/// meaning something". The difference is a use that resolved to **nothing**,
/// which no posting can be keyed by — and which is exactly what a rename onto
/// that name would give a meaning.
#[test]
fn files_spelling_finds_the_uses_no_posting_can_be_keyed_by() {
let sources = [
("dangling.sv", "module strayer;\n import absent_pkg::*;\nendmodule\n"),
("resolved.sv", "module holder;\n sub u0 ();\nendmodule\n"),
("quiet.sv", "module quiet;\n wire absent_pkg;\n assign absent_pkg = 1'b0;\nendmodule\n"),
("sub.sv", "module sub; endmodule\n"),
];
let ws = index(&sources);
let named = |name: &str| -> Vec<&Path> {
ws.files_spelling(name).filter_map(|file| ws.path(file)).collect()
};
// Nothing declares `absent_pkg`, so it is in no posting at all …
assert!(ws.units("absent_pkg").is_empty());
// … but the file importing it is found, and the file that merely declares
// a local wire of the same name is not: a local declaration resolves
// inside its own file and the workspace was never asked about it.
assert_eq!(named("absent_pkg"), vec![Path::new("dangling.sv")]);
// A use that *did* resolve is here too — a name that already means
// something can equally start meaning something else.
assert_eq!(named("sub"), vec![Path::new("resolved.sv")]);
assert!(named("nobody_spells_this").is_empty());
}
#[test]
fn replacing_one_file_rebuilds_reference_postings_without_reparsing_the_others() {
let declaration = "module sub; endmodule\n";
@@ -1383,6 +1414,16 @@ endmodule
let text = files[0].1;
assert_eq!(&text[sites[0].site_span.as_range()], "sub");
assert_eq!(&text[sites[0].owner.name_span.as_range()], "top");
assert_eq!(
sites[0].instances.iter().map(|instance| instance.name.as_str()).collect::<Vec<_>>(),
["u1", "u2"],
"the statement edge keeps each instance without becoming two call sites"
);
for instance in &sites[0].instances {
assert_eq!(&text[instance.name_span.as_range()], instance.name);
assert!(instance.span.start <= instance.name_span.start);
assert!(instance.name_span.end <= instance.span.end);
}
assert!(sites[0].owner.span.start <= sites[0].owner.name_span.start);
assert!(sites[0].owner.name_span.end <= sites[0].owner.span.end);
}
@@ -1668,6 +1709,36 @@ fn a_records_every_field_survives_the_round_trip() {
// inheritance edges — so this is the whole record, not a summary of it.
assert_eq!(back, facts);
assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte");
let mut builder = vlog_semantic::IndexBuilder::new();
builder.add_facts(back);
let restored = builder.finish();
let instances = &restored.instantiations_of("sub")[0].instances;
assert_eq!(instances.len(), 1);
assert_eq!(instances[0].name, "u_sub");
assert_eq!(&EVERY_FIELD[instances[0].name_span.as_range()], "u_sub");
assert_eq!(&EVERY_FIELD[instances[0].span.as_range()], "u_sub ()");
}
/// What format 4 wrote for an instantiation: the statement ended immediately
/// after its module-name span, before the per-instance count and records added
/// in format 5. It must be dropped, not field-shifted into the following `S`
/// tag.
#[test]
fn a_format_4_record_without_instance_occurrences_is_rejected() {
let facts =
FileFacts::of(PathBuf::from("/w/i.sv"), "module top; sub u1 (), u2 (); endmodule\n");
let encoded = facts.encode().expect("encodes");
let mut fields: Vec<&str> = encoded.split('\t').collect();
let instances_at = fields.iter().position(|field| *field == "I").expect("I tag");
assert_eq!(fields[instances_at + 1], "1", "one statement edge");
// I,count,module, owner(name + two ranges), site range = ten fields. The
// next field is the occurrence count added in format 5; each occurrence is
// thirteen more — name, two byte ranges, two client ranges.
let occurrence_count_at = instances_at + 10;
assert_eq!(fields[occurrence_count_at], "2", "two individual instances");
fields.drain(occurrence_count_at..occurrence_count_at + 1 + 2 * 13);
let format_4 = fields.join("\t");
assert!(FileFacts::decode(&format_4).is_none(), "format 4 decoded as format 5");
}
/// Every indexed declaration carries the line it is written on, so a caller
@@ -1709,6 +1780,64 @@ fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() {
assert_eq!(index(&[("/w/w.sv", wide)]).units("m").first().expect("m").lines.name, 3);
}
/// The extension `DeclLines` was shaped for, taken: a file-scope declaration
/// now also carries the two ranges a *client* is pointed at, in the units a
/// client counts in — 0-based lines and UTF-16 code units.
#[test]
fn a_file_scope_declaration_carries_its_client_ranges() {
let src = "// \u{1F389}\nmodule top;\nendmodule\n";
let index = index(&[("/w/t.sv", src)]);
let positions = index.units("top").first().expect("top").lines.positions.expect("positions");
assert_eq!(positions.name.start, Utf16Pos { line: 1, character: 7 });
assert_eq!(positions.name.end, Utf16Pos { line: 1, character: 10 });
assert_eq!(positions.decl.start, Utf16Pos { line: 1, character: 0 });
assert_eq!(positions.decl.end, Utf16Pos { line: 2, character: 9 });
}
/// A multi-byte character before a name shifts its UTF-16 column away from the
/// byte column the spans are in — the whole reason the conversion is done here
/// rather than guessed at later.
#[test]
fn client_ranges_count_utf16_units_not_bytes() {
// `🎉` is four bytes and two UTF-16 units; `é` is two bytes and one.
let src = "/*\u{1F389}\u{e9}*/ module top; endmodule\n";
let index = index(&[("/w/t.sv", src)]);
let def = index.units("top").first().expect("top");
let positions = def.lines.positions.expect("positions");
assert_eq!(def.name_span.start, src.find("top").expect("top") as u32, "the byte span");
// `/*`, two units of `🎉`, one of `é`, `*/`, a space, then `module `.
assert_eq!(positions.name.start, Utf16Pos { line: 0, character: 15 }, "the client column");
assert_eq!(positions.decl.start, Utf16Pos { line: 0, character: 8 });
}
/// Every instance occurrence carries the same pair, for the other half of what
/// a design-hierarchy row points at.
#[test]
fn every_instance_occurrence_carries_its_client_ranges() {
let src = "module top;\n sub u1 (), u2 ();\nendmodule\n";
let index = index(&[("/w/t.sv", src)]);
let edges = index.instantiations_of("sub");
let instances = &edges[0].instances;
assert_eq!(instances.len(), 2);
assert_eq!(instances[0].name_positions.start, Utf16Pos { line: 1, character: 6 });
assert_eq!(instances[0].name_positions.end, Utf16Pos { line: 1, character: 8 });
assert_eq!(instances[0].positions.start, Utf16Pos { line: 1, character: 6 });
assert_eq!(instances[1].name_positions.start, Utf16Pos { line: 1, character: 13 });
}
/// A member does not carry them, deliberately: there are two orders of
/// magnitude more members than units and no caller for theirs, so the record
/// spends nothing on them (`DeclPositions`).
#[test]
fn a_member_carries_lines_but_no_client_ranges() {
let src = "module m (\n input wire clk\n);\nendmodule\n";
let index = index(&[("/w/m.sv", src)]);
let port = index.member("m", "clk").first().expect("the port");
assert_eq!(port.lines.name, 2, "a member still carries its line");
assert_eq!(port.lines.positions, None);
assert!(index.units("m").first().expect("m").lines.positions.is_some(), "the unit does");
}
/// A non-ANSI port is named in the header and finished in the body, and the
/// carrier holds a line for each — the extension the shape was chosen for:
/// richer per-declaration position data is another field on `DeclLines`, not
@@ -1785,34 +1914,52 @@ fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
);
}
/// The generalization of `index_cache`'s `strip_the_line_fields`: remove the
/// two trailing (`name_line`, `detail_line`) fields from every one of
/// `units` unit-decls and `members` member-decls in an encoded record —
/// i.e. what `FACTS_FORMAT` 3 wrote for the same file. Assumes `D0` (no
/// `` `define``s), which every fixture here satisfies, so the `U` tag's
/// field index is fixed and decl positions can be computed directly rather
/// than parsed.
/// The generalization of `index_cache`'s old-record stripper: turn a record
/// this format wrote back into what `FACTS_FORMAT` 3 wrote for the same file —
/// remove, from every one of `units` unit-decls and `members` member-decls, the
/// client positions added in format 5, the `decl_span` added in format 5, and
/// the two trailing (`name_line`, `detail_line`) fields added in format 4.
/// Assumes `D0` (no `` `define``s), which every fixture here satisfies, so the
/// `U` tag's field index is fixed and decl positions can be computed directly
/// rather than parsed.
fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) -> String {
let mut fields: Vec<&str> = encoded.split('\t').collect();
let units_at = fields.iter().position(|f| *f == "U").expect("a U tag");
assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count");
// decl = name, kind, name_span×2, detail_span×2, line×2 — 8 fields.
let unit_decls_end = units_at + 2 + units * 8;
let members_at = unit_decls_end;
// A member's decl = name, kind, name_span×2, decl_span×2, detail_span×2,
// line×2 — 10 fields. A unit's is that plus its two client ranges, four
// numbers each — 18.
let members_at = units_at + 2 + units * UNIT_DECL_FIELDS;
assert_eq!(fields[members_at], "M", "premise: members tag follows the units");
assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count");
// A member entry is the owning unit's name (one text field) plus a decl.
let member_decl_starts: Vec<usize> = (0..members).map(|m| members_at + 2 + m * 9 + 1).collect();
let unit_decl_starts: Vec<usize> = (0..units).map(|u| units_at + 2 + u * 8).collect();
// Highest index first, so removing one strip does not move the others.
let mut starts: Vec<usize> = unit_decl_starts.into_iter().chain(member_decl_starts).collect();
starts.sort_unstable_by(|a, b| b.cmp(a));
for start in starts {
fields.drain(start + 6..start + 8);
let member_decl_starts: Vec<usize> =
(0..members).map(|m| members_at + 2 + m * (MEMBER_DECL_FIELDS + 1) + 1).collect();
let unit_decl_starts: Vec<usize> =
(0..units).map(|u| units_at + 2 + u * UNIT_DECL_FIELDS).collect();
// Highest index first, so removing one strip does not move the others, and
// within one decl highest-first for the same reason.
let mut starts: Vec<(usize, bool)> = unit_decl_starts
.into_iter()
.map(|start| (start, true))
.chain(member_decl_starts.into_iter().map(|start| (start, false)))
.collect();
starts.sort_unstable_by_key(|start| std::cmp::Reverse(start.0));
for (start, is_unit) in starts {
if is_unit {
fields.drain(start + MEMBER_DECL_FIELDS..start + UNIT_DECL_FIELDS);
}
fields.drain(start + 8..start + 10);
fields.drain(start + 4..start + 6);
}
fields.join("\t")
}
/// Fields one member declaration occupies in a record this format writes.
const MEMBER_DECL_FIELDS: usize = 10;
/// The same for a unit, which also carries its two client ranges.
const UNIT_DECL_FIELDS: usize = MEMBER_DECL_FIELDS + 8;
#[test]
fn an_index_built_from_records_is_the_index_the_parse_would_have_given() {
// The claim the cache rests on: facts through the record format and back
@@ -1983,7 +2130,7 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
let path = PathBuf::from("/w/x.sv");
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
let from_text = FileFacts::of(path.clone(), src);
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, &lines);
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, src, &lines);
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
assert_eq!(
from_analysis.encode(),
@@ -2013,7 +2160,8 @@ fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
};
let (tree, defines, sem, lines) = as_a_server_analyzes(&src);
let from_text = FileFacts::of(path.clone(), &src);
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &lines);
let from_analysis =
FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &src, &lines);
assert_eq!(
from_analysis.encode(),
from_text.encode(),
@@ -2066,6 +2214,7 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from
&tree,
&defines,
&sem,
src,
&lines,
));
}
@@ -2082,6 +2231,7 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from
&tree,
&defines,
&sem,
changed,
&lines,
));
let mut parsed = from_text.clone();
+246 -3
View File
@@ -81,9 +81,26 @@ workspace index, from the same file list, and are replaced with it.
- **Consumes `vlog_parser`**: `tokenize` for the word harvest, `KEYWORDS` for
the keyword tier, `defines::DefineKind` to keep `` `undef`` entries out of the
macro table.
- **Consumes `vlog_refactor`** exactly as M4 did — `module_names`,
`module_definition`, `instantiation_plan`, `render_with` — through the
unchanged `module_tier`. Nothing in `vlog_refactor` was touched.
- **Consumes `vlog_refactor`** — `module_definition`, `instantiation_plan`,
`render_with` — through `module_tier`. Nothing in `vlog_refactor` was
touched, then or since.
- **Stopped consuming `vlog_refactor::module_names` (2026-08-28).** That
function is `WorkspaceIndex::workspace_symbols("")` filtered to modules, and
`workspace_symbols` builds and sorts a record per declaration in the whole
workspace — 43 140 of them in opentitan, on *every keystroke*.
`Candidates::modules` is the same list, built once beside the index and
filtered per request, and
`candidates::tests::the_module_table_answers_exactly_what_module_names_answers`
asserts the two agree — set *and* order — at eleven queries.
`vlog_refactor::module_names` is unchanged and still has its own callers;
only tier 0 stopped asking it. **Note for whoever changes it**: the two are
now pinned against each other by that test, so a change to `module_names`'s
match rule or ordering breaks the build rather than silently diverging.
- **Reads `WorkspaceIndex::units`'s `Def::name_span` directly (2026-08-28)**,
to anchor the header slice (`module_header`). Treated as advisory, never as
truth: the byte range is checked against the text actually read, and a
mismatch — a file edited on disk since the last scan — declines the slice
and parses the whole file, exactly as before.
- **Duplicated deliberately, not shared**: `vlog_refactor::ports::visible_in`
answers "is this *one* name visible here" and is `pub(crate)` to that crate;
`completion::visible_symbols` answers "what is visible here". They share the
@@ -221,6 +238,74 @@ The one request that is *not* microseconds is a module-item position, which
still parses up to 64 defining files. That is M4's cost, unchanged and
separately capped.
### The module tier, 2026-08-28
That last paragraph was the whole bill. `performance.md` §6d measured
completion at **34–66 ms per keystroke** against opentitan, worst at 0–4 typed
characters, and typing an eleven-character identifier at **201 ms** of blocked
single-threaded loop. The probe
(`perf::completing_one_keystroke_at_a_time`) runs the same request with the
cursor at module-item position and inside an expression, where tier 0 is gated
off:
| generated corpus, 4 000 files | at an item | in an expression |
|---|---:|---:|
| empty prefix, before | 53.2 ms | 0.19 ms |
| empty prefix, after | **3.17 ms** | 0.19 ms |
Every other tier put together is 0.19 ms and always was. Two changes, neither
of which may alter an item:
1. **`module_header` — parse the header, not the file.** A plan reads a
module's parameter list and port list and nothing else, and both are in the
header; the body was being parsed to reach them. The slice is the file's
text up to the `;` that ends the header, **kept byte for byte** so every
span the plan reads still points where it did, with an `endmodule` written
in place of the body. It is anchored on the index's `Def::name_span`
(checked against the text, so a file edited under the index declines rather
than slices at a stale offset) and the end is found by lexing a bounded
window and walking a **whitelist**: `static`/`automatic`, `import …;`,
`#(…)`, `(…)`, `;`. Anything else answers "no slice" and the whole file is
parsed exactly as before — `module aes import aes_pkg::*; #(…) (…);` writes
three semicolons and only the last ends the header, which is why this is a
whitelist and not a search for the first `;`.
2. **`Candidates::modules` — table the module names.** See Handshakes.
Two guards keep the answer identical, and both are load-bearing rather than
decoration:
- **A non-ANSI port list writes its directions in the module *body***
(`module m (a); input wire [7:0] a;`), which is the part the slice drops. A
plan whose ports have neither a direction nor a type is the signature of
that, and `plan_for` re-plans from the whole file when it sees one.
`a_non_ansi_port_list_is_planned_from_the_whole_file` asserts both halves —
that the header alone really does lose them, and that the guard really does
get them back.
- **A slice that fails to plan is re-planned whole**, so the list can only
ever lose an item where it would have lost it anyway.
`the_header_slice_plans_exactly_what_the_whole_file_plans` is the argument, not
the prose: fifteen header shapes — imports, two imports, no ports, an empty
port list, non-ANSI with and without body declarations, a comment inside the
header, a lifetime qualifier, a directive between the name and the port list, a
directive *inside* the port list, an escaped module and port name, a second
module before and after the one being planned, and a header wider than the
first window rung — each planned both ways and compared field by field.
`HEADER_WINDOWS` is a ladder because the lex is the whole cost of the slice and
it is linear in what it is handed. The rungs are measured, not guessed: over
opentitan's 344 RTL modules 59% of headers end inside 256 bytes and 90% inside
2 KB, and the largest is 6.6 KB — so a top rung of 16 KB, because a rung that
is too small is not a wrong answer but a 2–4 ms whole-file parse. The full
before/after, including the four `aes_control*` modules that found this, is in
`docs/perf/README.md`, *Before / after — round 7*.
Against the real checkout, over the wire: **63–66 ms → 13.1–15.0 ms** at the
empty prefix, and typing `aes_reg_top` **200.9 ms → 64.5 ms**. What is left is
64 real header parses, and the two ways down from there — memoizing the plan,
or `completionItem/resolve` — both change something this round was not allowed
to change. They are filed in `docs/perf/README.md`.
## Version 0.3.0
Every place `tools/RELEASING.md` says the version lives, plus the install
@@ -269,9 +354,47 @@ incidental; they exercise the parser, not the version.
- [x] Version 0.3.0 across the workspace, the extension and the docs
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`,
`cargo test --workspace` all clean; `smoke.js` OK
- [x] **Performance wave, Lane B (2026-08-28):** completion 34–66 ms per
keystroke → 13–15 ms worst case on opentitan and 3.2 ms on the
same-sized generated corpus, with the items pinned identical. Tier 0
parses the header instead of the whole declaring file
(`module_header` / `plan_for`), and the module-name list is a table
built with the index (`Candidates::modules`) instead of a
whole-symbol-table sort per keystroke.
## Work log
- **2026-08-28 (dev, performance wave Lane B)** — the module tier.
Profiled first, as the brief asked, with an `#[ignore]`d house probe rather
than a guess: `perf::completing_one_keystroke_at_a_time` measures the whole
request at nine prefixes with tier 0 on and off. The answer was that
**everything except tier 0 costs 0.19 ms at every prefix**, so
`performance.md`'s hypothesis — "scanning/filtering the candidate set, and
the broader the prefix the more of the 3 976-file symbol table is walked" —
was half right: the symbol-table walk was real but it was
`vlog_refactor::module_names`'s, inside tier 0, not the word or index tiers'.
What changed is in *The module tier, 2026-08-28* above, with the identity
argument and the fifteen-shape test that carries it. Two decisions worth
naming:
- **No cache.** The obvious fix is to memoize the plan per module. It was not
taken: `Candidates` is rebuilt at `didSave`, and tier 0 reads
`ws.text_of`, which sees an *unsaved* buffer — so a cache there would go
stale exactly where `another_open_buffer_overlays_disk_once_the_index_is_rebuilt`
says it must not. Slicing needed no new invalidation rule at all, and it
makes the cold request fast rather than only the repeat.
- **The whitelist is a whitelist.** `header_end` refuses every shape it does
not recognise instead of scanning for the first `;`. `module aes import
aes_pkg::*; #(…) (…);` is the case that makes the difference, and it is
what most of opentitan's `aes*` modules are written as: a first-`;` scan
would have silently reported them as having no ports.
Deviations from the brief: none on this item. The measurement is on
`docs/perf/README.md` rather than here, because that is where this
repository keeps before/after numbers; this section keeps the argument.
- **2026-08-24 (dev)** — implemented.
**Keyword list.** `vlog_parser/src/token.rs`'s `is_keyword` was a 181-arm
@@ -637,8 +760,128 @@ unambiguous" (typo/missing assertion) territory; all three are judgment
calls for the dev/lead. No commits, no edits to `TODO.md` or the umbrella
`docs/features/refactor/README.md`.
### 2026-08-28 — QA agent (performance wave Lane B: the module tier)
Verdict: **the fix holds. No corruption found, one pre-existing parser gap
surfaced (filed below, not fixed here — out of this feature's touched
files).**
**What I attacked.** The whitelist walk in `header_end`, the guard in
`plan_for`, and `Candidates::modules`'s parity with
`vlog_refactor::module_names`, per the adversarial list in the round brief:
header-slice mis-slicing, stale-span handling, and the module-table's set
*and* order against hostile queries.
**Header-slice attacks — all safe, one gap in the dev's own test found and
fixed.** Extended `SHAPES` in `completion.rs` (in
`the_header_slice_plans_exactly_what_the_whole_file_plans`) with: a single
`import a::*, b::*;` declaration (comma-chained packages, one statement —
`skip_to_semicolon` must not stop at the first `::`), a parameter default
whose string literal contains a literal `;` and `)` (`"a;b)c"`), CRLF line
endings through the whole header, a genuine attribute instance right after
the module name, and one inside the port list on a single port. All five
plan identically sliced vs. whole-file; the two attribute shapes exposed
something worth recording (next paragraph). Added
`the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously`
(`completion.rs`) asserting the first three actually invoke the slice path
(`module_header(..).is_some()`) rather than passing the comparison
vacuously by both sides falling back to the whole file — a real risk with
this style of pinned-equality test, since a shape the whitelist declines
passes the assertion for free.
**Finding (LOW, not a regression this round introduced) — `completion.rs`,
`module_header`, and transitively `vlog_semantic`/`vlog_parser`: a module
with an attribute instance (`(* ... *)`) anywhere near its header is not
indexed as a `Module` unit at all.** `WorkspaceIndex::units("attributed")`
and `..("port_attributed")` both come back empty for
`module attributed (* some_attr *) #(...) (...);` and
`module port_attributed (input logic clk, (* keep *) output logic q);`.
`module_header` correctly declines at its very first line (`let [def] =
index.units(module)...else { return None }`, `completion.rs:99-103`) —
this is the documented whole-file fallback working exactly as designed,
not a slicing bug — but it means completion's module tier, which sources
its candidate names from the same index, never offers such a module as a
completion candidate in the first place, attribute-based header or not.
This predates 2026-08-28 (the index-level gap is not something tier 0's
change touches), so it is filed rather than fixed: out of Lane B's stated
files (`vlog_semantic`/`vlog_parser` are not touched-file scope for this
round). Reproduction: `cargo test -p lucisv_server -- completion::tests::
a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`, a new
permanent regression pinning the current (gap) behavior so a future fix to
the indexer is *noticed* here rather than silently changing what
`module_header` sees.
This also means the dev's own `noisy` shape's doc comment ("a comment and
an attribute inside the header") was inaccurate — it has two comments and
no attribute; I did not edit that comment since fixing it is a one-line
call for the dev, and the actual behavior is now separately pinned above.
**Stale-span attack**: `a_stale_index_span_declines_to_slice_rather_than_
slicing_the_wrong_bytes` (dev's own test) re-verified by hand — re-ran with
`cargo test -p lucisv_server -- completion::tests::a_stale_index_span` in
isolation, passes. No addition needed; the test already does the right
thing (name-span-vs-text mismatch declines).
**`Candidates::modules` parity**: `contains_ignore_case` (`candidates.rs`)
and `contains_ignore_ascii_case` (`vlog_semantic::workspace`) are
byte-identical implementations, and both `Candidates::modules` and
`vlog_refactor::module_names` ultimately filter the same
`workspace_symbols`-sorted, `container.is_none() && kind == Module` slice
with the same predicate — so parity is structural, not incidental, and
holds for any name content (case-different names, escaped identifiers,
duplicate names across files) without needing per-shape tests. Traced by
hand rather than by adding more cases to the dev's own
`the_module_table_answers_exactly_what_module_names_answers` (which
already covers duplicates-across-files and query-case-differences); no
counter-example found.
**Numbers reproduced** (release build, this machine, M1 Max):
- `perf::completing_one_keystroke_at_a_time`: empty prefix at item position
**3.28 ms** (dev's claim: 3.17 ms — within machine noise), expression
position 190 µs unchanged. Whole-file plan 2.68 ms vs. header-alone
16.3 µs for one skeleton off the 1214-line generated file — matches the
claimed order of magnitude.
- `LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test
--release -p lucisv_server perf::completing_over_a_real_project`: empty
prefix **11.6 ms** (dev's claim against the real wire protocol: 13.1–15.0
ms; this is the in-process `completions()` call without LSP round-trip
overhead, so a bit faster is expected, same order of magnitude). Zero
modules fell back to whole-file parsing across every prefix tested
(`parsed whole: []`), confirming the slice fires in practice on real RTL,
not just in the synthetic corpus.
- Live end-to-end confirmation against the real opentitan checkout with
this worktree's release binary (`node`-free, via a copy of the
scratchpad's `lspclient.py`/`bench.py` pointed at
`target/release/lucisv-server`): completion itself was not re-measured
over the wire (out of scope to re-run the whole battery), but see the
references-nav QA log below for the documentHighlight leg of the same
session, which used the identical harness.
**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test
--workspace` (1261 passed, up from 1259 with my additions), `node
editors/vscode/smoke.js target/release/lucisv-server` — all clean, run
against the worktree with my additional tests included.
No fixes applied beyond the two new permanent regression tests (attack
shapes actually slicing; the attribute-indexing gap pinned). No commits.
## Review
**2026-08-28 — lead, performance-wave Lane B.** Reviewed after QA's
SHIP; gates re-run on the worktree (fmt clean, clippy silent, 2495
workspace tests green). The header-slice design is right because of
what it refuses: a whitelist walk that re-plans from the whole file on
anything it does not positively recognize — including the non-ANSI
signature — is the honest shape, and QA's seven added attack shapes
plus the field-by-field plan-equality pin make the "items byte
identical" claim tested rather than asserted. The stale-span decline
and the Candidates::modules order-and-set parity are correctly pinned.
QA's LOW (attribute-instance modules not indexed as units — a
pre-existing parser/semantic gap the guard already declines safely) is
accepted as filed with its regression pin; it belongs to a parser
round, not this one. The residual opentitan cost is real header
parses, with the plan-cache and completionItem/resolve options filed
where the numbers are. Accepted.
**2026-08-24 — lead.** Reviewed after QA's ship verdict — the first
milestone through with no rework round; gates run independently (1262
tests, 0 failures, clippy silent). The keyword-table refactor was verified
+15 -1
View File
@@ -104,7 +104,21 @@ change. No `initializationOptions` fallback is needed, and none was added.
`extractSettingsInformation(['lucisv'])` calls
`workspace.getConfiguration(undefined).get('lucisv')`, which returns the whole
section with every key at its effective value — so the server sees
`serverPath` and `rainbowBeginEnd` in the payload too, and ignores them.
`serverPath`, `rainbowBeginEnd` and `verbose` in the payload too, and ignores
all three.
**Two settings in the section are deliberately not wire settings**, and the
list is worth keeping short:
- `lucisv.serverPath` decides *which binary* the extension spawns, so it can
only be read before there is a server to tell.
- `lucisv.verbose` (2026-08-29) decides *how* it is spawned — it becomes the
`--verbose` argument, and a process argument cannot be changed by a
notification. Hence the one thing no other setting here does: changing it
restarts the language server. It is a startup decision, not an opinion the
server can adopt mid-session, and giving it a second spelling as a wire
setting would mean two ways to say one thing that could disagree. See
`docs/features/verbose-timing/README.md`.
Other editors: anything that can send `workspace/didChangeConfiguration` with
that `settings` shape works. Neovim's `vim.lsp.config` sends its `settings`
+172
View File
@@ -145,6 +145,16 @@ invariant #4 is not in play. The formatter is not involved in this path at all.
have disagreed with the first in the corner cases nobody tests.
- **`IncludeGraph::incdirs()`** — a read-only accessor, so a candidate
spelling can be a suffix under a real include path rather than a guess.
- **`IncludeGraph::includers()`** (added 2026-08-28) — a read-only accessor
over the edge table's keys, which is what lets the sweep read the files
that write a resolving `` `include`` instead of every file in scope. The
property it stands on is `resolve`'s agreement with the `found` the edges
were built from; it is written out under "The sweep reads the includers,
not the workspace", and a change to either half must re-read it.
**Scope note for the lead:** `includes.rs` is outside the Lane A file
list this round was scoped to. The accessor is four lines, purely
additive, and there is no second way to ask the graph this question
without a second copy of the include scan — flagged rather than smuggled.
- **`includes::normalize` is now `pub`** (it was private). A renamed path and
a resolved include are compared, and they must be folded the same way; a
fourth private copy of that loop is the one thing that guarantees they
@@ -212,6 +222,47 @@ probe (`cargo test --release -p lucisv_server --bin lucisv-server
file_ops::tests::perf -- --ignored --nocapture`), the same shape as
`includes.rs`'s: it prints and asserts nothing but the corpus's presence.
### The sweep reads the includers, not the workspace (2026-08-28)
The prefilter above still cost a *read* of every file to run. On OpenTitan
(3 976 files) that is 249 ms of `sources()` per gesture, and the server
advertises `willRename` with a `**` folder filter, so **renaming any folder in
the explorer paid it**.
The include graph already holds the answer. `IncludeGraph`'s edge table is
built as `scan(text).filter_map(|include| self.found(Some(path), include))`
over every in-scope file, and `resolve` is exactly `found` followed by the
index's own spelling of the result — so `resolve` answers `Some` for an
include if and only if `found` did. Therefore:
> **A file with no entry in the edge table writes no `` `include`` this
> workspace can resolve, so every iteration of `will_rename`'s inner loop over
> it hits `let Some(old) = graph.resolve(…) else { continue }`.** It can
> produce neither an edit nor a warning, and reading it is reading the
> workspace to answer "nothing".
`Workspace::include_sources` is that set — `IncludeGraph::includers()` — plus
every **open buffer**, because the graph is rebuilt on save and an `` `include``
typed and not yet saved is in the buffer and in no edge
(`an_unsaved_include_is_still_rewritten`). The one-directional property is
asserted directly over a hostile tree rather than argued
(`nothing_skipped_has_an_include_to_rewrite`: every in-scope file the sweep
skips is checked to have no resolving include, and the tree is asserted to
actually exercise the skip).
Measured, `--release`:
| | before | after |
|---|---:|---:|
| synthetic 506 files, 1 of them including anything | reading the scope **16.1 ms** | reading the includers **18.9 µs**; whole answer **35.4 µs** |
| OpenTitan, 3 976 files, 331 of them includers | `sources()` **249 ms** | whole answer **14.1 ms** |
Same staleness premise the rename family adopted the same day
(`docs/features/refactor-rename/README.md`): the graph is the server's
authority on who includes what, a file changed on disk with nothing telling
this server is a file the sweep does not read, and open buffers are the
exemption.
The notifications cost one `reindex()` each, which is the cost a save has.
## Status / TODO
@@ -230,6 +281,10 @@ The notifications cost one `reindex()` each, which is the cost a save has.
is still one search order and one path folding.
- [x] `watch::watched` made public, so the notifications and the watcher share
one scope test.
- [x] The sweep reads the include graph's includers plus the open buffers
rather than `sources()` (2026-08-28): `IncludeGraph::includers`,
`Workspace::include_sources`, the one-directional property asserted over
a hostile tree, and a before/after probe.
- [x] Tests: 24 in `file_ops.rs`, 7 in `server.rs` (dispatch, warning volume,
reindex, watcher-double, unopened file, `null`), 1 in `main.rs` (the
capability on the wire), 1 e2e session (real binary, edit decoded,
@@ -327,6 +382,45 @@ target/debug/lucisv-server` → OK, 9 messages, unchanged from `bf17ddd`
JSON and adds no message). Perf measured as above. No new dependency, no
version bump, no other crate touched.
**2026-08-28 — dev agent (performance wave, Lane A).** The sweep stops reading
the workspace. `performance.md` §6e flagged `file_ops.rs:120`'s `ws.sources()`
as the same shape as the rename family's, unmeasured; it is 249 ms of file
reading per gesture on OpenTitan, and the server advertises `willRename` with
a `**` folder filter, so **renaming any folder in the explorer paid it** to
learn that 3 645 of 3 976 files write no `` `include`` that resolves.
The include graph already holds that fact. `IncludeGraph::includers()` — four
lines, the edge table's keys — is the new accessor, `Workspace::include_sources`
is the set (includers plus every open buffer, because the graph is rebuilt on
save and an unsaved `` `include`` is in neither `raw` nor `edges`), and
`will_rename`'s loop is otherwise untouched. The argument is one sentence long
and is written up under "The sweep reads the includers, not the workspace":
`resolve` is `found` plus a re-spelling, and `raw` is built from `found`, so a
file with no edge has no include `resolve` answers — every iteration of the
inner loop over it hits its first `continue`.
Rather than argue that by inspection alone it is asserted over a hostile tree:
`nothing_skipped_has_an_include_to_rewrite` walks every in-scope file the sweep
skips and checks each of its `` `include``s resolves to nothing, and asserts
the tree exercises the skip at all. Two behaviour tests beside it —
`the_narrowed_sweep_reads_the_includers_and_answers_the_same` (24 files, 1
includer, 2 with dangling includes) and `an_unsaved_include_is_still_rewritten`.
Measured, `--release`: synthetic 506 files, reading the scope **16.1 ms** →
reading the includers **18.9 µs**, whole answer **35.4 µs**
(`perf::a_will_rename_before_and_after`). OpenTitan, 3 976 files with 331
includers: `sources()` **249 ms** → whole answer **14.1 ms** (throwaway probe
against the local checkout, deleted; no test depends on it).
**One scope deviation, flagged not smuggled:** `includes.rs` is outside the
file list this lane was scoped to, and the accessor was added there anyway.
The alternative was a second copy of the include scan inside `state.rs`, which
is the one thing this module's Handshakes section already says must not
happen. Recorded in Handshakes above and in the round's report.
Gates: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` clean,
`cargo test --workspace` green, `node editors/vscode/smoke.js` OK.
## QA log
### 2026-08-27 — QA agent, file operations (TODO.md §9c)
@@ -514,8 +608,86 @@ nested-batch ordering is a documentation/robustness suggestion for the dev,
not a blocker — no corruption path exists even in that shape, thanks to the
safety net doing its job independently of what `Moves` models.
**2026-08-28 — QA agent (performance wave, Lane A).** Verified the round that
moves `will_rename`'s sweep off `ws.sources()` onto
`Workspace::include_sources()` (the include graph's `includers()`, plus open
buffers). Worked alongside the rename-family QA pass in the same worktree;
see `docs/features/refactor-rename/README.md`'s QA log for the shared gate
run.
### Gates
`cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace` (0
failures workspace-wide) and `node editors/vscode/smoke.js` all pass — see the
refactor-rename QA entry for the exact run, which covered this round's diff
in the same pass. `file_ops::tests::perf::one_rename_sweeps_the_whole_corpus_in_milliseconds`
and `includes::tests::perf::building_the_graph_over_the_whole_corpus_is_milliseconds`
fail in this worktree because `corpus/` is not checked out here; confirmed
pre-existing (unchanged by this diff, present at `HEAD` before it) and
unrelated.
### Attacks
The safety-net argument this narrowing rests on ("a file with no entry in the
edge table writes no `` `include`` this workspace can resolve") is
mechanical and did not need attacking on its own terms — `nothing_skipped_
has_an_include_to_rewrite` already asserts it directly over whatever tree a
test builds. What was worth attacking is whether `includers()` narrows in
**every** file that matters, not just the ones the dev's own tree happened to
build:
- **An include chain, `a.svh -> b.svh`, with a third file `c.sv -> a.svh`
never spelling `b.svh` at all.** Renaming `b.svh` must narrow to `a.svh`
(its direct includer) and rewrite only it; `c.sv` must not be mistaken for a
candidate even though it transitively depends on the moved file through
`a.svh`. Added `an_include_chain_narrows_to_the_direct_includer_of_the_moved_file`
— passes: `will_rename` only ever rewrites a *direct* include of the moved
file, which is exactly what `includers()` (a flat key set, not a
reachability walk) bounds.
- **A case-mismatched include spelling** — `` `include "DEFS.svh"`` written
against a real `defs.svh` on disk, which macOS's default case-insensitive
filesystem (confirmed case-insensitive on this machine) resolves silently.
`IncludeGraph::found`/`found_as_if` key `raw` by the **includer's own path**,
not the target's spelling, so the case mismatch does not stop the includer
from landing in `includers()`. Added
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites` — passes,
narrows in and rewrites correctly.
- **Unsaved includer, and the property test's own coverage** — re-read
`an_unsaved_include_is_still_rewritten` and
`nothing_skipped_has_an_include_to_rewrite`; both hold and both are
exercised (`assert!(skipped > 0, ...)` in the property test actually forces
the tree to have skippable files, so the property is not vacuously true).
No divergence found: every file `will_rename` would have read under the old
`ws.sources()` sweep and actually needed (an includer of something that
resolves) is still read under `include_sources()`, and no file that used to
be read-and-skipped is now silently mis-included either. The `includes.rs`
scope deviation the dev flagged (a four-line, purely additive accessor,
outside Lane A's stated file list) is accepted as argued — the only
alternative was a second copy of the include scan, which the feature's own
Handshakes section already forbids.
### Summary
| Claim | Verdict |
|---|---|
| Gates | **Pass** |
| `includers()` narrows in every file that can produce an edit or a warning | **Holds** under an include-chain attack and a case-mismatched-spelling attack, beyond the dev's own tree |
| Scope deviation (`includes.rs::includers`) | Accepted, correctly flagged, minimal |
**Verdict: ship.** No findings against this round's diff. (The rename family's
own residue finding, which needs the lead's ruling, is filed in
`docs/features/refactor-rename/README.md` and does not touch this feature.)
## Review
**2026-08-29 — lead, performance-wave Lane A (willRenameFiles).** The
includers() narrowing is the same discipline as the rename fan-out
applied to the include graph, QA's chain/case-spelling/unsaved attacks
all pinned, and the property test ("nothing skipped has an include to
rewrite") is the right shape of guarantee. Accepted; merged by the
lead.
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
+19
View File
@@ -22,6 +22,25 @@ per notification.
filelist, are whole rebuilds exactly as before. `watch::one_scope_file` is
the test. See `docs/features/incremental-index/README.md`.
- **Amended (index-scope, 2026-08-28): this feature now carries a little more
weight than it did, and the difference is named here rather than left to be
found.** A scope-widening `didOpen` used to run a whole rescan, which re-read
every in-scope file and so *incidentally* caught anything that had changed on
disk behind the server's back. Since that round it indexes only the folders it
added. For a client that advertised
`workspace.didChangeWatchedFiles.dynamicRegistration` — VS Code and Neovim
both do — nothing is lost: the registered glob covers create, change and
delete of every source file in the workspace, which is the mechanism, and the
widen never was. For a client that did not, the **save-only model this README
already documents is slightly narrower**: an external change in a folder
already in scope now waits for the next whole rescan (a save of a file the
index does not hold, a settings change, a folder change, a rename/delete
notification) instead of possibly being caught by the next jump. That is the
same class of window, not a new one — a save has taken the one-file
incremental path since 2026-08-27, so such a session already had no reliable
whole-tree re-read. Written up in full in
`docs/features/index-scope/README.md`.
- **Registration is the only way in.** The protocol has no static
`didChangeWatchedFiles` server capability — a server that wants file events
must ask for them with `client/registerCapability`, and only a client that
+9 -1
View File
@@ -96,7 +96,15 @@ promised:
- **A third one is a field.** A column, a rendered preview, an end line: add it
to `DeclLines`, write it in `Writer::decl`, read it in `Reader::decl`, bump
`FACTS_FORMAT`. Nothing else moves, because nothing else knows how many
fields a `DeclLines` has. A *parallel table* keyed by declaration was the
fields a `DeclLines` has. **Taken, 2026-08-29**, and it went exactly that
way: `docs/features/vscode-hierarchy-sidebar/README.md` added
`positions: Option<DeclPositions>` — the declared name's and the whole
declaration's ranges in the units a client counts in — for `FACTS_FORMAT`
4 → 5, so a design-hierarchy snapshot needs no file text at all. The one
amendment that round made to the story above: those positions ride
**file-scope declarations only**, because members outnumber units by two
orders of magnitude and the record's `U` and `M` groups are separate, so
the absence costs a member nothing. A member still carries its lines. A *parallel table* keyed by declaration was the
alternative and was rejected: it would have to be kept in step with `Decl`
through every merge, every incremental update and every record round-trip,
and there is no second consumer to justify the indirection
+25 -7
View File
@@ -221,13 +221,28 @@ impl WorkspaceIndex {
`detail_span`. **3 → 4** (2026-08-28,
`docs/features/hover-line-index/README.md`): each declaration gained its two
*line numbers*, which is what lets a server print `file:line` for an indexed
declaration without reading that file. Same rule each time, same
declaration without reading that file. **4 → 5** (2026-08-29,
`docs/features/vscode-hierarchy-sidebar/README.md`): one bump for three
additions — each declaration's `decl_span`; a per-instance
`InstanceOccurrence` list on every instantiation edge (the edge itself is
still one per *statement*, so no census moved); and **client positions**,
0-based lines and UTF-16 columns, on every file-scope declaration and every
instance occurrence, which is what lets the design-hierarchy snapshot answer
with no file read at all. Members deliberately get none: the `U` and `M`
groups of a record are separate, so "units carry positions, members do not"
costs a member no field, not even a presence flag — and members outnumber
units by two orders of magnitude. Same rule each time, same
consequence: the store is discarded whole on the first scan after the
upgrade and rewritten — measured at about 175 ms over the 860-file corpus,
once. `a_store_from_any_previous_facts_format_is_dropped_not_misread` now
once. `a_store_from_any_previous_facts_format_is_dropped_not_misread`
checks **every** format this build is not, rather than the one literal
number it was pinned at, so the next bump inherits the test.
The store grew 68 KB (2.9 %) for the lines.
number it was pinned at, so each bump inherits the test; its
belt-and-braces half (a genuine previous-format record served past the
header) is re-derived at each bump — `as_a_format_4_record` at format 5.
The store grew 68 KB (2.9 %) for the lines at format 4, and a further
212 KB (8.9 %) over the 860-file corpus for all of format 5 — of which the
client positions are 1.7 %, measured separately on the same corpus and again
on opentitan (1.9 % of a 24.7 MB store).
- `record_path` is public separately because a store keyed by path reads that
field out of every record it holds and decodes only the ones it is asked
for.
@@ -363,9 +378,12 @@ site's own name span `22..25`), no subclasses, and one external reference fact
(`e`, name `sub`, one resolution path also named `sub`, occurrence `22..25`),
then the checksum. **The example is written at `FACTS_FORMAT` 2 and is kept
for its shape, not its field count**: since then every declaration also
carries its detail span (`0 0` when there is none, format 3) and its two line
numbers (format 4), so a real record today has four more numbers per
declaration than the one above. The framing — one line, tab-separated,
carries its detail span (`0 0` when there is none, format 3), its two line
numbers (format 4), its `decl_span` and — for a file-scope declaration only —
its two client ranges of four numbers each (format 5); and an instantiation
edge carries a length-prefixed list of its individual instances, each a name,
two byte ranges and two client ranges. So a real record today is considerably
wider per declaration than the one above. The framing — one line, tab-separated,
length-prefixed lists, checksum last — is what the example is for and is
unchanged. The record is what lies between the hash field and the
checksum; both hashes above are illustrative.
File diff suppressed because it is too large. Load diff
+12 -1
View File
@@ -74,7 +74,18 @@ are answerable without a debugger. All three settings ride both settings doors
here because it is the one non-obvious reach of the setting.
- **The denominator is the work list after `exclude` and after the cap.** It
is `vlog_semantic::index_order`'s length, known before the first parse, so
the bar counts towards a number the scan will actually reach.
the bar counts towards a number the scan will actually reach. **Amended
(index-scope, 2026-08-28): a scope widen's work list is the files it is
actually indexing** — the folders it added, plus the open buffers it refreshes
— so a jump into a 25-file folder of a 4 000-file project says `1/25`, not
`1/3979`. That is the same rule, not an exception to it: the denominator has
always been "what this scan will do", and a widen simply does less. The bar's
**end message is unchanged** and still names the whole index
(`"N files indexed"`), because the bar names the scan and the message names
what the workspace now holds. No test in this feature moved; the fixtures
here are small enough that a widen's work list is the whole scope, and the
new denominator has its own test in `state.rs`
(`a_widen_bar_counts_the_new_files_and_not_the_whole_scope`).
- **The percentage only counts up, and the last file always reports.** See the
throttle below; `the_report_schedule_never_floods_and_never_stops_short`
checks both properties across nine workspace sizes.
+26 -3
View File
@@ -12,6 +12,26 @@ loop, document state, position arithmetic, and one small handler per
capability. It deliberately contains no analysis of its own; anything that
looks like language knowledge in here is a bug or a `Handshake` request.
## Starting it: the argument contract
`lucisv-server` needs **no arguments** — that is the spawn every editor uses,
the one `editors/vscode/smoke.js` drives, and it is unchanged. Since
2026-08-29 it also *accepts* exactly one:
| argument | effect |
|---|---|
| *(none)* | The shipped server. Silent unless something is worth saying. |
| `--verbose` | Every operation says how long it took, as `timing:` lines in the client's log channel (`window/logMessage`, `MessageType::LOG`). Repeats are idempotent. See `docs/features/verbose-timing/README.md` |
| `--stdio` | Accepted and changes nothing: stdio is the only transport this server has. It is here because `vscode-languageclient` appends it for `TransportKind.stdio` — the spawn every real VS Code session makes — and rejecting it crashed the extension the moment strict parsing shipped (lead hotfix, 2026-08-29). The smoke and restart harnesses spawn the binary directly, which is why nothing in the loop caught it; `smoke.js` now spawns with `--stdio` so the library's real spawn shape stays covered. |
| anything else | `error: unknown option: <arg>` and `usage: lucisv-server [--verbose] [--stdio]` on **stderr**, exit **2** — the CLI's own wording and its "an error occurred" code. Nothing is started |
There is no `-v`, no `--help` and no `--version`: one spelling for the one
flag, and the version number lives on the `lucisv` CLI, which is where
`tools/release.sh` reads it. Anything that is not a startup decision is an
`lucisv.*` setting instead, pushed or pulled over the protocol — a flag can
only be changed by spawning again, which is why `lucisv.verbose` is the one
VS Code setting that restarts the server.
## Capabilities as shipped
| LSP request | Engine it consumes | Notes |
@@ -491,9 +511,12 @@ called by the request handler.
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
Result<String, FormatError>` and `Config { max_width, indent_width }`.
**Promised to nobody yet.** This crate is a leaf: it has no library target and
nothing depends on it. The editor packaging round (TODO.md §6) will consume
the binary's name and its stdio contract, nothing else.
**Promised to the editors:** the binary's name, its stdio contract, and — since
2026-08-29 — its *argument* contract: no arguments required, `--verbose` the
only one accepted, every other one refused with exit 2 (the table under
"Starting it" above; TOPO.md §1.2's `editors/vscode ◀──▶ lucisv_server` row;
`docs/features/verbose-timing/README.md`). Beyond that this crate is a leaf: it
has no library target and nothing in the workspace depends on it.
**Requested of other modules** — none of these block this round, and none was
done here:
+256 -9
View File
@@ -32,6 +32,9 @@ pub fn propagate_ports(files: &[(PathBuf, String)], file: &Path, offset: u32)
pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32)
-> Vec<PortAction>;
pub fn may_have_port_action(text: &str, offset: u32) -> bool;
// added 2026-08-28, for the server's file-set question:
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String>;
pub fn enclosing_module(text: &str, offset: u32) -> Option<String>;
```
`files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence
@@ -339,14 +342,85 @@ neither is offered where the refactoring would be refused. They answer for the
**start** of the requested range: a code action is about where the cursor is.
A code-action request arrives on **every cursor move**, and computing an
answer means reading the whole in-scope file set and building an index — a
fifth of a second on a large workspace, on a single-threaded server. So the
engine exposes a cheap one-file question, `may_have_port_action(text, offset)`:
one parse of the buffer itself, no workspace and no I/O, answering "is this
position inside a port element, a non-ANSI port declaration, or an
instantiation?". The server asks it *before* materializing anything. It cannot
hide a refactoring: all three start by locating exactly one of those three
constructs.
answer used to mean reading the whole in-scope file set and building an index
— a fifth of a second on a large workspace, on a single-threaded server, and
2.9 s on OpenTitan's 3 976 files, with every queued definition and hover
waiting behind it. Two things keep that off the cursor path, and both are the
engine's own walk:
- `may_have_port_action(text, offset)` — one parse of the buffer itself, no
workspace and no I/O, answering "is this position inside a port element, a
non-ANSI port declaration, or an instantiation?". The server asks it
*before* materializing anything. It cannot hide a refactoring: all three
refactorings start by locating exactly one of those three constructs.
- `port_action_modules(text, offset)` — the same walk saying *which* module it
found, so the server can hand the engine that module's own fan-out instead
of the workspace. `may_have_port_action` is this function asked for
emptiness (one walk, two readers), which is what keeps the gate and the
fan-out from ever disagreeing about which positions carry an action.
### The file set a port action reads — why a subset is the same answer
`Workspace::module_sources(file, modules)` (`lucisv_server/src/state.rs`)
builds the file set both `ports::code_actions` and `ports::execute` hand to the
engine. It is `sources()` narrowed to four rungs:
1. **the file the request names** — the open buffer's text, as always;
2. **every file declaring one of `modules`** — `index.units(name)`;
3. **every file that instantiates one** — `index.instantiations_of(name)` —
**or otherwise refers to one** — `index.references_to(def)`;
4. **every open buffer**, whatever it contains.
The answer is *equal* to the whole-workspace answer, and the argument is one
per way a file can influence the result:
- **A file the plan can edit.** `plan_add`/`plan_remove` loop over the whole
scope, but `instantiation_edits`/`disconnection_edits` write nothing in a
file that does not textually contain the module name and parse an
instantiation of it under `collect_instantiations`. That census — module
bodies, packages, nested modules, generate regions (`if`/`for`/`case`), and
`bind` — is walk-for-walk the one `vlog_semantic::instantiations::sites`
performs to record the index's instantiation edges, so rung 3 names exactly
the files that could gain or lose a connection. `plan_propagate` edits the
cursor's file alone. **One gap**: `edges_of` drops a site with no owning
module — an instantiation written at *file scope*, illegal SystemVerilog a
tolerant parse still produces — and the engine would have edited it. Rung 3's
second half covers it: an instantiation's module name is a
`Target::Module` reference wherever it is written, so the file appears in
`references_to` even when it is nobody's edge.
- **A file that decides `locate_module`'s verdict.** Every one of them is in
rung 2, *all* of them, so a module declared twice still produces the "lucisv
will not guess which module's ports these are" refusal instead of quietly
picking the one definer that happened to be in the set. Rung 2 is the reason
the set is built from `units(name)` rather than from a single definition.
- **A file the verifier watches.** `check::watched_files` widens verification
to every file spelling the module name, edited or not, and compares each
one's declarations and resolutions before and after. For a file that is not
edited, "before" and "after" differ only if some *anchor* moved — and an
anchor is a local declaration (its own text, unchanged) or a def in the
rebuilt index (pre-shifted through the edits by `Shifts`, which is why an
insertion in the module's file does not read as a difference). An anchor
that could move is by construction a reference *into* the edited module or
its members — which is a `references_to` posting, rung 3. Every other file's
print is identical on both sides whether it is in the set or not, so
omitting it cannot turn a refusal into an offer.
- **A file the index has not seen.** An unsaved buffer's live text can add or
remove any of the above, and the edges are only as fresh as the last save —
so rung 4 takes every open buffer whole, exactly as `collect_sources` does.
Everything else about the set is `collect_sources`'s rules unchanged: each
file's text is the open buffer's when there is one and disk otherwise, a
buffer on the large-file fast path contributes nothing, and a file over
`lucisv.index.maxFileSize` is not read.
Pinned by four tests in `lucisv_server/src/ports.rs`, each asserting against
the whole-workspace computation rather than a transcription of it:
`a_code_action_answers_what_the_whole_workspace_would`,
`an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen`,
`a_module_declared_twice_is_refused_through_the_subset_as_well`,
`a_command_computes_over_the_subset_and_answers_the_same`, plus
`the_files_a_code_action_reads_are_the_modules_own_fan_out`, which asserts the
noise files really are absent (4 files read of 44).
**Commands** (`workspace/executeCommand`, advertised in
`executeCommandProvider`):
@@ -390,7 +464,19 @@ engine's sentence verbatim, M2's precedent.
- **A port refactoring is a rare, user-initiated request**, so re-parsing the
in-scope files that mention the module (twice: once to plan, once to verify)
is affordable. The substring prefilter M2 introduced keeps it to a handful of
files. Measured below.
files. Measured below. **Amended 2026-08-28**: a *code action* is not rare —
it arrives on every cursor move — so the files handed to the engine are the
module's fan-out rather than the workspace (above).
- **The index is the server's authority on where a module is declared and
instantiated.** The fan-out is read from it, so a port action sees the
workspace as far as the index describes it: a file changed on disk with
nothing telling this server, or a file a startup scan has not reached yet,
is a file the action does not read. That is the same rule every other
index-backed answer already lives by — definition, hover, references, the
code lens, the call hierarchy — and the file watcher is what keeps it true.
Before 2026-08-28 a port action re-read the whole scope from disk and was
the one answer in the server that could see further than the index; it no
longer is.
- **Two spaces** are used for the one indentation lucisv has to invent (a body
declaration in a module with no items at all). Every other insertion copies an
indentation that is already in the file.
@@ -436,6 +522,27 @@ engine's sentence verbatim, M2's precedent.
- `warnings` are informational: an `Ok` with warnings is still safe to apply.
- `PortAction.title` is user-facing text; the server does not rewrite it.
**Consumed from `vlog_semantic`, added 2026-08-28** (no change required):
`WorkspaceIndex::{instantiations_of, references_to}` — the incremental-index
edge and posting tables — are what make the file set a lookup instead of a
workspace read. The equality argument above leans on one property of theirs:
`edges_of` records the census `instantiations::sites` walks, which is the walk
`ports::collect_instantiations` performs. If either walk grows a node kind the
other does not, the fan-out stops being a superset of the editable files —
so **they must move together**.
**Requested of `lucisv_server`'s rename surface (follow-up, not this round):**
`rename` and `prepare_rename` still call `ws.sources()` and run the engine
over every in-scope file. On the synthetic 504-file workspace the port probe
uses, `prepare_rename` costs **249 ms** (of which `sources()` alone is 14.5
ms — the rest is the index build and the analyses over every file);
`textDocument/prepareRename` is sent when the user presses the rename key, not
per cursor move, so it does not block the way the code action did. The subset
for a rename is a *different* argument from this one — a rename must see every
file that could name the symbol, and the postings table
(`references_to`/`references_are_ambiguous`) is the candidate — so it is filed
here rather than guessed at now.
**Changed in `lucisv_server`** (protocol layer only): `code_action::wanted` is
now `pub` so the port actions can honor the same `only` filter the lint actions
do; `server.rs` gained the `workspace/executeCommand` arm and the port-action
@@ -467,6 +574,11 @@ call inside the existing `textDocument/codeAction` arm; `main.rs` advertises
- [x] `lucisv_server`: code actions, three commands, capabilities
- [x] `may_have_port_action` — the one-file pre-check that keeps a
cursor-move-frequency code-action request off the workspace walk
- [x] The file set a port action reads is the module's fan-out through the
index, not `sources()` (2026-08-28): `port_action_modules` /
`enclosing_module` in the engine, `Workspace::module_sources` in the
server, one builder for both callers, with the equality argument above
and five equivalence tests
- [x] Conditional-compilation guard on both insertion paths: refuse inside an
arm, warn when the list carries directives at all (QA HIGH #1)
- [x] Preprocessor warnings on removal — macro-invocation arguments and
@@ -652,6 +764,62 @@ still `Ok((6, 18))` in 0.36 s, so the guard false-refuses nothing in real RTL.
One clippy-driven tidy while there: the header planner's arguments are now a
`File { text, path, tokens }` struct rather than eight positional parameters.
**2026-08-28 — dev agent.** `textDocument/codeAction` no longer reads the
workspace per cursor move. The owner's instrumented session on OpenTitan
measured 3 111 ms and 3 015 ms for a code action against 0.01–0.44 ms for
every other request; VS Code sends one on nearly every cursor move and the
server is single-threaded, so a cursor resting on an instantiation — which is
exactly where F12 leaves it — held every queued definition and hover behind
it. That is the "goto definition is slow" report: the definition answered in
microseconds and stood in a three-second queue.
What changed:
- **`vlog_refactor::port_action_modules`** — `may_have_port_action`'s walk,
returning the module names it found instead of a bool, and
`may_have_port_action` is now that function asked for emptiness. One walk,
two readers, so the gate and the fan-out cannot drift; a byte-by-byte
equality test over a mixed file pins the two against each other.
**`vlog_refactor::enclosing_module`** is the same question for the command
path, where `lucisv.addPort` takes a position anywhere in a module —
`module_at` made public, which is precisely what `ModuleRef::At` resolves
with, so the server names the module the engine will name.
- **`Workspace::module_sources`** — the one file-set builder, used by
`ports::code_actions` and by all three commands through `ports::sources_at`.
Four rungs and the equality argument are written up under "The file set a
port action reads" above; the two decisions worth repeating here are that
**all** definers of the name go in (or an ambiguous module would stop
refusing) and that `references_to` goes in beside `instantiations_of` (or a
file-scope instantiation, which records no edge, would stop being edited).
- Both callers share the builder, so there is no second code path with a
second answer; `execute` computes the names per command shape rather than
materializing anything before it knows what it was asked.
Measured, release:
| | before | after |
|---|---|---|
| synthetic 504 files, cursor on a port instantiated in 3 of them | 725 ms | **0.41 ms** |
| OpenTitan (3 976 files), cursor on a port of `adc_ctrl_core`, action offered | 4.56 s | **7.1 ms** |
| OpenTitan, cursor on a `prim_fifo_sync` instantiation (36-file fan-out) | 2.93 s | **83 ms** |
The last row is the honest ceiling: `prim_fifo_sync` is instantiated all over
OpenTitan, so its fan-out is 36 real files and the engine parses them twice
(plan, then verify) — 1.3 ms of that is reading them, the rest is the engine.
A module with a normal fan-out is the middle row. The synthetic probe is
`perf::a_code_action_at_an_instantiation_before_and_after`, which prints the
before column, the after column and `sources()` alone; the OpenTitan numbers
were taken with a throwaway probe against the local checkout and deleted, since
no test may depend on it. Both OpenTitan cursors were also checked for
*equality* against the whole-workspace computation — same titles, same edited
file counts — beside the five equivalence tests in the suite.
Deliberately untouched: `rename`/`prepare_rename`'s `sources()` calls, filed as
a Handshake follow-up with its number (249 ms on the synthetic workspace).
Gates: `cargo fmt` clean, `cargo clippy --all-targets` clean, `cargo test`
green workspace-wide, `node editors/vscode/smoke.js` OK against the release
binary.
## QA log
**2026-08-24 — QA agent.**
@@ -1179,8 +1347,87 @@ counts across all three QA passes are themselves evidence against scope
creep. The one imprecision found (over-broad trailing-directive warning
text) is cosmetic, safe-direction, and not blocking.
**2026-08-28 — QA agent.** Round on the codeAction-fan-out change: `Workspace::module_sources` replacing `ws.sources()` for `textDocument/codeAction` and the three port commands. Adversarial charter: find a file the whole-workspace computation would have edited (or that would change/refuse the answer) missing from the subset — refactoring correctness, invariant-1-adjacent.
### Gates
- `cargo fmt --all -- --check` — clean.
- `cargo clippy --all-targets` — clean, zero warnings, workspace-wide (one warning surfaced from a QA-added test — `map_or(true, …)` → `is_none_or(…)` — fixed directly, small and unambiguous).
- `cargo test --workspace` — green, **2482** passed, 0 failed, 0 measured (28 `#[ignore]`d perf probes not run) — includes the 6 permanent regression tests added this round (below). `lucisv_server`'s own unit suite: **1249** passed, 28 ignored. `vlog_refactor` unit: 72, `tests/ports.rs`: 52 (dev added 2: the byte-sweep pinning `may_have_port_action`/`port_action_modules` against each other, and `enclosing_module`'s own test).
- `node editors/vscode/smoke.js target/release/lucisv-server` — OK (had to pass the binary path explicitly; `lucisv-server` is not on `PATH` in this environment, not a project issue).
- Reproduced the synthetic perf claim exactly: `perf::a_code_action_at_an_instantiation_before_and_after` (`--release`) printed **724 ms → 409 µs**, `sources()` alone **14.4 ms**, `prepareRename` **250 ms** — matches the README's 725 ms / 0.41 ms / 14.5 ms / 249 ms table to the reported precision.
- Reproduced the OpenTitan claim's *shape* independently, with a throwaway probe (added to `perf.rs`, run, then reverted — not in the tree): cursor on a port of `adc_ctrl_core.sv` went **3.13 s → 3.17 ms**; cursor on a `prim_fifo_sync` instantiation (in `otp_ctrl.sv`, a different real fan-out site than the dev's) went **3.08 s → 84.6 ms** — both essentially the dev's numbers (4.56 s→7.1 ms; 2.93 s→83 ms) to within what a different instantiation site and a warm/cold FS cache would explain. Both probe cursors landed on offsets that produced 0 offered actions on *both* sides (an imprecise offset, not a bug), but the **parity held** (0 == 0) in both cases, which is the property that matters here. No test depends on the checkout, per the brief.
### Attack angles from the brief, and what I found
**1. Missing-file attacks — all held.** Wrote 4 new permanent regression tests attacking the exact scenarios the brief named, each asserting the subset's `code_actions`/`module_sources` answer against `whole_workspace_at` (the dev's own reference function) or `ws.sources()`:
- `qa_file_scope_instantiation_lands_in_the_subset` (`crates/lucisv_server/src/ports.rs`) — an owner-less instantiation (`sub u_fs (.clk(c), .rst(r));` at file scope, no enclosing module) records **no** `InstantiationEdge` (confirmed directly: `edges_of` requires an owner), yet the file lands in `module_sources` and the subset's answer matches the whole-workspace one exactly. This is the dev's rung-3-second-half claim (`references_to` catching what `instantiations_of` structurally cannot) — verified empirically, not just by reading `resolve.rs`'s `named_at_file_scope`/`bind_instantiation` code path that makes it true. This was the brief's most specific, most load-bearing ask ("verify it actually lands in `references_to`") and it does.
- `qa_generate_block_instantiation_lands_in_the_subset` — an instantiation inside a `generate for` body is a real `InstantiationEdge` (confirmed) and its file is in the subset, subset == whole-workspace.
- `qa_escaped_module_name_instantiation_parity_with_whole_workspace` — an escaped-identifier instantiation (`` \sub u_esc (...) ``). Whatever the parser/binder does with the escape (resolve it to `sub` or treat it as a distinct name — did not chase which, since it is a pre-existing lexical question this round did not touch), the subset and whole-workspace answers agree. Framed as a parity check rather than a correctness check of escaping itself, since a bug there would be M1/M2-era and out of this round's scope.
- `qa_add_port_by_position_still_fans_out_to_instantiation_files` — the dev's own equivalence test (`a_command_computes_over_the_subset_and_answers_the_same`) only exercises `lucisv.addPort` with a **module-name** argument, which reaches `module_sources` directly. The **Position** argument goes through a different function (`sources_at`, used by all three commands and by nothing else previously tested at the command layer) — confirmed it still reaches all 3 instantiating files, matching `ws.sources()`'s answer byte-for-byte.
- Not separately tested as a new attack, but read and reasoned through carefully: `.*` connections, hierarchical-reference-only files, and macro-expanded module names. `.*` sites are structurally ordinary `Instantiation` nodes to `edges_of`/`collect_instantiations` (connection *style* plays no part in either census), so they get the same edge as a named-connection site — no special case to miss. A file whose only relationship to the module is a hierarchical reference to one of its ports (no instantiation) is not in scope for *either* the old or the new computation (neither `collect_instantiations` nor `edges_of` would ever find or edit it), so it cannot be a point of divergence. A macro-expanded module name is one opaque token to lucisv's non-preprocessing binder in both the old and new code paths equally (documented Assumption, unchanged) — not a regression this round could introduce.
- Did **not** separately verify a duplicate-module-name-under-macro or a nested-module-inside-a-package instantiation; ran out of budget. Low-risk: `collect_instantiations`/`edges_of` both explicitly walk `ItemKind::Package{items,..}` identically (confirmed by direct side-by-side read of both functions, `crates/vlog_semantic/src/instantiations.rs:68-105` vs `crates/vlog_refactor/src/ports.rs:489-518` — they are the same match arms in the same order, which is exactly the Handshake's "walk-for-walk" claim, verified by inspection rather than by a fresh test).
**2. Refusal-parity attacks.**
- Duplicate-definer-already-indexed: the dev's own `a_module_declared_twice_is_refused_through_the_subset_as_well` covers this (re-ran, passes).
- New module in an **unsaved buffer the index has never heard of at all** (not stale — genuinely absent): `qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled` — a module declared only in a brand-new, never-saved-to-disk buffer, with the cursor inside that same buffer. Rung 1 ("the file the request names") is what carries it, since rung 2 (`index.units`) is empty for a name the index has never indexed. Confirmed it still offers the action correctly (`lucisv: remove port \`b\` (no instantiation in scope)`), no panic, no silent no-op.
- **Index stale vs. disk — the one place I judged rather than just tested.** `qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption`: wrote a *second* definer of `sub` straight to the filesystem, bypassing the server (`fs::write`, no `rebuild_index`, no `set_document`). Confirmed: the subset computation, unaware of the new file, does **not** refuse — it offers the action as if the module were still uniquely declared, which is a real, observable divergence from `ws.sources()`'s always-fresh-from-disk answer (the old code path *would* have refused here). Judged against invariant 1, not against freshness, per the brief's own framing: this cannot corrupt anything, because the engine is handed exactly the files in the subset and has no I/O of its own — `dupe.sv` is never read and never appears in the produced edit (asserted directly). The worst case is a **stale-but-internally-consistent** answer (an edit that is fully verified against the files it actually saw), not a wrong-and-unverified one. This is exactly the trade-off the dev's own Assumptions section documents ("the index is the server's authority... a file changed on disk with nothing telling this server is a file the action does not read") and explicitly parallels every other index-backed LSP answer in the server (definition, hover, references). I agree with the dev's framing: this is a disclosed staleness trade-off, not a hidden safety gap, and does not violate "never corrupt code." Confirmed the parity is restored the moment the index is told (`rebuild_index()` → refuses, matching whole-workspace).
**3. Gate ⟺ subset coherence — verified by direct code comparison, no divergence found.** `may_have_port_action` is now defined literally as `!port_action_modules(...).is_empty()` (`crates/vlog_refactor/src/ports.rs:159`), so the two cannot drift by construction; the only residual risk was a logic bug introduced while refactoring the original single-`bool` walk into a `Vec<String>`-returning one. Diffed the two versions line-by-line: the only structural change is `.any(...)` → `.filter(...).map(...).collect()` over the same predicate, which is behavior-preserving (a multi-match, if the tolerant parser ever produced overlapping instantiation spans, would just widen the returned module list — still correctly non-empty, never a false negative). The dev's own new test (`the_pre_check_names_the_module_whose_files_the_action_will_need`, `crates/vlog_refactor/tests/ports.rs`) sweeps every byte offset of a mixed file and asserts `may_have_port_action(text, offset) == !port_action_modules(text, offset).is_empty()` — re-ran it, passes. No old-vs-new crafted-file attack found a gate-false position the old whole-workspace path would have offered an action for, because the "old path" *is* this same walk (`may_have_port_action` was never a separately-maintained function — it's the same code, just newly able to say which module).
**4. Command parity — held**, including the position-argument case above (attack 1's `qa_add_port_by_position...` doubles as this). `REMOVE_PORT`/`PROPAGATE_PORTS` both go through `sources_at`, which unions `port_action_modules` (what the offset directly names — a port, or an instantiation's own module) with `enclosing_module` (the module the offset sits textually inside) — read `locate_module`'s `ModuleRef::At` (`ports.rs:379-413`) and `locate_port`/`plan_propagate`'s own module-name derivation to confirm `sources_at` always names a superset of what the engine will independently look up for each of the three commands; for `propagate_ports` specifically the extra `enclosing_module` name is unnecessary (the README says propagate only ever touches the cursor's own file) but harmless — it can only add files, never omit the one that matters.
**5. Verifier integrity.** Read this one by construction rather than by attack: `check::watched_files` and the whole verifier only ever see the files handed to `Scope::build(files)` — the crate does no I/O of its own (Handshakes, unchanged this round). So "an edit corrupts a file outside the subset" is not reachable as a distinct failure mode in this design: the engine cannot write to, or even read, a file that was never in the set. The only failure mode a wrong subset can produce is the one attack angle 1 covers (a file that *should* have been edited is silently skipped) — which is why I put the budget there instead of trying to construct a doomed "verifier misses an out-of-subset corruption" scenario that the architecture rules out by construction.
### Tests added (all permanent, all in `crates/lucisv_server/src/ports.rs`'s `mod tests`)
`qa_file_scope_instantiation_lands_in_the_subset`, `qa_generate_block_instantiation_lands_in_the_subset`, `qa_escaped_module_name_instantiation_parity_with_whole_workspace`, `qa_add_port_by_position_still_fans_out_to_instantiation_files`, `qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled`, `qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption`. No probe files left in the tree; the only non-test-only edit was the `map_or` → `is_none_or` clippy fix inside my own new test code (nothing in the dev's code touched).
### Summary
| Claim | Verdict |
|---|---|
| `cargo fmt`/`cargo clippy`/`cargo test --workspace`/smoke | **Pass** |
| File-scope (owner-less) instantiation lands in the subset via `references_to` | **Pass, confirmed empirically** — the brief's most specific ask |
| Generate-block instantiation, escaped-identifier parity | **Pass** |
| `ModuleArgument::Position` (not just `Name`) still fans out correctly | **Pass, confirmed** — previously untested combination |
| Ambiguous-module refusal, via the index | **Pass** (dev's own test, re-verified) |
| Unsaved brand-new module (index has never heard of it) | **Pass** |
| Index stale vs. disk (duplicate definer unindexed) | **Behaves as documented**: a stale-but-verified answer, never a corruption; matches the Assumptions section's own framing |
| Gate (`may_have_port_action`) ⟺ fan-out (`port_action_modules`) coherence | **Pass, verified by construction + the dev's byte-sweep test** |
| Command parity across all three commands | **Pass** |
| Verifier cannot touch a file outside the subset | **True by construction** (no I/O in the crate) |
| Perf claims (synthetic + OpenTitan) | **Reproduced**, synthetic to the reported precision, OpenTitan to the same order of magnitude on different cursor sites |
No corruption, no false refusal, no lost feature, and no missing-file divergence found anywhere I could construct one. The one real, novel-to-this-round behavior change (index staleness vs. `sources()`'s always-fresh disk read) is pre-existing in spirit everywhere else in the server, is disclosed prominently in the feature's own Assumptions section, and cannot produce a corrupt edit by the crate's own no-I/O architecture — so I am not filing it as a finding, only recording that I attacked it deliberately and it held.
**Verdict: SHIP.** No blocking or non-blocking findings this round.
## Review
**2026-08-28 — lead, codeAction fan-out round.** Reviewed after QA's
clean SHIP; gates re-run independently (fmt clean, clippy silent, 2482
workspace tests green). This closes the owner's original report from
the root: the "slow F12" was a 3–4.5 s codeAction on every cursor move
blocking the single-threaded loop, and the fix is the house pattern —
the index's fan-out instead of `ws.sources()` — with the sufficiency
argument written before the speed was trusted. The dev's fourth rung
(`references_to`, because `edges_of` drops owner-less file-scope
instantiations) is exactly the kind of gap that separates a subset from
a superset, found by reading rather than by failing; QA confirmed it
empirically and pinned it. The one behavior change — a port action now
sees the workspace as the index describes it, so an unindexed on-disk
duplicate yields a stale offer instead of a fresh refusal — is
disclosed in Assumptions, cannot corrupt (the engine does no I/O of
its own; QA proved the untouched file untouched), and aligns this
answer with every other index-backed one. 4.56 s → 7.1 ms on
opentitan, 83 ms honest ceiling at a 36-file fan-out, both reproduced
by QA on different cursors. The prepareRename follow-up (250 ms on the
synthetic; 2.5–3 s measured on opentitan in performance.md) is Lane A
of the performance wave. Accepted; committed by the lead.
**2026-08-24 — lead.** Reviewed after QA round 2's ship verdict; gates run
independently (1170 tests, 0 failures, clippy silent). The splice verifier
plus per-feature shape check is the right division — the verifier stays
+868 -1
View File
@@ -29,6 +29,12 @@ pub fn prepare_rename(files: &[(PathBuf, String)], file: &Path, offset: u32)
-> Result<RenameTarget, String>;
pub fn rename(files: &[(PathBuf, String)], file: &Path, offset: u32, new_name: &str)
-> Result<RefactorEdit, String>;
// Added 2026-08-28 (the performance wave). Same question, no file set.
pub fn prepare_rename_here(semantics: &Semantics, external: &ExternalResolutions,
index: &WorkspaceIndex, offset: u32)
-> Result<RenameTarget, String>;
pub fn rename_name_at(semantics: &Semantics, offset: u32) -> Option<String>;
```
`files` is **the boring option**: the in-scope files as `(path, text)` pairs —
@@ -47,6 +53,15 @@ Deviations from the milestone sketch, and why:
parameter would be cast at both ends of every call.
- **`prepare_rename` returns a `RenameTarget`**, not a bare range: the editor
wants the placeholder too, and it is the identifier's own text.
- **`prepare_rename_here` takes an analysis rather than a file set** (added
2026-08-28). The server already holds every argument it needs for the open
buffer, so this asks nothing of the filesystem; `prepare_rename` stays as
the whole-workspace oracle the parity tests measure it against. See "The
file set a rename reads" below.
- **`rename_name_at` decides nothing.** It answers only "which identifier is
under this cursor", which is what the server needs to ask the index for the
fan-out. Every refusal stays with `rename`, which is the call that has the
files; a second opinion here could only disagree with it.
## What can be renamed
@@ -131,6 +146,300 @@ shape for refactorings).
needs to decide whether to open the rename box at all: everything else needs a
new name to judge.
## The file set a rename reads (2026-08-28)
Until this round both entry points were handed `Workspace::sources()` — every
in-scope file, read from disk — and built a whole `WorkspaceIndex` over it
before answering anything. On OpenTitan (3 976 files) that cost **1.7–3.0 s
for `prepareRename`** and **3.2–8.7 s for `rename`**, on a single-threaded
server where everything the editor sent next waited behind it. `prepareRename`
is what the rename key sends *before the box opens*, so those seconds were a
frozen editor on a keypress that had committed to nothing.
Two different fixes, because they are two different questions.
### `prepareRename`: the buffer already holds the answer
The question is "is this a renameable symbol, and what are its range and
placeholder". `prepare_rename_here` answers it from the open buffer's own
`Semantics`, the `ExternalResolutions` overlay the server keeps beside it, and
the index — **no file is read and nothing is parsed**. Measured: 238 ms →
**200 ns** on the synthetic 504-file workspace, 1.604 s → **135 ns** on
OpenTitan.
#### Refusal-by-refusal parity
Every refusal `prepare_rename` can produce, and what the cheap path does with
it. Deferring a refusal to `rename` is allowed — LSP explicitly permits an
optimistic `prepareRename` — and losing one is not: a deferred refusal is
still delivered, in the same words, by the `rename` that follows.
| # | Refusal (its own sentence) | Where it comes from | Cheap path |
|---|---|---|---|
| 3 | *"… is not one of the files lucisv indexes …"* | the request's file absent from `files` | **unreachable either way.** `sources()` contains every open buffer with a path, and this handler is only reached for one; a fast-path (large) buffer is refused by `server.rs` before it gets here. |
| — | *"the file could not be analyzed."* | `Scope::analysis` of an in-range index | **dead code in both**: the index came from `index_of`, so the lookup cannot miss. |
| 4 | *"there is no symbol to rename at this position."* | no reference and no symbol at the offset | **reproduced** — `reference_id_at` / `symbol_at` on the buffer. |
| 5 | *"… is not resolved to any declaration …"* | `Resolution::NotFound` | **reproduced** — single-file resolution, in the buffer. |
| 6 | *"… could only come from the base class `B` …"* | `Resolution::InheritedCandidate` | **reproduced** — same. |
| 7 | *"… is declared outside the files lucisv indexes …"* | `ExternalTarget::StillUnresolved` / absent | **reproduced** — the overlay is `resolve_external` against this same index, which is the call `Scope::declaration_across_files` makes. |
| 8 | *"… is declared in more than one indexed file …"* (from a cross-file use) | `ExternalTarget::Ambiguous` | **reproduced** — same overlay. |
| 9 | *"… is declared in more than one indexed file …"* (from the declaration) | `declaration.scope == file_scope && index.units(name).len() > 1` | **reproduced** — the buffer knows the scope, the index knows the count. |
| 11a | *"lucisv cannot find where `x` is spelled in its declaration …"*, declaration **in this buffer** | empty `name_span` | **reproduced.** |
| 11b | the same sentence, declaration in **another** file | that file's fresh `name_span` | **deferred.** The index only ever records a non-empty span, so this can only fire on a file whose analysis disagrees with the index — which means reading it. |
| — | *"`x`'s declaring file is not in scope."* | `index_of` on the declaring path | **deferred** (and unreachable in practice: `sources()` is a superset of the index's files). |
| — | *"the declaring file could not be analyzed."* / *"lucisv cannot locate the declaration of `x`."* | the declaring file's own analysis | **deferred**, same reason. |
| 1, 2, 10, 12, 13 | new-name validity, same name, ambiguous use onto this declaration, capture, token drift | — | **not `prepare_rename`'s at all**; they always were `rename`'s. |
Pinned by `rename::tests::the_buffer_answers_a_prepare_exactly_as_the_workspace_does`
and its five siblings, which ask both entry points the same question at **every
byte** of hostile buffers — packages and qualified names, a name declared
twice, nothing resolving, generate blocks and macros, a file that does not
parse — and fail on any reworded refusal, any different answer, and any
refusal the cheap path *invents*. Deferrals are counted, never asserted away.
**The one divergence, stated exactly.** Rule 9's count comes from the index,
and the index is rebuilt on save, not on keystroke (`state.rs`), so an unsaved
edit that adds or removes a file-scope declaration of the name is not in it.
`prepare_rename` counts the same declarations over the *current* texts. Both
directions are possible in principle; both are the ordinary index-staleness
window every other index-backed answer in this server lives in, and the
sentence itself says "indexed file". `rename` re-derives the count from the
current texts and is the authority.
### `rename`: the symbol's fan-out, and why it is enough
`Workspace::rename_sources` (state.rs) builds the file set from what the index
already holds. Its rungs, for the request's file, every open buffer, and each
spelling `N` in `{old_name, new_name}`:
1. **every file declaring `N`** — `WorkspaceIndex::workspace_symbols(N)`
filtered to the exact name, which covers units *and* members (ports,
parameters, package and class members);
2. **every file the index recorded a use of one of those declarations in** —
`references_to(def)`, for **every** such declaration, not only the target's;
3. **every file instantiating `N`** — `instantiations_of(N)`;
4. **every file whose `` `define`` table names `N` or spells it in a macro
body** — a walk over the `DefineTable`s the index already holds (no file is
read), asking the same `vlog_refactor::contains_word` that
`Scope::define_sites` decides with, so the fan-out and the warning cannot
disagree about which files carry one;
5. **the units that export `N` as a member**, and every file declaring,
referring to or instantiating one of them — how a third file's `.N(...)`
connection or `u::N` is reached.
and, for the **new name only**, a sixth:
6. **every file that spells the new name in a use this workspace had to look
outside that file to answer — including the uses it could not answer at
all** — `WorkspaceIndex::files_spelling(N)`, a walk over the per-file
records (no file is read, nothing is parsed). Rungs 1–5 are all keyed by a
*declaration*, and a use that resolved to nothing has no declaration to be
keyed by; this is the rung that finds it. Why only the new name needs it is
argued under "The dangling-use case" below.
Rung 6 is the only one whose cost grows with the workspace rather than with
the symbol, so it is measured on its own: **852 µs on OpenTitan's 3 976 files
in the worst case** — a name nothing spells, where the walk cannot
short-circuit — and 402 µs for `clk_i`, which 681 files spell. Building the
whole file set is 4.75 ms, most of it the other five rungs'
`workspace_symbols` scan and `` `define`` walk. Against a rename that costs
105 ms and used to cost 3.5 s, a sub-millisecond linear scan is the boring
implementation and stays one; a name-keyed side map is the fallback if a
workspace ever makes it visible, and nothing measured here comes close.
#### The sufficiency argument
**Lemma (name-locality of resolution).** A reference spelling `N` is resolved
by `vlog_semantic::follow_paths`, which tries the reference's recorded paths in
order and, for each, calls `follow_one` — and `follow_one` returns either
`index.units(N)` or `index.member(u, N)` for some unit name `u`. **Both are
keyed by `N`, and both are contributed only by files that declare the name
`N`** (as a unit, or as a member of some unit). Rung 1 puts every one of those
files in the set. Therefore, for every path list and every unit name,
`follow_one(subset, N, ·) == follow_one(whole, N, ·)`, so
`follow_paths(subset, N, ·) == follow_paths(whole, N, ·)`: **every reference
spelling `N` resolves in the subset exactly as it resolves in the whole
workspace.** ∎
Three consequences, which are the three things that could have gone wrong:
- **No missed edit.** `Scope::collect_occurrences` emits a span in file *i*
only when *i* is the declaring file, or when a reference in *i* spelling the
old name resolves to the target declaration. The declaring file is rung 1.
A file with such a reference resolves the same way in the whole workspace
(Lemma), so the index recorded a posting for it — rung 2. Hence every file
the whole-workspace rename would edit is in the set. This is the
invariant-1 claim, and it is asserted directly, not only through an
equality, by `every_file_the_workspace_rename_edits_is_in_the_fan_out`.
- **No extra edit.** The converse of the same Lemma: a file in the subset
cannot resolve a reference *onto* the target that the whole workspace
resolves elsewhere. Without rung 1 this was a live corruption route — drop
the file declaring `p::x` and a `p::x`/`q::x` reference would fall through
to `q::x` and be renamed — which is why rung 1 is `workspace_symbols` and
not `units`.
- **The verifier keeps its reach.** `check::watched_files` watches every file
spelling the old *or the new* name. In the subset it can only watch what it
was given, so the new name gets rungs 1–6 of its own — which is what keeps
refusal 12 (capture) alive: `the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere`
builds exactly the third file whose existing reference the rename would make
ambiguous, and the subset holds it because it is in the *new* name's
postings.
#### The dangling-use case, and why the sixth rung is the new name's alone
The Lemma settles what a name *resolves to*. It does not by itself settle
which files hold a use of that name, and rungs 1–5 answer that question only
through declarations: a file is in the set because it declares the name,
because a posting keys it to a declaration of the name, because it
instantiates the name, because a macro table mentions it, or because it names
the unit that exports it. **A use that resolved to nothing is keyed by
nothing.** `merge_references` drops a `StillUnresolved` result rather than
posting it, which is correct for `references_to` — there is no declaration to
post it against — and is exactly the hole.
That hole is real and it costs a *refusal*, not a warning. Take
`import taken_pkg::*` in a file with no other tie to the rename: today it
resolves to nothing, and `check::print` records `Anchor::Unresolved`. Rename a
package to `taken_pkg` and the same use resolves — `Anchor::External` — which
is a changed meaning in a file the rename never edits, and refusal 12 exists
to refuse exactly that. QA found this on 2026-08-28 and reproduced it; the
lead ruled it not shippable, and rung 6 is the fix.
**The old name has no analogous case, and this is why.** A rename only ever
*removes* declarations of the old name — it renames them away — and never adds
one. So for a use spelling the old name:
- if it **resolves**, its declaration is one of the declarations of the old
name, so the file is in `references_to` of that declaration — and rung 2
walks *every* declaration of the name, not only the target's. Already in the
set.
- if it **resolves to nothing**, it still resolves to nothing afterwards.
`follow_one` looks the name up in `units(old)` and `member(u, old)`; the
rename only takes entries out of those, and a lookup cannot start succeeding
because a candidate was taken away. `Anchor::Unresolved` before,
`Anchor::Unresolved` after — nothing for the verifier to see, so nothing
lost by not reading the file.
- if it **resolves ambiguously**, the escape hatch below fires and the whole
scope is handed over anyway.
Pinned from both ends: `a_dangling_import_of_the_new_name_is_refused_by_both_paths`
(the new name's case, now parity rather than a disclosed gap) and
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own` (the old name's,
which asserts both that the new-name rung fires when the dangling spelling is
the *destination* and that nothing is pulled in when it is merely a bystander).
#### The escape hatch
Refusal 10 — *some other reference resolves ambiguously onto this
declaration* — is the one the postings cannot locate: an ambiguous use is
recorded against the declarations it could name (`references_are_ambiguous`)
and **not** against the file that writes it. Rather than lose that refusal,
`rename_sources` hands back the whole `sources()` the moment the index says
**any** declaration of either spelling is ambiguously referenced. Correct and
slow beats fast and silent. Pinned by
`an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope`.
**How often it fires, measured.** On OpenTitan the `aes` and `clk_rst_if`
cursors narrow to 7 and 114 files of 3 976; a cursor on a `.clk_i` port
connection falls back to all 3 976 — some declaration named `clk_i` somewhere
in the checkout is ambiguously referenced, and the hatch is deliberately
asked about *every* declaration of the name rather than about the target
alone. The answer is still right there (edits identical, all 652 warnings
identical); it is simply not faster. **The obvious narrowing — ask only about
the declaration the cursor resolves to, which is the only one refusal 10
tests — is left for a later round on purpose**: it needs the target `Def`
identified server-side, which reintroduces the buffer-staleness question the
rest of this design keeps on one side of a line. Filed, not guessed at.
#### The staleness premise, stated exactly
> The index is the server's authority on which files declare a name and which
> files use it. A file changed on disk with nothing telling this server — no
> save, no watcher event, no rescan — or a file a startup scan has not reached
> yet, is a file a rename does not read. **Open buffers are the one exemption:
> every open buffer is in the set whatever the index holds, and the engine
> re-analyzes it from its current text, so unsaved edits are seen in full.**
This is the same rule definition, hover, references, the code lens and the
call hierarchy already live by, and the file watcher is what keeps it true. It
is what the port refactorings adopted on 2026-08-28, one round earlier. What
it costs a rename specifically: a reference living only in a file whose disk
copy moved unseen is a reference the rename does not rewrite **and cannot
refuse over** — `check::verify` re-analyzes the subset, so a file outside it
is not compared before and after. Before this round `rename` was, with
`prepareRename` and the port actions, one of the few answers in this server
that could see *further* than the index; it no longer is.
#### The residue — what the subset cannot see
Written out rather than argued away. Each of these is a file whose only
mention of a name is something the index records no declaration, posting,
instantiation edge, macro definition or external-reference fact for. **After
the 2026-08-28 rework there is exactly one, and it costs a warning — no edit
and no refusal:**
- **One warning flavour, and it is the loudest item on this page — measured,
not hypothetical.** `Scope::warnings` produces three sentences. Two are read
off a file's `` `define`` table (*"`x` is also a macro defined at …"* and
*"`x` appears in the body of macro `M` …"*) and **both survive**: the index
holds every file's table, and rung 4 walks it
(`the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read`).
The third comes from a **macro invocation whose arguments spell the name**,
and that one needs the file's token stream. A file outside the fan-out no
longer produces it.
On the real OpenTitan checkout, at two cursors, with **no edit lost at
either**:
```
aes -> aes_core_top edits identical (7 files, 7 edits)
warnings 7 -> 0, every one of them a
macro-invocation sentence:
`aes` in the arguments of `CONNECT_TL_DEVICE_IF`
at tb__xbar_connect.sv:30 and :47 (twice),
`DRIVE_CHIP_TL_DEVICE_IF` at :97, :140, :161,
`uvm_error` at keymgr_dpe_scoreboard.sv:644
clk_rst_if -> clk_rst_thing edits identical (114 files, 275 edits)
warnings 64 -> 61, the three lost being
`uvm_fatal` invocations
```
Those macro invocations really do still spell the old name after the
rename, and saying so is the whole point of the warning.
`tb__xbar_connect.sv` mentions `aes` **only** inside macro-invocation
tokens, and the index models those in no table at all: a macro invocation is
one opaque token, contributing no declaration, no reference, no
instantiation edge and no define entry, so nothing short of reading and
lexing the file can find it.
**This is a lead decision, and it is stated here rather than buried.** The
narrowing costs no edit and no refusal — the same runs assert the edit sets
byte-identical — but it costs the user a real piece of news. Recovering it
as things stand means running the warning pass over `sources()` while the
edits and the verification run over the fan-out: at least the 200–241 ms
workspace read plus a `tokenize` of every file spelling the name, which is
most of the win this round is for. The right answer is a
**macro-invocation census in `FileFacts`**, which would make this rung an
index lookup like the other five; that is a `vlog_semantic` change, and it
is filed as a request below rather than guessed at here.
- **No lost refusal.** The first draft of this round had one — a file whose
only mention of the new name was a use that resolved to nothing — and it is
**closed**, by rung 6. See "The dangling-use case" above for the argument
and the two tests. It is recorded here rather than deleted because the
shape is worth remembering: every rung keyed by a *declaration* is blind to
a use that has none, and a rename's whole job is to change which
declarations exist.
- **Nothing else.** A file whose occurrences of either name are strays — a
comment, a string, a local declaration inside a module, a hierarchical tail
— resolves identically before and after the edit, so the whole-workspace
verifier had nothing to say about it either.
The alternative considered and not taken: hand the engine the whole file list
but a *prebuilt* index, which narrows nothing and would still cost the
`sources()` read (200–241 ms on OpenTitan) plus an index clone. It is recorded
here so the choice is visible rather than implied.
## The verification story
Two independent checks, both run in memory on the edited text, before
@@ -230,7 +539,18 @@ implemented:
the index's `FileId`s describe the same texts.
- A rename is a rare, user-initiated request, so re-analyzing candidate files
twice (once before the edit, once after) is affordable. No caching, no
incrementality.
incrementality. **Amended 2026-08-28**: a *prepareRename* is not rare — it
is what the rename key sends before the box opens — and "the candidate
files" is now the symbol's fan-out through the index rather than the whole
scope. See "The file set a rename reads".
- **The index is the server's authority on where a name is declared and
used** (2026-08-28). The fan-out is read from it, so a rename sees the
workspace as far as the index describes it: a file changed on disk with
nothing telling this server, or one a startup scan has not reached, is a
file the rename does not read. Open buffers are exempt — every one of them
is in the set whatever the index holds. The exact premise, what it costs and
what it does not, is written out under "The staleness premise, stated
exactly".
- Refactored output is *edited source*, not reformatted source (umbrella
Handshakes): the edits are minimal, and the user runs the formatter
separately.
@@ -256,10 +576,64 @@ implemented:
ranges that slice back to the name — every edit span is one of these, and
the engine re-checks the slice before emitting it.
**Consumed from `vlog_semantic`, added 2026-08-28** (no change required):
`WorkspaceIndex::{workspace_symbols, references_to, references_are_ambiguous,
instantiations_of, defines}` — the posting, edge and macro tables — are what make
the rename's file set a lookup instead of a workspace read. The sufficiency
argument leans on one published property of theirs, and it is worth naming so
it moves under supervision: **`references_to`'s postings are built by
`merge_references`, which resolves each recorded reference with the same
`follow_paths` `resolve_external` uses.** If those two ever stop being the one
function, the postings stop being a superset of the files a rename must edit.
The same goes for `workspace_symbols` covering both the `units` and the
`members` tables: rung 1 of the fan-out *is* that coverage.
**Changed in `vlog_semantic`** (lead-authorized 2026-08-28 after QA, strictly
additive — the second such change this feature has made, the first being M2's
`Target::Declaration`):
- **`WorkspaceIndex::files_spelling(name) -> impl Iterator<Item = FileId>`** —
every file holding an external reference *fact* spelling `name`, resolved or
not. New query, no new state, no format change: it reads the
`FileFacts::references` records the index already keeps, and
`FACTS_FORMAT` is untouched. Logged in `docs/features/vlog-semantic/README.md`'s
work log, as M2's change was.
- **Why it had to live there.** The records are `pub(crate)`, and the question
— "which files hold a use spelled `N` that this index had to look outside
that file to answer" — is a question about the index's own tables. The
alternative was for the server to re-derive it by reading and analyzing
files, which is the workspace read this whole round removes.
- **The contract it carries:** `references_to` is keyed by the declaration a
use *landed on*, so a use that landed on nothing is in no posting.
`files_spelling` is the same records asked by spelling instead, which is
what makes it answer for the unresolved ones. If `facts_from_analysis` ever
stops recording an unresolved external candidate — today it records every
`ExternalCandidate`/`InheritedCandidate` with a non-empty path list — rung 6
stops closing the dangling-use case and this section must be re-read.
**Promised to `lucisv_server`** (and to any future CLI):
- `rename` never panics and never returns a partial edit: `Ok` means every
edit in it verified together, `Err` means nothing at all is to be applied.
- `prepare_rename_here` refuses in the *same sentences* `prepare_rename` does,
or defers to `rename`; it never invents a refusal `prepare_rename` would
not have made. The parity table above is the contract, and the byte-by-byte
parity tests are the enforcement.
- `rename_name_at` names the identifier `prepare_rename`'s `RenameTarget`
would name, at every offset where `prepare_rename` answers at all
(`the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on`).
**Requested of `vlog_semantic` (filed 2026-08-28, not taken):** a
**macro-invocation census in `FileFacts`** — per file, the macro invocations
it writes and the identifier-shaped words in their arguments. It is the one
piece of the rename's warning set the index cannot answer, and its absence is
the measured residue above: on OpenTitan, renaming `aes` loses seven
"`aes` appears in the arguments of the macro invocation …" warnings because
the files holding them contribute nothing else about `aes`. The census would
be one more `Vec` on a record `FACTS_FORMAT` already versions, read off the
token stream the parse already produced, and it would turn
`Scope::macro_use_warnings` from a workspace lex into a lookup — for the port
refactorings' identical scan as much as for this one.
- `RefactorEdit.edits` is sorted by path; each file's edits are sorted by
start offset, non-overlapping and non-empty.
- `warnings` are informational only — an `Ok` result with warnings is still
@@ -312,6 +686,19 @@ a much larger change than an end label and is not part of M2.
- [x] Tests: 64 in `vlog_refactor` (14 unit incl. 8 masked-corruption attacks,
48 behavior, 2 corpus), 3 new in `vlog_semantic`, 8 in `lucisv_server`
(7 in `rename.rs`, 1 capability), 1 e2e session
- [x] `prepareRename` answered from the open buffer and the index rather than
from `sources()` (2026-08-28): `prepare_rename_here` in the engine, the
refusal-by-refusal parity table above, and six byte-by-byte parity
suites against `prepare_rename` as the oracle
- [x] `rename` computed over the symbol's fan-out rather than the whole scope
(2026-08-28): `Workspace::rename_sources` in the server,
`rename_name_at` in the engine, the sufficiency argument above, the
ambiguity escape hatch, and equivalence tests over hostile workspaces
- [x] The dangling-use rung (2026-08-28, QA-driven rework):
`WorkspaceIndex::files_spelling` and rung 6 of the fan-out, applied to
the new name, which closes the one refusal the first draft lost. The
old name's exemption is argued under "The dangling-use case" and pinned
by its own test
- [ ] Deferred: rename in comments and strings (rope's `docs=True`) — the
umbrella lists it as an option, off by default, "until asked for"
- [ ] Deferred: renaming a module together with its file
@@ -473,6 +860,158 @@ Checks after the rework: `cargo fmt --all -- --check` clean,
`cargo clippy --all-targets` zero warnings workspace-wide,
`cargo test --workspace` green at 1085 tests (was 1072).
**2026-08-28 — dev agent (performance wave, Lane A).** The rename family stops
reading the workspace. `performance.md`'s two worst rows were
`textDocument/rename` (3.6–8.7 s) and `textDocument/prepareRename`
(2.5–3.0 s), both of them `ws.sources()` followed by a whole `WorkspaceIndex`
build; the measurer's own push-back — that `prepareRename` is what the rename
key sends *before the box opens*, not a rare user gesture — is the framing
this round took.
Everything argued under "The file set a rename reads" above. The decisions
worth repeating here:
- **`prepare_rename_here` takes an analysis, not a file set.** The server
already holds the buffer's `Semantics`, its `ExternalResolutions` overlay
and the index, and the overlay is `resolve_external` against that same
index — which is the exact call `Scope::declaration_across_files` makes. So
every refusal that depends on *which* declaration a use names is reproduced
rather than approximated, and only the four that need the declaring file's
own text are deferred. `prepare_rename` stays, as the oracle the parity
tests measure against; the refusal sentences were factored into five
functions so the two paths cannot word one situation two ways.
- **The fan-out's first rung is `workspace_symbols`, not `units`.** This is
the rung the whole equality argument turns on and the one that was easy to
get wrong: `follow_paths` looks a reference's *own* name up, in `units(N)`
or `member(u, N)`, and both tables are contributed only by files that
declare the name `N`. Drop the file declaring `p::x` from the set and a
reference with paths `[p::, q::]` falls through to `q::x` and is renamed —
an *over*-edit, corruption in the direction nobody looks. With rung 1 in
place the Lemma makes the subset's resolution of every reference spelling
either name identical to the workspace's, which is what buys "no missed
edit" and "no extra edit" at once.
- **The new name gets the whole fan-out too**, or refusal 12 (capture) dies:
the file whose existing reference a rename would make ambiguous is in the
*new* name's postings and in nothing of the old name's.
- **The ambiguity escape hatch.** An ambiguous use is recorded against the
declarations it could name, never against the file that writes it, so
refusal 10 cannot be reached from a subset. `rename_sources` hands back
`sources()` when the index reports one. Slow and correct beats fast and
silent.
- **`willRenameFiles`** got the same treatment through the include graph —
written up in `docs/features/file-operations/README.md`, including the
four-line `IncludeGraph::includers` accessor, which is the one file this
round touched outside its stated scope and is flagged there for the lead.
Measured, `--release`, and the equality checked as well as the clock:
| | before | after |
|---|---:|---:|
| OpenTitan (3 976 files), `prepareRename` on the `aes` instantiation | 1.663 s | **139 ns** |
| OpenTitan, `rename` of `aes` (7 files edited) | 3.467 s | **105.5 ms** (7-file fan-out) |
| synthetic 504 files, `prepareRename` on a module name | 251 ms | **212 ns** |
| synthetic 504 files, `rename` (4 files edited) | 486 ms | **370 µs** |
(All four re-taken after the 2026-08-28 rework below, so the table describes
the shipped code. The earlier round measured 1.604 s → 135 ns, 3.284 s →
103.6 ms, 238 ms → 200 ns and 465 ms → 294 µs on the same corpus: the sixth
rung is inside the noise, which is what the separate rung measurement above
says directly.)
The OpenTitan numbers were taken with throwaway probes against the local
checkout and deleted — no test may depend on it. The reproducible probe is
`perf::a_rename_before_and_after`. The throwaway also swept **every 7th byte
of `tb.sv`** comparing `prepare_rename_here` against `prepare_rename`: **564
offsets, all identical, zero deferrals** — the parity table's contract holding
over real code, not only over the six synthetic buffers in the suite.
**What the OpenTitan sweep found, and it is not nothing.** At the `aes` cursor
the two edit sets are byte-identical (7 files) and the *warnings* are 7 → 0:
`tb__xbar_connect.sv` and `keymgr_dpe_scoreboard.sv` spell `aes` only inside
macro-invocation tokens, which the index does not model in any table. Written
up in full under "The residue", with the cost of recovering it and a filed
request for the `FileFacts` macro-invocation census that would make it a
lookup. **It is a lost warning, never a lost edit or a lost refusal, and it is
the lead's call at review** — the honesty gate the brief asked for.
Deliberately not done: `check::watched_files` still sweeps the file list it is
given with `contains_word`, which is now the fan-out rather than the
workspace; no attempt was made to narrow it further, because it is O(files in
the set) over text already in memory.
Gates: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` clean
workspace-wide, `cargo test --workspace` green, `node editors/vscode/smoke.js`
OK against the release binary.
**2026-08-28 — dev agent (QA-driven rework: the lost refusal is closed).** The
lead ruled the round's "one lost refusal" residue not shippable — *a silently
weaker refusal is not a residue we ship* — and directed the fix. QA had found
it, reproduced it and pinned it as
`known_residue_a_dangling_import_of_the_new_name_is_a_lost_refusal`; that test
is now `a_dangling_import_of_the_new_name_is_refused_by_both_paths` and
asserts parity through `same_answer` instead of pinning the divergence.
The diagnosis, which is what makes the fix a rung rather than a patch: **rungs
1–5 are every one of them keyed by a declaration.** A file is in the set
because it declares the name, because a posting keys it to a declaration of
it, because it instantiates it, because a macro table mentions it, or because
it names the unit exporting it. A use that resolved to *nothing* has no
declaration to be keyed by — `merge_references` drops a `StillUnresolved`
result rather than posting it, correctly, since there is nothing to post it
against — and a rename's whole job is to change which declarations exist. So
`import taken_pkg::*` of a package nobody declares yet was invisible to the
fan-out and became meaningful the moment the rename landed, which is exactly
what capture rule 12 refuses over.
What changed:
- **`WorkspaceIndex::files_spelling(name)`** — one additive, lead-authorized
`vlog_semantic` query: every file holding an external reference *fact*
spelling the name, resolved or not. No new state, no new field,
`FACTS_FORMAT` untouched; it reads the `FileFacts::references` records the
index already keeps, which is the only reason the answer is available at all
without reading files. Logged in `docs/features/vlog-semantic/README.md`'s
work log as M2's `Target::Declaration` was, and the recording rule it rests
on is written into both Handshakes sections so it moves under supervision.
- **Rung 6 of `Workspace::rename_sources`**, `want_spellers`, applied to the
**new name only**. The old name provably needs nothing: a rename only ever
*removes* declarations of it, a resolving use of it is already in rung 2
(which walks every declaration of the name, not only the target's), and a
non-resolving one cannot start resolving because a candidate was taken away.
That argument is written out under "The dangling-use case" and pinned from
the other side by `a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`,
which checks both that the new-name rung fires when the dangling spelling is
the destination and that nothing is pulled in when it is a bystander.
- The Lemma is unchanged — it was always about what a name *resolves to*, and
it was always sound. What it never claimed, and what the sufficiency
argument now says out loud, is which files *hold* a use. Rung 6 is that
second question's answer.
**The rung's cost, measured** (the lead asked for the number, and for a
name-keyed side map as the fallback if it were large — it is not). On
OpenTitan's 3 976 files: **852 µs** for a name nothing spells, which is the
worst case because `any()` cannot short-circuit, and **402 µs** for `clk_i`,
which 681 files spell. The whole file-set build is 4.75 ms, most of it the
other rungs. `rename` itself went 103.6 ms → 105.5 ms, i.e. unchanged against
a 3.5 s baseline. On the synthetic 504-file corpus the rung is 49.8 µs of a
128.7 µs set build; both are printed by `perf::a_rename_before_and_after`,
which grew two lines for them.
Re-verified after the rework, against the real OpenTitan checkout: all four
cursors still byte-identical (`aes` 7 files, `clk_rst_if` 114 files, `.clk_i`
4 files), the capture refusal on `aes` → `prim_fifo_sync` still verbatim, the
warning counts unmoved. The refusal parity table is unaffected — it is
`prepareRename`'s, and neither entry point's refusal set changed; what changed
is which files `rename` reads before producing rule 12's.
**The macro-invocation warning residue stands as documented** — the lead
accepted it on the record, and the `FileFacts` macro-invocation census remains
filed as the real fix.
Gates after the rework: `cargo fmt --all -- --check` clean,
`cargo clippy --all-targets` clean workspace-wide, `cargo test --workspace`
green, `node editors/vscode/smoke.js` OK against the release binary.
## QA log
**2026-08-24 — QA agent.**
@@ -883,8 +1422,336 @@ surface (hierarchical tails, `defparam` paths, mismatched/redeclared end
labels) is honestly disclosed and consistent with the "lucisv does not
preprocess / does not elaborate" boundary the umbrella already draws.
**2026-08-28 — QA agent (performance wave, Lane A).** Verified the round that
moves `prepareRename` and `rename` off `ws.sources()`. Adversarial charter:
find a rename that edits, warns or refuses differently than the
whole-workspace path would, or a `prepareRename` that lies. Worked in
`.claude/worktrees/agent-a2cccf825469bf247`.
### Gates
- `cargo fmt --all -- --check` — clean, after fixing formatting in QA's own
additions (`cargo fmt --all`; the dev's diff itself was already clean).
- `cargo clippy --all-targets` — clean, zero warnings, forced re-check after
`touch`ing every file this round changed.
- `cargo test --workspace` — green, 0 failures, across every crate (doc-tests
included).
- `node editors/vscode/smoke.js target/release/lucisv-server` — OK, 10
messages, against a freshly built release binary carrying this round's diff
plus QA's added tests.
- Numbers reproduced against the actual code under review (not trusted from
the Work log), `cargo test --release -p lucisv_server --bin lucisv-server
perf:: -- --ignored --nocapture --test-threads=1`: `prepareRename` 238.29 ms
→ **179 ns**; `rename` 466.54 ms → **294.9 µs**; `willRenameFiles` scope-read
11.39 ms → includers-read **15.1 µs**. All within noise of the Work log's
claims. (Two unrelated corpus-dependent perf tests failed in this worktree
because `corpus/` is not checked out here — pre-existing, unaffected by this
diff, confirmed present in `HEAD` before this round's changes.)
- Real OpenTitan checkout (`/Users/guoliangchen/repo/opentitan` @ `0098135264`,
3979 files, matching `performance.md`'s provenance), driven over real LSP/
stdio with a client pointed at this worktree's own `target/release/
lucisv-server` (not the dev's throwaway probes, and not the earlier
"instrumented" binary from the measurer's session): cold workspace scan
settled in 2 940.7 ms; six repeated `rename`s of `aes` averaged **~104 ms**
and all edited exactly the 7 files the Work log names (`tb.sv`, `aes.sv`,
`aes_wrap.sv`, `aes_tb.sv`, and the three `*_pd_main.sv` top-level
instantiation sites); four repeated `prepareRename`s on the same cursor
averaged **~0.05 ms** client-observed (the LSP round trip, not the dev's
in-process 135 ns — consistent with `performance.md`'s own 0.02–0.33 ms
transport floor: the request now costs essentially nothing but the pipe).
**All three gates and the numbers: pass, claims confirmed.**
### Confirmed finding (HIGH, disclosed by the dev, verified real and exactly
as bounded) — the residue's "one lost refusal"
The README's own "The residue" section names a case the fan-out cannot catch:
a file whose only mention of the **new** name is a bare reference that
resolves to nothing today (an `import new_name::*` of a package that does not
exist yet, or a type spelled `new_name`). The whole-workspace verifier refuses
such a rename (capture rule 12: the import would start meaning something);
the fan-out never reads that file, so it returns `Ok` instead — a materially
weaker answer, not merely a lost warning like the macro-invocation case below
it. I built the minimal repro and pinned it as a permanent regression test,
`crates/lucisv_server/src/rename.rs`,
`known_residue_a_dangling_import_of_the_new_name_is_a_lost_refusal`: package
`cfg_pkg` renamed to `taken_pkg`, with a third file `module strayer; import
taken_pkg::*; endmodule` that declares, references (under the old name) and
instantiates nothing. `vlog_refactor::rename` over the whole scope refuses
(`"...would change what taken_pkg means in stray.sv..."`); over
`Workspace::rename_sources`'s real output, it succeeds silently. Confirmed
this is exactly as narrow as documented — every attack in the next section
(new-name declared elsewhere, new-name instantiated elsewhere, new-name
reached via a member connection) is still caught by rungs 1/3/5, so the gap is
precisely "an unresolved bare reference to the new name, nothing else." This
is not a new defect: it is the dev's own disclosed residue, verified to
reproduce exactly as written and correctly bounded. Recorded per CLAUDE.md
invariant 4's spirit (a widened forgiveness needs attack tests proving the
boundary) even though this is a narrowing, not `verify.rs`, because the same
"guilty until proven innocent, with tests" discipline applies to any new gap
between the fast and slow paths. **This is the one item that needs the lead's
explicit ruling** before ship — the brief's own honesty gate.
### Attacks that held — no divergence found
All added as permanent regression tests in `crates/lucisv_server/src/rename.rs`
unless noted, run against the real `Workspace::rename_sources`/
`prepare_rename_here` production code paths, not reimplementations:
- **Escaped-identifier instantiation** (`\sub u_weird (...)`- a different
name to `vlog_semantic` than `sub`, a pre-existing simplification this round
did not touch): `an_escaped_identifier_instantiation_does_not_break_fan_out_parity`.
Both paths call the identical engine, so the escaped spelling is untouched
by both, byte-identical — the fan-out dropping the file (it posts nowhere)
changes nothing observable, since the whole-workspace run's own watch of it
is also a no-op.
- **Same spelling, different symbol kind** (a module named `sub` vs. an
unrelated wire also named `sub` in a different module):
`a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out`. The
unrelated wire's file and declaration are never touched.
- **Escape hatch discovered on the second spelling, not the first** — the
ambiguity is on the *new* name only, so `fan_out_of`'s loop over `[name,
new_name]` must not leak a partially-built, too-narrow `wanted` set when it
bails on the second iteration:
`the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous`. Falls
back to the whole scope correctly; `Workspace::rename_sources`'s early
`return self.sources()` on the first ambiguous hit (state.rs, `fan_out_of`)
discards the partial set rather than returning it, exactly as needed.
- **Prepare parity fuzz beyond the dev's six buffers**
(`crates/vlog_refactor/src/rename.rs`): a valid head followed by an
unparseable tail, CRLF line endings, multi-byte UTF-8 text ahead of the
probed identifiers, and a macro-heavy buffer (`` `ifdef``/`` `define``/
`` `BUMP(x)`` all in one file) — every offset of every buffer, no
divergence, no invented refusal.
- **Include-graph-adjacent attacks on `willRenameFiles`**, in
`crates/lucisv_server/src/file_ops.rs`: an include chain `a.svh -> b.svh`
with a third file `c.sv -> a.svh` (renaming `b.svh` narrows to `a.svh` only,
correctly leaves `c.sv` unedited since it never spells `b.svh`,
`an_include_chain_narrows_to_the_direct_includer_of_the_moved_file`), and a
case-mismatched include spelling (`` `include "DEFS.svh"`` against a real
`defs.svh` on this case-insensitive filesystem,
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`) — both
narrow in correctly and rewrite correctly.
- **Deferred-refusal reachability (rule 11b).** Attempted to construct a case
where the declaring file (in another file from the buffer) has an empty
`name_span`, which is the one row the parity table marks "deferred" rather
than "reproduced." Could not construct one through the public parsing API:
the name-span contract (`vlog-semantic`'s Handshakes, and this feature's own
"every edit span originates in a parsed node") guarantees a non-empty span
on every declaring node the binder records, so this refusal looks
unreachable through any real workspace state today, in the same way the two
"—" rows in the parity table are marked unreachable. Not fixed or asserted
either way — flagging for the record rather than claiming coverage the
suite does not have.
### Not attempted / out of scope for this round
The end-label, hierarchical-tail, `defparam`, and escaped-identifier
*declaration* findings from the 2026-08-24 rounds above are pre-existing and
untouched by this diff — re-read, not re-attacked. The `willCreateFiles`/
`willDeleteFiles` non-goals in file-operations are unrelated to this round.
### Summary
| Claim | Verdict |
|---|---|
| Gates (fmt/clippy/test/smoke) | **Pass** |
| Numbers (synthetic probes + real OpenTitan, this worktree's own build) | **Pass, reproduced independently** |
| Sufficiency argument (name-locality lemma) | **Holds** under every attack tried: escaped identifiers, same-spelling different symbols, mid-walk ambiguity, prepare-parity fuzz, include-chain/case-mismatch narrowing |
| The residue — macro-invocation warning loss | Reproduces exactly as measured on OpenTitan (7→0, 64→61); no edit or refusal lost, only the one warning flavour; already the lead's disclosed call |
| The residue — "one lost refusal" (dangling import of the new name) | **Confirmed real, reproducible, and exactly as bounded** — a genuinely weaker answer than the whole-workspace path, not just a lost warning. **Needs the lead's explicit ruling before ship.** |
**Verdict: REWORK-gate, not ship-as-is** — not because anything is broken by
accident, but because the one item the brief calls "gate the subset path
behind that honesty (lead decides at review)" has not yet had that decision
made. Every other attack in the adversarial charter held. My recommendation,
for the lead: this is very likely acceptable to ship (it is a narrowing of a
*refusal*, not an edit — CLAUDE.md invariant 1 is about edits, and none is
lost or wrong here), especially since the parallel macro-invocation-warning
residue was already accepted; but "very likely acceptable" is not the same as
"decided," and the brief was explicit that this exact honesty gate needs a
lead ruling, not a QA one.
**2026-08-29 — QA agent (re-verification of the rework: rung 6,
`WorkspaceIndex::files_spelling`).** Focused pass, not a full re-run, on the
lead-authorized fix for the HIGH finding above: the flipped test
(`a_dangling_import_of_the_new_name_is_refused_by_both_paths`) and the new
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`, plus "The
dangling-use case" section's argument (rung 6 is the new name's alone because
a rename only ever *removes* declarations of the old name). Charter: attack
rung 6's completeness, attack the old-name exemption with a shadowing/
"unmasking" hunt, verify the tests actually assert what they claim, spot-check
the rung's cost, run the gates. Worked in the same worktree.
### Rung 6 completeness — three new attacks, all pass
Read `WorkspaceIndex::files_spelling` (`crates/vlog_semantic/src/workspace.rs`)
and `resolve.rs`'s `Target::{Package,Unit,UnitMember}`/`miss` machinery to find
every way a real reference could spell the new name and end up with a
`Resolution` whose `paths` are empty (invisible to `files_spelling`, since
`facts_from_analysis` only records `ExternalCandidate`/`InheritedCandidate`
with a non-empty path list). The exhaustive case split: **every** miss on
`Target::Package`, `Target::Unit`, `Target::UnitMember` — including the head
of `p::x` and an `extends`/`implements` base — always pushes at least the bare
name onto its paths (`named_at_file_scope`'s `None` arm, `unit()`'s unconditional
`external.push(name.to_string())`, `unit_member`'s two unconditional
`ExternalCandidate` arms), so all of those are recorded regardless of whether
they resolve. The **only** empty-paths cases are `this_member`/`super_member`
(always `paths: Vec::new()`) and a plain `Target::Lexical` miss inside a class
with `extends` when no import in scope supplies anything
(`miss()`'s `InheritedCandidate { base, paths: external }` with `external`
empty) — and for exactly these, `resolve_external` can *never* produce an
overlay entry (`follow_paths` on an empty list is `StillUnresolved` by
construction, unconditionally, both before and after any rename, because the
paths are fixed by the file's own unedited text), so the reference's `Anchor`
is provably invariant and excluding the file costs nothing on either path.
Three permanent regression tests added to `crates/lucisv_server/src/rename.rs`
to check this empirically rather than trust the proof alone:
- `a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6` — a
class `extends taken_base` where `taken_base` is declared nowhere; renaming
a package to `taken_base` is refused by both paths, and rung 6 pulls the
file in via the `Target::Unit` path (a genuinely different resolution
target than the import case rung 6 was built for). Passes.
- `an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung`
— the one real empty-paths shape (a bare identifier inside a class that
extends an existing, unrelated base, no import in scope). Confirmed
`files_spelling` does **not** pull the file in, and confirmed (via
`same_answer`) that excluding it changes nothing — the rename still
succeeds identically on both paths. Passes, both assertions.
- `a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal`
— a wire declared and used only locally in a third file, sharing the new
name's spelling. `files_spelling` correctly excludes it (it is a
`ReferenceFact::Local`, which the function's own `match` arm returns
`false` for), and the rename succeeds with no edit to that file. This is
also directly what `files_spelling_finds_the_uses_no_posting_can_be_keyed_by`
in `crates/vlog_semantic/tests/workspace.rs` pins at the query's own level
(`quiet.sv`'s local wire named `absent_pkg` is excluded from
`named("absent_pkg")`) — read and re-run, still passes.
### Old-name exemption — shadowing/"unmasking" hunt, none found
Tried to construct exactly the counterexample the charter asked for: two
packages `p_pkg` and `q_pkg` both exporting a member spelled `shared_name`, a
third file importing both (`p_pkg` first, so "first-written import wins"
resolves `shared_name` to `p_pkg`'s declaration today), then renaming *away*
`p_pkg::shared_name` — the hypothesis being that the importer's reference
would silently fall through to `q_pkg`'s pre-existing, unrelated declaration
without the importer's file being in the fan-out.
It doesn't happen, and reading why is the actual finding: the importer's
`shared_name` reference currently *resolves to the rename target itself*, so
it is not a bystander a removal could silently redirect — it is an edit site.
`Scope::collect_occurrences` rewrites it to the new name along with the
declaration, so the text never says `shared_name` again for `follow_paths` to
re-resolve against `q_pkg`. Generalizing: any reference that could possibly
be affected by removing declarations of the old name must itself spell the
old name (the workspace tables are keyed by literal name string, so a
reference to an unrelated name cannot be touched by removing entries under a
different key), and by the Lemma such a reference either (a) resolves to the
target — edited away, not orphaned — or (b) resolves to a *different*
existing declaration of the same name — already in the set, because rung 1
(`workspace_symbols`, not `units`) walks *every* declarer of the name and rung
2 posts against each one, not only the target's — or (c) resolves to nothing
— stays resolving to nothing, since removing a candidate cannot manufacture a
new match. There is no fourth case, so there is no shadowing route the old
name needs a rung for. Verified empirically as well as by this argument:
`removing_the_old_names_winning_declaration_does_not_escape_the_fan_out`
(added to `crates/lucisv_server/src/rename.rs`) builds the exact scenario
above and confirms the fan-out includes both `q.sv` (rung 1, every declarer)
and `user.sv` (rung 2, posted against `p_pkg`'s declaration), that the rename
succeeds, edits exactly the declaration and the importer's reference, and
never touches `q_pkg`'s unrelated declaration. **The old-name exemption
argument held under attack — no counterexample found, and the reason none
exists is now written into the test itself, not just asserted.**
### Tests genuinely assert what they claim — sabotage-verified
Read every test named above plus the dev's flipped/new ones
(`a_dangling_import_of_the_new_name_is_refused_by_both_paths`,
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`) end to end, then
sabotaged rung 6 out (`Workspace::rename_sources`, wrapped the
`want_spellers` call in `if false { … }`) and re-ran the whole
`rename::tests::` module:
- **Failed, as they must**: `a_dangling_import_of_the_new_name_is_refused_by_both_paths`,
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own` (the file "the
fan-out lost the refusal … and edited 1 files instead" — exactly the
pre-rework residue, reproduced on demand), and the new
`a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6`.
- **Still passed, as they must** (they test cases that provably do not
depend on rung 6): the empty-paths test, the local-only-symbol test, the
shadowing/unmasking test, and every pre-existing fan-out test.
Reverted the sabotage (`git diff crates/lucisv_server/src/state.rs` after
reverting shows zero trace of it) and re-ran — all 26 tests in
`rename::tests::` pass again. This is the strongest confirmation available
short of formal proof: the tests that claim to depend on rung 6 actually do,
and the tests that claim not to actually don't.
### Numbers, spot-checked
Release probe (`cargo test --release -p lucisv_server --bin lucisv-server
perf::a_rename_before_and_after -- --ignored --nocapture --test-threads=1`),
against this worktree's own freshly rebuilt binary: file-set build **137.2
µs**, of which `files_spelling` **52.1 µs**; rename fan-out **396.1 µs**;
`prepareRename` whole-workspace **249.5 ms** → buffer+index **212 ns**. All
within noise of the Work log's 128.7/49.8/370/238/200 µs-and-ns figures.
Real OpenTitan checkout, over actual LSP/stdio with a client pointed at this
worktree's own rebuilt `target/release/lucisv-server` (not a throwaway
in-process probe): six repeated `rename`s of `aes` on a cold workspace scan
(3 015.7 ms settle) averaged **~118 ms** (107–134 ms), consistent with the
Work log's 105.5 ms and my own prior-round measurement of ~104 ms — the
spread is machine noise, not a regression from rung 6. Re-requested the same
`aes` → `aes_core_renamed_qa2` rename directly (not just repeated identical
renames) and got the **same 7 files, same edit counts** as my prior-round
spot check, confirming rung 6 changes nothing about the real edit set.
### Gates
`cargo fmt --all -- --check` clean. `cargo clippy --all-targets` clean (forced
re-check after `touch`ing every file this rework changed, zero warnings —
including in the three new tests, one `unused_must_use` warning caught and
fixed on the way, noted so it isn't mistaken for a dev-side issue). `cargo
test --workspace`: **0 failures**, no panics, workspace-wide (34 test binaries
including doc-tests). `node editors/vscode/smoke.js target/release/lucisv-server`
— OK, 10 messages.
### Verdict
**SHIP.** The rework closes the HIGH finding exactly as claimed: rung 6 is
complete under every completeness attack tried (including two shapes — the
extends-base case and the empty-paths InheritedCandidate case — the dev's own
writeup didn't walk through explicitly), the old-name exemption holds under a
genuine shadowing/unmasking attempt (with the reason now understood and
tested, not just asserted), the flipped and new tests are not vacuously
passing (sabotage-confirmed), and the rung's cost is sub-millisecond on
OpenTitan with no measurable end-to-end regression. No new findings. The
macro-invocation warning residue is unchanged and remains the lead's
already-accepted, separately-tracked call.
## Review
**2026-08-29 — lead, performance-wave Lane A.** Reviewed after QA's
initial REWORK-gate, the fix round, and QA's SHIP on re-verification;
gates re-run on the worktree (fmt clean, clippy silent, 2518 workspace
tests green). The round's spine is the name-locality lemma, and the
rework is what made it whole: rungs 1–5 are all keyed by declarations,
so the dangling-use capture case — a refusal, not a warning — needed
rung 6 (`files_spelling`, over the reference facts the index already
keeps, FACTS_FORMAT untouched), and the lead ruled the residue
unshippable rather than documentable. QA then enumerated resolve.rs's
full miss taxonomy to prove the rung's two blind spots workspace-
invariant, hunted a shadowing counterexample to the old-name exemption
and found the lemma held, and sabotage-verified the parity tests bite.
That is the loop working as designed. prepareRename 1.66 s → 139 ns,
rename 3.47 s → 105 ms with the rung costing 852 µs worst-case,
willRename 249 ms → 14 ms; byte-parity swept at four real cursors and
564 offsets. The accepted macro-invocation warning residue and the
FileFacts macro census stay filed; the includes.rs accessor deviation
was the correct refusal to copy a scan. Accepted; merged by the lead.
**2026-08-24 — lead.** Reviewed the full diff after QA round 2's ship
verdict; ran the three gates independently (1085 tests, 0 failures, clippy
silent). The two-layer verification in `check.rs` is the right safety story
+168
View File
@@ -47,6 +47,12 @@ predicate, and three handlers.
be paired with different bytes; an open file contributes live spans instead.
Location conversion fetches and line-indexes each touched file once, however
many occurrences it contains.
- **`documentHighlight` is a *document* answer even for a cross-file name**
(2026-08-28). The cursor on an instantiated module, or on a `.port` in a
connection list, highlights that name's uses **in this file** — the workspace
overlay is consulted to learn *which declaration* the cursor names, never to
widen the answer past the buffer. So the same position can answer 1 here and
7 to `references`, and both are right.
- **Read/write is not distinguished** in `documentHighlight`. LSP permits a
plain `Text` kind, and telling a read from a write in Verilog means
classifying continuous vs. procedural assignment, port direction and
@@ -140,6 +146,20 @@ decision.
## Status / TODO
- [x] **`documentHighlight` answered nothing on a cross-file name
(2026-08-28, performance wave Lane B):** `performance.md` §7 reported it
returning 0 results at *every* opentitan position tried — the `aes`
instantiation, the `.clk_i` port connection, at both scopes, before and
after a widen — while `references` at the same positions returned 7 and
10. **Not a benchmark mistake: a real bug**, reproduced in a five-line
fixture and fixed. Root cause and the argument are in the work log
below; the regression tests are
`nav::tests::a_cross_file_name_highlights_its_uses_in_this_file` and, over
the wire at the same two positions,
`e2e::cross_file_references_folding_and_highlights_round_trip_over_the_wire`
ids 6 and 7. Still fast now that it answers: **0.05–0.15 ms** against the
0.03–0.12 ms it took to answer nothing.
- [x] **References latency with a big buffer open (2026-08-28):** measure both
directions of a cross-file references request while a 1.4 MB, 40 000-line
`top.sv` is an open document, then fix what the numbers convict. Landed:
@@ -210,6 +230,54 @@ decision.
## Work log
### 2026-08-28 — documentHighlight answered nothing on a cross-file name
**The report.** `performance.md` §7: `documentHighlight` returned 0 results at
every opentitan position tested, while `references` answered at the same
positions. It was fast because it was doing nothing, which is the kind of
result a benchmark that only times things rewards.
**Reproduced first, in five lines.** A `top.sv` that instantiates a `sub`
declared in another file, with two instantiations and a `.clk_i` connection on
each. `references` at the module name answered 3; `document_highlights` at the
same byte answered `None`. That is
`a_cross_file_name_highlights_its_uses_in_this_file`, written to fail before
anything was changed.
**Root cause.** `document_highlights` asked `symbol_at`, which is
`Semantics::reference_at(offset).resolved()` or `Semantics::symbol_at(offset)`
— **both of them single-file questions**. A name this file *uses* but does not
*declare* has no in-file symbol at all: `analyze` records the use as an
external candidate and leaves it to the workspace layer, so `reference_at`
resolves to nothing and `symbol_at` finds no declaration. An instantiated
module's name and a `.port` in a connection list are exactly that shape, and
they are most of what a cursor lands on in a testbench.
`references` never had the bug because it reads `doc.external` — the workspace
overlay — through `leaves_this_file`/`indexed_target`. The two handlers were
answering the same question from different halves of the same document, and
only one half had been wired up. The existing highlight tests all used a
signal declared in the file under test, which is why the suite was green.
**The fix**, `nav::external_occurrences`: when `symbol_at` finds nothing, ask
the overlay for the reference at the cursor, and if the workspace answered it,
collect every reference in *this* file that spells the same name and that the
overlay answered the same way. Same-name-and-same-answer rather than
same-name: two uses of `clk_i` that resolve into different modules are
different symbols, and comparing the whole `defs()` slice rather than its
first entry keeps two *ambiguous* uses together only when they are ambiguous
between the same declarations. A use the index cannot answer is still left
alone, so the editor keeps its own word highlighting — the contract the rest
of the function already honours.
It stays a **document** highlight: one file's occurrences, which is why the
opentitan `aes` position now answers 1 where `references` answers 7. That is
not a smaller answer to the same question; `tb.sv` instantiates `aes` once.
Nothing outside `nav.rs` changed — the handler in `server.rs` already had the
document in hand, and `Document::external` is already beside `Document::
semantics`, so no signature moved.
### 2026-08-28 — references latency with a big buffer open
The owner reported find-references from a *use site* in a big open `top.sv`
@@ -858,8 +926,108 @@ dev's original shape plus exactly my one addition.
TODO.md discrepancy) left for the lead to reconcile — neither is a
correctness or safety issue in the shipped feature.
### 2026-08-28 — QA agent (performance wave Lane B: the documentHighlight fix)
Verdict: **the fix is correct and holds under attack. One genuine behavioral
divergence from `references` found and recorded (not a bug, but the lead
should see it before calling the two "cross-checked").**
**Reproduced the original bug, live.** Built this worktree's release binary,
pointed a copy of the scratchpad's `lspclient.py`/`bench.py` harness at it
(`SERVER` edited to `target/release/lucisv-server`, `ROOT` unchanged at
`/Users/guoliangchen/repo/opentitan`), and ran `bench.py nav workspace -`
against the real checkout: `documentHighlight(aes)` and
`documentHighlight(.clk_i)` now each return **1 result** (the `tb.sv`-local
occurrence — correctly fewer than `references`'s 7/10, since `references`
is workspace-wide and highlight is this-file-only by contract), where
`performance.md` §7 recorded 0. Confirms the fix end-to-end, not just in
the unit suite.
**Attacked the grouping logic (charter item 4) with three new permanent
tests in `nav.rs`:**
1. `an_ambiguous_instantiation_highlights_where_references_gives_up` — two
files both declare `module dup`, instantiated twice in a third file.
`document_highlights` correctly groups both instantiations (same
ambiguous def set). **Finding, not a bug**: `references` at the same
position returns *empty*, not the same answer — traced to
`indexed_target` (`nav.rs`), which only builds an `IndexedTarget` from
`Definition::External([def])`, exactly one candidate; an ambiguous
external use (2+ candidates) makes it return `None`, so `references()`
falls through to `in_file_references`, which requires a *local* symbol
(`symbol_at`) that an external use does not have — net empty, and this
is pre-existing, unrelated to this round. `document_highlights`'s new
`external_occurrences` has no such restriction: it groups by the
overlay's whole answer, ambiguous sets included. This is a genuine
divergence from "highlights == references-in-this-file at the same
position", though arguably the *better* behavior (answering something
reasonable beats forcing the editor's own word-highlighter to fall back
to nothing) — recorded per the charter's instruction to cross-check
rather than assumed away.
2. `two_uses_ambiguous_between_different_def_sets_do_not_group` — the sin
the charter names directly. Building this took two attempts: my first
version used two module-scope `import p1::*; import p2::*;` wildcards
expecting position-scoped ambiguity, and it failed — both usages grouped
together (lines `[3, 5]` where I expected `[3]` and `[5]` separately).
Root cause, traced through `bind.rs::bind_module` /
`follow_paths`/`follow_one`: imports are collected per-scope and tried
*in declaration order*, and `follow_paths` returns on the **first** path
with any answer — so multiple wildcard imports of packages that each
independently declare the same member never produce a multi-package
`Ambiguous`; each reference resolves against whichever imported package
is tried first. Real ambiguity comes from **duplicate declarations of
the same entity** (two files declaring the same module/package), not
from multiple distinct wildcard imports. Rebuilt the test around two
*different* modules (`dup_a`, `dup_b`), each duplicated across two
files, both exposing a port named identically (`same_port`) and
connected in the same top module — same `reference.name`, disjoint
ambiguous def sets (`dup_a`'s two files vs. `dup_b`'s two files). Passes:
the two connections do not group. This is the test that actually proves
`external_occurrences`'s `defs()` comparison (not just the name match)
is load-bearing.
3. `an_unanswered_external_use_declines_rather_than_guessing` — an import
of a package the workspace does not declare, and a member reference the
overlay cannot place. `document_highlights` returns `None` (declines),
confirming the empty-`defs()` early-out and preserving the editor's
own word-highlighting fallback.
**Cross-file name collision (charter item 4, "local at one position,
external at another")**: traced by hand rather than by a new test —
`external_occurrences` only ever matches a candidate occurrence through
`doc.external.get(at)`, which is populated only for references the
workspace overlay actually resolved (`resolve_external`,
`vlog_semantic::workspace`); a same-spelled local declaration/use has no
entry there, so `None == Some(target.defs())` excludes it automatically.
No counter-example found.
**Reference-id indexing**: confirmed `ReferenceId(i)` in
`vlog_semantic::lib.rs` corresponds exactly to index `i` in
`Semantics::references()`'s backing `Vec` (`self.references.get(id.0 as
usize)`), so `external_occurrences`'s `enumerate()` + `ReferenceId(*at as
u32)` round trip is not an off-by-one risk.
**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test
--workspace` (1261 passed), `node editors/vscode/smoke.js
target/release/lucisv-server` — all clean, run against the worktree
including my three additions.
No fixes applied to feature code — the fix is correct as shipped. Three
permanent regression tests added to `nav.rs`. No commits.
## Review
**2026-08-28 — lead, performance-wave Lane B (documentHighlight).**
The zero-results report was a real bug with a clean root cause: both
cursor questions were single-file, so a name this file uses but does
not declare had no answer, and every existing test used a declared
name. The fix reads the overlay and groups by the whole defs() slice —
the conservative equality — and was written failing-first with the two
exact opentitan positions pinned over the wire. QA's INFORMATIONAL
asymmetry (highlight answers on a globally-ambiguous target where
references declines) is pre-existing, arguably correct — a highlight
is file-local and read-only — and is now recorded here rather than
discovered again. Accepted.
**2026-08-28 — lead, references-latency round.** Reviewed after QA's
clean SHIP; gates re-run independently (fmt clean, clippy silent, 2407
workspace tests green). Measure-first discipline held: the probes were
+14
View File
@@ -78,6 +78,20 @@ its work list.
### `lucisv_server::state` — the scan as a value
**Amended (index-scope, 2026-08-28): a scan now has two shapes and one
ending.** `Scan` carries a private kind, `Workspace::begin_widen` is a second
constructor for it — the files a scope widen brought in, rather than every
in-scope file — and `finish_scan` branches on that kind so a widen cannot be
landed as a whole scan. **`begin_scan`, `scan_step` and `publish_scan` are
unchanged and are the same code for both shapes**, which is what keeps the
cache behaviour, the open-buffer reuse and the event stream identical without a
second implementation to keep in step. A widen deliberately does *not*
interleave: it is a rescan, so `must_wait` holds requests queued behind it
either way, and the point of that round is that there is no longer a wait worth
breaking up. A widen asked for **mid-scan** sets `rescan_wanted` like every
other mid-scan trigger, so it is one more *whole* scan behind this one and never
a scan inside a scan. See `docs/features/index-scope/README.md`.
```rust
pub struct Scan { /* work list, how far through it, what is staged */ }
+888
View File
@@ -0,0 +1,888 @@
# verbose-timing
## Goal
`lucisv-server --verbose` makes the server say how long every operation took,
as `timing:` lines in the client's own log channel. It is the diagnostic build
the lead produced twice by hand-patching, made permanent and opt-in: the same
lines, the same wording, now shipped behind one flag instead of a rebuild. The
question it answers is the one a user asks when the editor feels slow — *was
that request slow, or was it never started?* — and the two lines that answer it
are `<method> answered in X ms` and `<method> HELD behind a rescan`. Off is the
shipped state and costs one branch per timed site: no clock read, no
`format!`, no notification. VS Code turns it on with `lucisv.verbose`, which
restarts the server because the flag is a spawn argument.
## What it prints
Every line is one `window/logMessage` at `MessageType::LOG`, prefixed
`timing: ` — the same channel and the same message type the per-file index log
(`lucisv.index.logFiles`) already uses, so a client that shows one shows both
and `grep timing:` separates them. Durations are milliseconds to two decimals,
from one helper (`ms`), so a 60 µs hover reads as `0.06 ms` rather than `0 ms`.
| line | where | says |
|---|---|---|
| `timing: <method> answered in X ms` | `Server::request` | One request, handler only — the flush it triggers, the analysis, the answer |
| `timing: <method> handled in X ms` | `Server::notification` | One notification, including any rescan it caused |
| `timing: <method> HELD behind a rescan (answering=…, wanted=…, already held=N)` | `Server::process_batch` | The request did not start: the order contract made it wait. The three fields are `must_wait`'s three clauses, so the line names *which* one held it |
| `timing: scan started: N file(s)[, interleaved]` | `Server::scan_once` | The work list's size, and whether the scan will answer messages between its files (`total > INTERLEAVE_ABOVE`) |
| `timing: scan finished: N file(s) (S skipped, C from cache) in X ms` | `Server::scan_once` | The same counts the progress bar's closing message carries, with the time |
| `timing: widen started: N folder(s) added: <paths>` | `Server::reindex_widened` | Which folders a `didOpen` added to the scope, by name |
| `timing: widen finished: N file(s) (S skipped, C from cache) in X ms` | `Server::reindex_widened` | What that cost |
| `timing: flush of N dirty buffer(s) took X ms` | `Server::flush_dirty` | The debounced reparse a typing burst was coalesced into |
| `timing: reindex_one(<path>) took X ms` | `Server::reindex_one` | The one-file incremental index update a save takes |
Three absences are deliberate:
* **`shutdown` is never timed.** `Connection::handle_shutdown` answers it in
the loop, ahead of the dispatch, so it never reaches the timed wrapper.
Nothing measurable happens there and routing the handshake through the
wrapper to get a line would be worse than not having one.
* **A scan a `shutdown` interrupted prints no `finished` line**, and a
`reindex_one` that declined (the file was not in the index) prints nothing
either: the first must not speak to a client that has gone, and the second
did no work — its caller is about to rebuild the whole index, and *that*
times itself.
* **A cancelled request prints no `answered in` line.** `process_batch`
resolves `$/cancelRequest` before `Server::request` (the timing wrapper) is
ever called — a cancelled id is answered from the cancelled set directly —
so the handler never ran and there is nothing to have timed. Pinned by
`a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing`
in `tests/e2e.rs` (QA, 2026-08-29).
## Ordering: the line comes **before** the response
A request's timing line is sent before the response it describes. The dispatch
is `Server::request`, and the response is sent by its caller
(`process_batch`), so a wrapper around the dispatch can only speak first. That
was chosen over threading the start time out to the caller because it keeps the
measurement to exactly the handler, with none of the transport in it, and it
keeps the shape the two diagnostic builds already had.
Nothing keys off the order. A `window/logMessage` carries no id; a client pairs
a response with its request by id, whatever arrived in between. The one real
consequence — that in verbose mode a response is preceded by one extra small
write — is the cost of the flag and is why it is off by default. The e2e test
`the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel`
pins the order, so a future change to it is a deliberate one.
## The restart: one chain, reconciled to the last toggle
`--verbose` is a spawn argument, so `lucisv.verbose` can only take effect by
starting a new process. That makes the extension's restart the one piece of
this feature with a concurrency problem, and `editors/vscode/restart.js` is
the whole of the answer to it.
**The rule: there is exactly one chain of transitions, no transition exists
outside it, and it always reconciles to the last arguments anybody asked
for.**
- Every toggle writes what it wants into `desiredArgs` **synchronously** and
queues a reconcile onto the same promise (`chain = chain.then(reconcile)`).
Nothing else starts or stops the client — the **activation spawn is the
first link of that chain too**, which is the part that matters: a start is
in flight for as long as the first workspace scan takes, and that is exactly
when a user reaches for the setting.
- A reconcile that finds the running arguments already equal to the desired
ones does nothing. That is what collapses a burst of toggles — `on`, `off`,
`on` — into at most one restart, landing on the last one.
- Otherwise: `stop()` (awaited, and a rejection is tolerated — a client that
is not running cannot be stopped, and because this is on the chain, nobody
else is stopping it), write the arguments into `serverOptions.args` (the
client re-reads that object at every `start()`), `start()` (awaited), then
repaint.
- A `start()` that rejects records "nothing is running", so the next toggle
retries whatever it asks for, and is reported through the same handler
activation failures use rather than swallowed by an anonymous `catch {}`.
The chain survives it.
- **Teardown is a link of the chain too.** `deactivate()` calls
`restarter.dispose()` and awaits it; it never touches `client.stop()`
itself. `dispose()` shuts the door — `want()` becomes a silent no-op, and
any reconcile *already queued* returns without doing anything — and then
puts one final stop on the same chain, which is what the returned promise
resolves after. Idempotent, and a dispose before anything was spawned stops
nothing.
That last bullet is the second half of the same invariant, and it was learned
the same way. `deactivate()` used to await a **snapshot** of the chain and then
stop the client itself. A `lucisv.verbose` event landing in the same tick
mutated the live chain and queued a whole reconcile — stop, then **spawn** —
as a sibling of that stop, with nothing left to await the new process: QA
reproduced `stop, stop, start(--verbose)` against the shipped module (finding
3, 2026-08-29). When the whole window closes that server dies with its parent's
stdin, but an extension *disable* or an extension-host-only restart leaves the
host alive and the process orphaned. Two guards close it, and both are wanted:
the one in `want()` keeps the chain from growing after teardown, and the one
inside `reconcile()` catches the toggle that got into the queue *first* — the
chain only promises that a queued reconcile runs after `dispose()` was called,
not that it was never queued.
Why it has to be a chain rather than a guard: `vscode-languageclient` 9's
`start()` returns the *in-flight* start whenever one exists (`client.js:642`),
and its `stop()` rejects while the client is still `Starting`
(`client.js:960`). A restart that just calls `stop()` then `start()` therefore
stops nothing, rejoins the start that was already running **with the old
arguments**, and reports success — the user believes the toggle worked while
the server has never heard of it. That was QA finding 1 (2026-08-29), and the
chain removes the precondition for it: no transition ever begins while another
is in flight, so there is no in-flight start to rejoin.
`restart.js` knows nothing about VS Code — it takes a client-like object with
`start()`/`stop()`. That is what lets `editors/vscode/restart_test.js`
(`node restart_test.js`, plain node, no dependencies, run like `smoke.js`
beside it) drive **this** logic against a scripted fake, rather than
re-implementing the language client's state machine and testing the copy.
## Why the in-loop send cannot deadlock
Every timing line goes out through `Server::notify`, the same fire-and-forget
path the diagnostics push, the scope warnings and the per-file index log have
always used, on the same thread, holding no lock (this server has none — it is
one thread and `lsp-server`'s two I/O threads).
`lsp-server` 0.10.0's stdio transport makes the writer channel `bounded(0)`, so
a send waits for the writer thread to take the message. That thread does
exactly one thing — write the message to stdout and hand it to a dropper thread
— and never sends anything back into the loop, so there is no cycle to close.
If it has exited, the receiver is dropped and the send returns `Err`, which
`notify_on` discards: a client that has gone is nobody to report to. The only
way a send can wait is a client that has stopped reading its own stdout, and
that already blocks every diagnostic and every one of the hundreds of per-file
log lines a scan sends — verbose adds volume there, not a new hazard.
Ordering is likewise unchanged: one channel, one writer thread, FIFO. A timing
line sent before a response is written before it, and the two can never
interleave.
## Assumptions
- **The client shows `MessageType::LOG`.** `vscode-languageclient` 9 appends
it verbatim to the extension's output channel (its `LogMessageNotification`
handler falls through to `outputChannel.appendLine`), which is where the
index log already lands. A client that drops LOG messages sees nothing —
the same deal `lucisv.index.logFiles` has always had.
- **A user who turns this on accepts the volume.** A busy session logs a line
per keystroke (the flush) and per request. That is stated in the setting's
description rather than rate-limited: a sampled diagnostic is a lying one.
- **Two decimals of a millisecond is enough resolution.** The fastest thing
timed here is a cursor answer at ~0.05 ms; nanoseconds would be noise from
the clock read itself.
- **Nobody parses these lines.** They are for a person reading a channel.
Nothing in the repo greps them except this feature's own tests.
## Handshakes
**Amends `editors/vscode ◀──▶ lucisv_server` (TOPO.md §1.2).** The spawn
contract said "binary named `lucisv-server`, no args, no env, LSP over stdio,
…". It now reads, in that row:
> The extension passes exactly `[]` by default or `['--verbose']` when
> `lucisv.verbose` is true; the server accepts only that spelling (repeats are
> idempotent) and refuses any other argument with exit 2. Changing that
> setting restarts the server because it is a process argument, not an LSP
> setting. […] `smoke.js` still drives the default no-argument contract
> headlessly; `tests/e2e.rs` pins both spawns.
Both halves of that are load-bearing and both are pinned:
- **The no-argument spawn is unchanged**, which is what `smoke.js` drives (its
spawn untouched this round, still passing) and what
`without_the_flag_not_one_timing_line_is_ever_sent` proves stays silent.
- **An argument the server does not take is refused, not ignored.** Today's
server ignores `std::env::args` entirely, so `lucisv-server --verbos` would
have started a perfectly normal server that logged nothing, and the user
would have had no way to tell that from a broken feature. Exit 2 matches the
CLI's own "an error occurred" code and its `error: unknown option: …`
wording. There is deliberately **no** `-v`, `--help` or `--version`: one
spelling, and the version lives on the `lucisv` CLI, which is where
`tools/release.sh` reads it (TOPO.md §1.2, `tools/` handshake).
**Consumed from `editors/vscode`:** the `lucisv.verbose` setting, whose
`false` default and the server's "no argument means off" are pinned against
each other by `the_extension_ships_the_flag_off_which_is_what_no_argument_means`
in `main.rs`, reading `package.json` — the same manifest-vs-shipped-defaults
check `settings.rs` makes for `scopeDepth` and `maxFileSize`.
**Promised to nobody else.** The lines are not a wire format: no client parses
them, and `lucisv.verbose` is not a *server* setting — the server never reads
it out of the `lucisv` section it is pushed (it is spawn-time or nothing), so
`settings.rs` is untouched by this round.
## Status / TODO
- [x] `--verbose` parsed in `main.rs`; unknown arguments exit 2 with a usage
line on stderr; the flag threaded to `Server` as one `bool`.
- [x] `Server::request` / `Server::notification` are timing wrappers around
`answer_request` / `handle_notification`.
- [x] The `HELD` line, naming which `must_wait` clause held the request.
- [x] Scan, widen, flush and `reindex_one` lifecycle lines.
- [x] `timer` / `timed` / `timing` / `ms`, so verbose-off is one branch per
site and nothing else.
- [x] Verbose-off cost measured against HEAD (see the work log).
- [x] `lucisv.verbose` in `package.json`, passed in the spawn args, and a
restart when it changes.
- [x] That restart is **one serialized chain reconciling to the last toggle**
(`editors/vscode/restart.js`), with the activation spawn as its first
link — QA finding 1, reworked 2026-08-29.
- [x] And **teardown is a link of the same chain**: `deactivate()` awaits
`restarter.dispose()`, which shuts the door (in `want` and in a queued
`reconcile`) before its final stop, so no toggle can spawn an orphan on
the way out — QA finding 3, reworked 2026-08-29.
- [x] `node editors/vscode/restart_test.js`: eleven cases over that chain
against a scripted fake client, mutation-checked five ways.
- [x] e2e: the flag times things, the absence of it times nothing, a held
request says so, an unknown argument exits 2.
- [x] e2e: a cancelled request is timed for exactly what ran, and nothing is
reordered under a flood (QA, 2026-08-29).
- [x] `smoke.js` unchanged in behaviour and still passing.
- [x] Contract amended in TOPO.md, `lucisv-server`, `editor-settings`, both
editor READMEs.
- [ ] Not done, deliberately: no `--verbose` on the `lucisv` CLI (it formats
files; there is no session to time), no log file, no rate limit, no
per-category filter. If the volume turns out to be the problem, the next
round is a *filter*, not a sampler.
- [ ] Known, not this round's to fix: after a start that *failed*,
`vscode-languageclient` 9 never clears its `_onStart`, so a later
`start()` re-joins the rejected promise — the chain's retry asks
correctly and the library declines, and a window reload is still needed
to recover from a bad `lucisv.serverPath`. Pre-existing (QA, 2026-08-29);
the retry is the right shape either way and costs nothing.
## Work log
### 2026-08-29 — dev agent (rework 2, after QA finding 3, MEDIUM)
QA's re-verification closed finding 1 (their two mutations were caught by the
shipped test) and found one more transition outside the chain: `deactivate()`
itself. It awaited `restarter.settled()` — a *snapshot* of the chain — and then
called `client.stop()` beside it, so a `want()` landing in the same tick queued
a full reconcile, spawn included, that nothing was left to await. Their trace
against the shipped module: `stop, stop, start(["--verbose"])`. Self-healing
when the window closes (the child's stdin dies with the parent), an orphan when
the extension host outlives the module — a disable, or a host-only restart.
Fixed to the lead's ruling, ten lines:
- `restart.js` gains `disposed` and `dispose()`. The flag is set synchronously
and checked in **two** places: the top of `want()` (nothing new is accepted,
and the chain does not even grow — `want` hands back the teardown promise)
and the top of `reconcile()` (whatever was already queued does nothing). The
second is the load-bearing one: a toggle can beat `dispose` into the queue by
a tick, and the chain only guarantees it *runs* afterwards.
- `dispose()` then chains one `stopForGood` onto the same `chain` and returns
that link, so awaiting it means "the server is stopped", not "the stop was
queued". It stops nothing when nothing was spawned (the real client rejects
a stop of a client that never ran), tolerates a rejected stop (teardown —
nobody can act on it), and is idempotent, with every caller's promise
resolving after the one real stop.
- `extension.js`'s `deactivate()` is now `return restarter ?
restarter.dispose() : undefined` and no longer names `client.stop()` at all.
With that, `grep '\.start(\|\.stop('` over `extension.js` finds no client
transition outside the restarter, which is the invariant the module header
claims — QA checked that grep last pass and it is now true.
`restart_test.js` grows four cases (11 total, 44 checks): QA's exact repro (a
`want()` in the same tick as `dispose()` spawns nothing, and a later toggle
adds no link at all); a reconcile queued *before* `dispose()` becoming a no-op;
`dispose()` resolving only after the final stop, twice-in-one-tick included;
and a dispose before anything was spawned stopping nothing. Mutation-checked to
five now, each caught and each file restored byte-identical: dropping the
`disposed` check in `reconcile` (the half the ruling named), dropping it in
`want`, returning from `dispose` before its stop finishes, hanging that stop
beside the chain instead of on it, and stopping a client that was never
started.
Also took QA's LOW comment nit in
`aFailedStartIsReportedAndTheChainStaysUsable`: the comment said the retry is
"what a user who fixed their `serverPath` does", which reads as though the
retry works against the real client. It does not — `_onStart` is never cleared
after a failed start — so the comment now says what the test actually pins:
`restart.js` keeps *asking*, and whether the ask can succeed is the known
library limitation recorded in Status / TODO.
No `crates/` change in this iteration; the server side is untouched by both
reworks.
### 2026-08-29 — dev agent (rework after QA finding 1, HIGH)
QA found the restart could **silently lose a toggle**: with a `start()` in
flight, `stop()` rejects (swallowed), `start()` rejoins the in-flight start
with the old arguments, the extension repaints, and nothing anywhere says the
setting did not take. Their trace of the vendored client
(`client.js:642-653`, `960-965`, `988-992`) is in the QA log; their repro
harness re-implemented that state machine and was rightly not committed.
Fixed to the lead's ruling — serialize, and reconcile to the last desired
state. New module `editors/vscode/restart.js` (~90 lines, no VS Code
dependency, shipped) holding `createRestarter({ client, serverOptions,
onStarted, onStartFailed })`:
- `desiredArgs` is written synchronously by every `want(args)`; `runningArgs`
is what the live process was actually spawned with (`null` when none is).
- One `chain`; `want()` and `start()` both do
`chain = chain.then(reconcile).catch(onStartFailed)`. **`activate` now
spawns through `restarter.start()` instead of calling `client.start()`
directly** — that is what closes the finding, since the activation start was
the in-flight start being rejoined.
- `reconcile()` returns immediately when `sameArgs(runningArgs, desiredArgs)`
(so a burst collapses to one restart), else stops (tolerating a rejection),
writes `serverOptions.args`, starts, repaints. A rejected `start()` sets
`runningArgs = null` and rethrows, so the failure is reported *and* the next
toggle retries. `sameArgs(null, anything)` is false, `null` included, which
is what makes that retry possible.
- `onStartFailed` is `reportStartFailure` in `extension.js`, now shared with
activation: one line into the client's own output channel (no popup — the
client already reports the spawn failure itself, and activation never opened
one), wrapped in case there is no channel to write to.
- `deactivate()` now waits for the chain before stopping, for the same reason
the toggles do.
**The test seam and the test.** `restart.js` takes a client-like object, so
`editors/vscode/restart_test.js` drives *our* rule against a fake whose
`start()`/`stop()` the test settles by hand — no re-implementation of the
library's state machine, which is what made QA's harness uncommittable. Plain
node, no dependencies, `node editors/vscode/restart_test.js`, exit 0/1, the
same invocation style as `smoke.js` beside it; documented in `README.md`
("Checking the server without an editor") and in `tools/RELEASING.md`'s
`.vscodeignore` bullet. Seven cases, 28 checks:
1. activation spawns once with the settings' arguments;
2. **the finding**: a toggle during the in-flight activation start spawns
nothing while that start is running, then restarts onto `--verbose` once it
finishes (and `serverOptions.args` is what the second start reads);
3. `on`→`off`→`on` during an in-flight start costs **one** restart, landing on
the last toggle;
4. asking for what is already running restarts nothing;
5. a rejected `start()` is reported once, records nothing as running, and the
chain still retries the next toggle;
6. a rejected `stop()` does not cost the start that was asked for;
7. `sameArgs` compares by value and treats `null` as "nothing running".
Deliberately mutation-checked, because a green test proves nothing on its own:
removing the chaining fails case 2 ("nothing else may spawn while it is"),
keeping `runningArgs` after a failed start fails case 5, and reconciling to
the old arguments instead of the desired ones fails case 2's landing
assertion. A watchdog timer fails the run rather than letting node exit 0 in
silence if a promise never settles — which it did during development, and is
a trap worth keeping shut. `.vscodeignore` excludes `restart_test.js` (and
still `smoke.js`); `restart.js` itself must ship, which `RELEASING.md` now
says out loud with the `unzip` check.
QA's own LOW (a cancelled request gets no timing line, documented as the third
deliberate absence and pinned by
`a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing`)
is kept as they left it. The server side is unchanged by this rework.
### 2026-08-29 — dev agent
**Server.** `verbose_flag` in `main.rs` walks `std::env::args().skip(1)`:
every argument must be `--verbose` (repeats are fine — they say the same thing
twice), and the first one that is not is returned and reported. `main` refuses
before `Connection::stdio()` is built: answering LSP anyway would hide the
mistake for a whole session. The flag becomes `Server { verbose: bool }`
(`Server::new` and the test seam `Server::started` each take one more
argument).
`request` and `notification` became timing wrappers; the old bodies are
`answer_request` and `handle_notification`, unchanged. Each wrapper's first
statement is `let Some(started) = self.timer() else { return … }`, so
verbose-off is a field read and a branch — no `Instant::now`, no method clone,
no `format!`. The other five sites use the same `timer()` plus `timed(started,
|took| …)`, whose closure is never called when the timer is `None`; the two
"started" lines (scan, widen) are under `if started.is_some()`.
Decisions worth naming:
- **The line precedes the response** — argued in full above, and pinned by a
test rather than left to a reader.
- **`scan started: N file(s) …`** — the brief's ellipsis is resolved to
`, interleaved` when the scan is over `INTERLEAVE_ABOVE` and to nothing
otherwise. It is one word, it is decided at exactly that point, and it is
the second half of the `HELD` answer: a scan that does not interleave
answers nothing at all until it is done.
- **One duration format for every line.** The brief wrote `X.XX ms` for
requests and `X ms` for the lifecycle lines; both go through `ms()` and read
as `X.XX ms`. Two formats would have been a difference with no meaning.
- **Counts are pluralized** (`1 file`, `0 files`) rather than printing a
literal `file(s)`, which is what `end_indexing` next door already does.
- **`shutdown` is not timed**, because it never reaches the dispatch — found
by an assertion that expected it to be there, now inverted and commented.
**Extension.** `serverArgs()` reads `lucisv.verbose` (`=== true`, so nothing
but a real boolean turns it on) and is called once at activation for
`serverOptions.args`, and again by every toggle. This extension had **no**
restart-on-settings path before; `lucisv.serverPath` still needs a window
reload, which this round deliberately did not change.
*(The first cut of the restart — a straight-line
`stop()`/write-args/`start()` guarded by comparing the new arguments with
`serverOptions.args` — lost a toggle that arrived while a `start()` was in
flight. It was rewritten as the reconcile chain below after QA finding 1;
see the rework entry.)*
The decorations are repainted after each successful start, because they went
with the old connection.
**Tests.** Four e2e cases, and `talk_with(args, session)` so a test can spawn
with arguments (`talk` is now its no-argument case, which is the contract
`smoke.js` drives):
- `the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel`
— one session that opens a buffer, types in it, asks two questions, saves,
and shuts down: it produces every kind of line but `HELD`, and each is
asserted by its exact prefix. It also pins the line-before-response order.
- `without_the_flag_not_one_timing_line_is_ever_sent` — the same session over
the shipped spawn: zero `timing:` lines, and the answers still arrive (a
server that failed to start would also be quiet).
- `a_request_queued_behind_a_rescan_says_it_was_held` — 100 generated files in
a filelist make the startup scan interleave; the session's settings push is
drained mid-scan and asks for a rebuild, so the `workspace/symbol` behind it
is held, says so, and is answered afterwards.
- `an_argument_the_server_does_not_take_is_refused_rather_than_ignored` —
`--verbos` exits 2, names the option, prints the usage line, and puts
nothing on stdout.
Plus `the_extension_ships_the_flag_off_which_is_what_no_argument_means` and
three `verbose_flag` unit tests in `main.rs`.
**Docs.** The contract is amended in five places, because five documents state
it: TOPO.md §1.2's spawn-contract row (see the note at the end of this entry),
`lucisv-server`'s README (a new "Starting it: the argument contract" table, and
its Handshakes section, which said the binary promised nobody anything and now
names the argument contract), `editor-settings`' README (the two settings in
the `lucisv` section that are *not* wire settings, and why one of them
restarts the server), `editors/vscode/README.md`'s settings table, and
`editors/nvim/README.md` (a worked example, including the fact that Neovim
writes `window/logMessage` at info level and drops it at the default `WARN`
log level). `TODO.md` has no item this completes — the backlog never asked for
instrumentation — so it is untouched.
`smoke.js` is unchanged in behaviour: the only edit is the comment above the
spawn, which claimed the extension passes no arguments and now says it passes
none *by default*. It still spawns with `[]` and still passes.
**The verbose-off cost, measured against HEAD.** The claim is that a server
built with this round and started *without* the flag is indistinguishable from
the one at HEAD. Both are release builds of the same tree — HEAD's binary was
built and copied aside before the first edit — and each was driven through the
same scripted session: one 400-line buffer, 2,000 `textDocument/hover`
requests, client-observed round trips on a monotonic clock
(`time.perf_counter`), five runs of each binary, strictly alternating, on an
M1 Max.
| binary | each run's median, sorted | median of those |
|---|---|---:|
| HEAD `46e7b31…`, no args | 0.0265 0.0268 0.0268 0.0274 0.0283 | **0.0268 ms** |
| this round `21da327…`, no args | 0.0261 0.0262 0.0271 0.0280 *0.0510* | **0.0271 ms** |
| this round, `--verbose` (3 runs) | 0.0413 0.0451 0.0454 | **0.0451 ms** |
The off path is **unmeasurable**: the two no-argument binaries are 0.3 µs
apart — about 1 %, against a 1.8 µs spread *between runs of the same binary* —
and the new one is the faster of the pair in three of the five pairings, which
is the shape of noise rather than of a cost. That is what one predictable
branch on a `bool` field buys you: nothing this instrument can see. (The
italicized 0.0510 is the very first run after the binary was copied into place,
with the file cache cold and the machine still busy from the build; it is left
in the table rather than dropped, and the median is why it does not matter.)
Turning the flag **on** costs 14–18 µs per request, which is the extra
`window/logMessage` written before the response. That is half again as long as
a null hover like this probe's, and about 1 % of the 1.35 ms a real cold hover
over opentitan takes (`performance.md` §2). It is a real cost, which is why the
shipped state is off — but it is nowhere near large enough to change what the
lines it buys are measuring.
The probe is
`…/scratchpad/verbose_cost.py <binary> [--verbose]`; it needs no fixture but
its own temp buffer, so it can be re-run against any two builds.
**Note on TOPO.md.** The spawn-contract row this round amends was rewritten in
`topo.md` from outside this work while it was in progress (the file is
`TOPO.md`/`topo.md`, one file on a case-insensitive filesystem; its mtime moved
mid-round, and the whole document was re-dated to 2026-08-29 for several
rounds at once). The amendment already there states exactly what was built —
`[]` or `['--verbose']`, every other argument refused with exit 2, the restart
on the setting, `smoke.js` still driving the default spawn — so it was left
alone rather than written twice. Nothing else in the tree was touched from
outside; `git diff --stat` at the end of this round is this round's files plus
that one document.
## QA log
### 2026-08-29 — QA agent
Adversarial pass over the round described in the work log above. Verified by
**reading**: `crates/lucisv_server/src/main.rs`, `server.rs` (the whole diff,
line by line), `editors/vscode/extension.js` (the whole diff, and its
existing code around `client`), `editors/vscode/node_modules/vscode-languageclient`
9.0.1's `lib/common/client.js` (the real `start()`/`stop()`/`shutdown()` state
machine this round's restart relies on), `topo.md`, and every touched doc.
Verified by **test**: gates below, plus one new permanent regression test and
a standalone headless harness (not committed — see finding 1).
**Finding 1 — HIGH — `restartForVerbose` silently drops the toggle if it is
called while a `start()` is already in flight.** `editors/vscode/extension.js:284-304`.
`vscode-languageclient` 9.0.1's `BaseLanguageClient.start()` (`client.js:642-653`)
returns the *existing* `_onStart` promise whenever one is set, regardless of
whether the client is `Starting` or `Running` — it only throws when the state
is `Stopping`. `_onStart` is set the moment the first `start()` call begins
and is cleared **only** by a stop that actually reaches `cleanUp()`
(`client.js:988-992`). Consequently, a `client.stop()` issued while the state
is `Starting` hits `shutdown()`'s `"Client is not running and can't be
stopped"` branch (`client.js:960-965`) and rejects — which
`restartForVerbose`'s `try/catch` swallows exactly as it swallows "nothing to
stop" — and the subsequent `await client.start()` then just **joins the
original, already-in-flight start**, which captured the *old* `args` before
the toggle ever wrote the new ones into `serverOptions.args`. The function
then reaches `repaintVisible()` with no exception, no rejected promise, no
message anywhere — from the user's point of view the toggle "worked."
This is exactly the scenario the brief names ("toggle while the server is
mid-scan"): a large workspace's startup scan keeps `initialize()` — and
therefore `start()` — in flight for a while, and any `lucisv.verbose` toggle
during that window is lost. It also fires on a second toggle arriving before
a *previous* restart's own `start()` has resolved, i.e. it is not limited to
the very first activation.
Repro (headless, no real VS Code — see "what could not be tested" below):
mock `vscode` and replace `vscode-languageclient/node`'s `LanguageClient`
with a fake whose `stop()`/`start()` reproduce the state transitions read
above (join-if-in-flight, throw-if-not-Running/Stopping); `activate()` a
context, flip the fake `lucisv.verbose` setting and fire
`onDidChangeConfiguration` once, 5ms into a 30ms fake startup `start()`
(modeling a slow initial scan), then let everything settle. Observed:
```
spawn attempt #1 args=[]
running with args=[]
setting at end: verbose=true
```
Only one spawn ever happens, its args are the stale `[]`, and the setting
is left reading `true` while the running server has no `--verbose` — with
no error surfaced anywhere. The harness (`harness.js`, plus three other
scenarios that confirm rapid on→off→on *does* converge correctly once the
client is already `Running`, and that toggling after a genuine
`StartFailed` is at least non-throwing) lives at
`…/scratchpad/restart-harness/harness.js` in this QA session and was not
copied into the repo: it reimplements the vendored library's state machine
from the source cited above rather than driving the real one, so it is
strong enough to pin *this* extension's own guard/ordering logic but not a
substitute for an in-VS-Code integration test. Formalizing it (or a
real-`vscode-languageclient`, fake-`vscode` version of it) as a permanent
check is a design decision for the dev/lead, not something QA should decide
unilaterally.
Not filed as a fix because the right shape (retry-after-settle? track a
"desired args" and reconcile once any in-flight transition finishes? a
queue?) is itself a design call — flagging for dev/lead per "you verify, you
don't redesign."
**Finding 2 — LOW, fixed directly — cancel/timing interaction was
unspecified.** The brief's adversarial charter asked explicitly: "cancel a
request and check the timing line story... check the dev documented it." It
was not documented anywhere, and no test exercised `--verbose` together with
the cancel path. By reading `server.rs:479` (cancelled requests are
answered from the `cancelled` set inside `process_batch`, before
`self.request(request)` is ever called): a cancelled request gets **no**
`answered in` timing line, since the timed wrapper never runs. This is a
reasonable, already-consistent-with-the-rest-of-the-feature choice (matching
the `reindex_one`-declined and shutdown-during-scan absences the dev already
listed), so I documented it in the feature README's "Two absences are
deliberate" section (now three) and added a permanent regression test,
`a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing`
in `crates/lucisv_server/tests/e2e.rs`, which re-runs the existing
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each` flood **with
`--verbose`** and additionally asserts: every id still answered exactly once
(protocol-integrity check under load with the timing notify sharing the
writer channel — no reordering or corruption observed), and the count of
`timing: textDocument/formatting answered in` lines equals exactly the
number of requests that were *not* served from the cancelled set (never one
more, for a cancelled id; never one fewer, for a real one).
**Everything else checked and found sound:**
- **Silence when off**: `without_the_flag_not_one_timing_line_is_ever_sent`
covers every instrumented path in one session (request, notification,
scan, widen, flush, reindex_one); confirmed passing. `verbose_flag`'s exit-2
path and the flag's idempotency under repeats are unit-tested in `main.rs`
and pass.
- **HELD line correctness**: `server.rs:459` calls `say_held` before the
request is spliced into `self.held`, so `self.held.len()` at that point is
exactly "already held" as documented — confirmed by reading the ordering
in `process_batch`.
- **Ordering**: the request's `timing:` line precedes its response by
construction (`request` sends the notify, then returns to the caller which
sends the response) — confirmed by reading and pinned by the dev's own
`line_at < response_at` assertion in
`the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel`.
Confirmed no deadlock risk: `notify`/`timing` go through the same
fire-and-forget `bounded(0)` writer-thread channel every other
notification already uses; nothing in the loop holds a lock across it.
- **`didOpen` buffer survives a restart** (brief: "verify, don't assume"):
read `vscode-languageclient`'s `textSynchronization.js:38-53`
(`DidOpenTextDocumentFeature.register` walks `vscode.workspace.textDocuments`
and resends `didOpen` for every one matching the selector) and
`client.js:1005-1007` (`cleanUp()`, run by every successful `stop()`,
clears `_syncedDocuments`) — so a fresh `start()`'s `initialize()` always
re-syncs every currently-open buffer to the new server process. Verified by
reading the real vendored library; not exercised in a live VS Code window
(not available in this environment).
- **Decorations repaint after restart**: `restartForVerbose` calls
`repaintVisible()` after a successful `start()` — confirmed by reading;
not exercised in a live window.
- **`StartFailed` toggle does not throw**: `shutdown()`'s "not running"
branch and `start()`'s Stopping-only throw mean a toggle issued after a
failed start is caught by the existing `try/catch`s and returns quietly.
It also does not *retry* the spawn in that state (`_onStart` is never
cleared by a failed start, so a later `start()` just re-joins the same
rejected promise) — this looks like a pre-existing limitation of
`vscode-languageclient` itself rather than something this round
introduced, but it means "fix the bad `serverPath` and toggle verbose to
recover" will not work; a window reload is still required, same as it was
for `lucisv.serverPath` before this round. Not filing as a new finding
since the brief only asked whether `restartForVerbose` explodes (it does
not) — noting it here so it isn't lost.
- **Off-path cost**: re-ran `…/scratchpad/verbose_cost.py` — built a fresh
release binary of this round's tree and, separately, one from a clean
`git worktree` at `HEAD` (pre-round). Off-path medians over 3×2000 hovers:
HEAD ≈0.0292–0.0341 ms, this round (no args) ≈0.0262–0.0316 ms — well
inside the run-to-run spread of a single binary, confirming "unmeasurable."
`--verbose` medians ≈0.0440–0.0449 ms, a ~12 µs delta consistent with the
dev's reported 14–18 µs. Independently reproduced, not just re-read.
- **Contract coherence**: `topo.md`'s §1.2 spawn-contract row, its new
verbose-timing handshake row (§2.7), the `lucisv-server` README's new
argument table, `editor-settings`' README, `editors/vscode/README.md`'s
settings table, and `package.json`'s `markdownDescription` all state the
same contract (`[]`/`['--verbose']`, exit 2 on anything else, restart on
change). No mismatch found; `topo.md`'s pre-existing edit (noted in the
work log as done outside this round) matches what was actually built.
- **`smoke.js`**: diff is comment-only; still spawns `[]`; ran it directly
(`node smoke.js <built-binary-path>`) — passes.
- **nvim doc's `WARN`-level gotcha**: plausible and consistent with
Neovim's documented default log level (`WARN`) and its historical mapping
of LSP `MessageType.Log` to `INFO` in `window/logMessage`, but I do not
have a Neovim binary in this sandbox to execute against, so this is
recorded as read-only-verified-from-memory, not executed — worth a real
Neovim smoke check before anyone treats it as pinned.
**Gates, all green:**
- `cargo fmt --check` — clean (after formatting the test I added).
- `cargo clippy --all-targets --all-features` — clean, no warnings.
- `cargo test --workspace --release` — every crate green, including the
4 new e2e cases, the 4 new `main.rs` unit tests, and my added e2e case
(63 passed in `lucisv_server`, up from 62; 2 pre-existing perf tests
remain `#[ignore]`d as designed).
- `node editors/vscode/smoke.js <release binary>` — OK (needed an explicit
path; there is no `lucisv-server` on this sandbox's `PATH`, unrelated to
this round).
**Verdict: REWORK (one finding, severity HIGH; everything else SHIP-clean).**
Finding 1 is a genuine silent-failure in brand-new restart machinery, exactly
in the adversarial charter's target zone ("a restart that loses state") —
recommend the dev address it (likely: track the last-desired args and
reconcile once whatever transition is in flight settles, retrying rather
than assuming one attempt suffices) and add a regression check for it before
shipping the extension-side half of this round. The server-side half (the
actual timing instrumentation, the flag parsing, the protocol-safety
properties) is solid: every adversarial angle in the charter came back clean
or was closed with a new permanent test this pass.
### 2026-08-29 — QA agent (re-verification of the rework)
Focused pass over `editors/vscode/restart.js` (new), `restart_test.js` (new),
the rewritten `extension.js`, `.vscodeignore` and `tools/RELEASING.md`. Not a
full re-run of the earlier charter — the server side is untouched by this
rework (confirmed: `crates/` diff stat unchanged since the first pass) and was
not re-audited.
**1. Every entry point into `client.start()`/`client.stop()`, and whether
`desiredArgs` is ever read non-synchronously.** `grep -n "\.start(\|\.stop("
extension.js` finds exactly two live call sites outside comments:
`restarter.start()` (`extension.js:260`, the activation spawn, now the first
link of the chain) and a direct `client.stop()` in `deactivate()`
(`extension.js:270`). Inside `restart.js`, `client.start()`/`client.stop()`
are called from exactly one place, `reconcile()`, which only ever runs
serialized on `chain` — so within `restart.js` there is no second entry point,
confirming the module's own claim. `serverArgs()` (`extension.js:289`) is a
plain synchronous read of `vscode.workspace.getConfiguration`, called at
exactly two sites (`extension.js:157`, `241`), both of which pass its result
straight into `want()`/the initial `serverOptions.args` with no `await`
between the read and the write — no non-synchronous read of desired arguments
anywhere. **However** — see finding 3 below — `deactivate()`'s `client.stop()`
is a transition that happens **outside** the chain, which is exactly the kind
of second entry point the module's own header comment (`restart.js:18-20`)
says must not exist ("Nothing else starts or stops the client"). It is
guarded by waiting for `settled()` first, but that guard has a gap.
**2. My own mutation pass (two mutations, not the dev's three), against
`restart_test.js`, restored after each:**
- Dropped the `.catch(onStartFailed)` in `queue()` (`restart.js:97`,
`chain = chain.then(reconcile).catch(onStartFailed)` →
`chain = chain.then(reconcile)`), so a failed start poisons the chain
instead of leaving it usable. Caught immediately:
`restart: FAIL — Error: spawn ENOENT` (the unhandled rejection propagates
out of `main()`), at the very next test that hits a failure. Restored,
confirmed byte-identical to the pre-mutation file (`diff` clean) and
`restart_test.js` green again (28/28).
- Made `sameArgs` treat `null`/`null` as equal (`restart.js:29-32`, added
`if (a === null && b === null) return true;` before the existing checks).
Caught immediately by the direct unit case:
`restart: FAIL — not even against another nothing — a failed start must
retry`. Restored and re-verified green.
Both mutations were caught by the shipped test without needing a third or
fourth attempt — the suite has good discrimination on the two properties the
brief specifically flagged as easy to get wrong.
**3. Fake-client honesty, against my earlier reading of the real
`BaseLanguageClient`:**
- The fake's `start()`/`stop()` are simpler than the real state machine (no
"return the in-flight promise" join behavior, no `Starting`/`Stopping`
state at all) — but this is not dishonesty, it's the point: `restart.js`'s
whole fix is that it never calls `client.start()`/`client.stop()`
concurrently with itself, so the real library's join/reject-while-Starting
behavior (`client.js:642-653`, `960-965`) is now dead code from
`restart.js`'s point of view, and a fake that doesn't model it is testing
the right surface. `aStopThatRejectsDoesNotStopTheRestart` explicitly
covers the one real behavior that still matters (a `stop()` can reject),
which is the only piece of the real state machine `restart.js` still has to
tolerate.
- **One real gap, LOW:** `aFailedStartIsReportedAndTheChainStaysUsable`'s
fake lets a *second* `start()` call succeed once `failNextStart` is
consumed, and its comment reads "...which is what a user who fixed their
`serverPath` does" — read on its own, that suggests fixing the path and
toggling again brings the server up. Against the real library it does not:
per `client.js:651-653`, `_onStart` is never cleared by a failed start, so
a real second `client.start()` call returns the *same* rejected promise
without attempting a new spawn at all, regardless of whether the
underlying problem was fixed — which is exactly the "known, not this
round's to fix" item the README already states two sections above
(lines 219-224). The test's own assertions are still accurate (they check
that `restart.js` *asks* again, not that the ask succeeds), so this is a
comment-clarity nit, not a wrong assertion — worth a one-line tweak
("...which is what `restart.js` retries regardless of whether the real
client can act on it — see the known limitation above") but not a
regression or a blocker.
- The known-not-ours limitation itself: confirmed the README states it
plainly (lines 219-224) and that the code degrades to *exactly* that,
not worse — `reconcile()`'s catch sets `runningArgs = null` and rethrows
unconditionally on any `start()` rejection, real or fake, so a real
`StartFailed` rejoin is reported once per toggle (never silently dropped)
and every subsequent toggle keeps asking, forever, which is the documented
"asks correctly, library declines" shape.
**4. Toggle-while-deactivating — read, then confirmed by executing the real
`restart.js`: yes, a `want()` landing after `deactivate()` has read
`settled()` can spawn a process nothing will subsequently stop.**
`deactivate()` is:
```js
return restarter ? restarter.settled().then(() => client.stop()) : client.stop();
```
`settled()` returns whatever `chain` currently *is* — a snapshot, not a live
reference — and `deactivate`'s own `client.stop()` is attached as a `.then`
sibling on that snapshot, **not** enqueued through `want()`/`reconcile`. So
`deactivate` never marks the restarter as done, and nothing stops a `want()`
call (a stray `didChangeConfiguration` for `lucisv.verbose`, arriving from a
settings-sync apply or a user toggling right as the window closes) from
calling `queue()`, which mutates the *live* `chain` variable and queues a
perfectly normal `reconcile()` — stop, then **start a new process** — as a
second sibling off the same snapshot.
Reproduced directly against the shipped `editors/vscode/restart.js` (fake
client, no reimplementation of the library — script available on request,
not committed):
```
start([])
onStarted
--- activation settled, deactivate begins ---
stop()
stop()
start(["--verbose"])
onStarted
```
`deactivate()`'s own `client.stop()` resolves first (it was attached first),
but the `want()` fired in the same tick still runs its full `reconcile()`
afterward — including a fresh `client.start()` — with nothing left to await
it: `deactivate()` already returned a promise that resolved after the first
`stop()`, so whatever waits on `deactivate()` (VS Code's extension host) has
no way to know a second spawn is happening. In the common case (whole window
closing) the new child's stdin pipe dies with the parent process and
`lucisv-server`'s own loop exits on that EOF, so this self-heals; the bad
case is an extension disable, or an extension-host-only restart, where the
host process outlives the module unload — there the new process has no
remaining handle anywhere in the extension and is a genuine orphan. This is
the round's own target sin ("a restart that loses... servers"), reachable
only through this specific race, in code the rework just wrote.
**Verdict on item 4: confirmed real, not ruled out.** Filed as a new finding
rather than fixed directly, since the right shape is a design call (a
`disposed` flag that makes `want()` a no-op after `deactivate` starts; or
routing `deactivate`'s stop through the same chain, e.g.
`chain = chain.then(() => client.stop())` before returning it, so a `want()`
racing it queues *after* the stop instead of beside it) — QA verifies, it
doesn't redesign.
**Finding 3 — MEDIUM — `deactivate()` is a transition outside the chain and
can race a concurrent `want()` into spawning an orphaned server process.**
`editors/vscode/extension.js:264-271`. See reproduction above. Requires a
`lucisv.verbose` configuration-change event to land in the same microtask
turn as (or after) `deactivate()` reading `restarter.settled()` — a narrow
window, and self-healing in the ordinary whole-window-close path — but
confirmed reachable by direct execution against the shipped module, and it
is exactly the failure class ("loses servers") the brief's top-level charter
named. Recommend closing before shipping, given how cheap the fix looks
(routing `deactivate`'s stop through the chain, or a disposed-flag guard on
`want`), but it does not block on its own the way finding 1 did — the
common-case teardown path is not at risk.
**Gates, all green (re-run in full since a prior pass, given the file
changes span both sides):** `cargo fmt --check`, `cargo clippy --all-targets
--all-features`, `cargo test --workspace --release` (unchanged pass counts
from the first QA pass — the rework did not touch `crates/`), `node
editors/vscode/smoke.js <release binary>`, `node
editors/vscode/restart_test.js` (28/28).
**Verdict: SHIP with one open item (MEDIUM).** Finding 1 (HIGH, the silent
lost-toggle) is closed: the chain construction is sound, the fix targets the
actual root cause (the activation spawn now being the chain's first link),
and both my own mutations plus the dev's own three were caught by
`restart_test.js`. Finding 2 (LOW, cancel/timing) remains closed from the
first pass. The new finding 3 (MEDIUM, the deactivate race) is real but
narrow, self-healing in the common teardown path, and does not reopen finding
1 — it is a defensible ship-with-a-followup rather than a hold, but the lead
should decide whether a same-round fix (small, per the two options above) is
warranted before release given how directly it falls under this round's own
charter.
## Review
**2026-08-29 — lead.** Reviewed across the full loop: dev, QA REWORK
(HIGH: a toggle mid-start silently rejoined the stale start), rework 1,
QA re-verify (SHIP plus a new MEDIUM: deactivate's stop outside the
chain could orphan a server), rework 2, and the lead's own gate run
(fmt clean, clippy silent, 2540 workspace tests, smoke OK, restart
harness 44/44). The server half was clean from the first pass: exact
diagnostic-build wordings kept, off-path cost measured unmeasurable
against HEAD by dev and QA independently, ordering and no-deadlock
arguments written rather than assumed, and the cancelled-request
absence made deliberate. The extension half is where the loop earned
its keep twice — both findings came from reading the pinned library's
real state machine, and the final shape is the right invariant stated
the right way: one chain, no transition outside it, reconciled to the
last toggle, with dispose() closing the door on both entry points.
The committed headless harness with five mutation checks is exactly
how extension-side machinery should be tested in a repo whose CI has
no VS Code; QA's fake-client honesty check and the plainly-documented
library limitation (_onStart never clears after StartFailed — reload
still required) keep it honest. The spawn-contract amendment is
consistent across topo.md, both server docs, both editor READMEs and
the manifest. Accepted; committed by the lead.
*(reserved for the lead)*
+33
View File
@@ -443,6 +443,39 @@ Checks at the end: `cargo test -p vlog_semantic` 26 tests green (19 + 6 + 1),
`cargo clippy -p vlog_semantic --all-targets` silent, `cargo fmt` clean,
`cargo test --workspace` green.
**2026-08-28 — `WorkspaceIndex::files_spelling`, lead-authorized, additive.**
One new query, requested by refactor-rename's performance round after QA found
a lost refusal in it; the second authorized cross-module change that feature
has made (M2's `Target::Declaration` was the first).
```rust
pub fn files_spelling(&self, name: &str) -> impl Iterator<Item = FileId> + '_
```
Every file holding an **external reference fact** spelling `name`, whether or
not it resolved. Nothing was renamed, removed, re-spanned or re-ordered; no
new state, no new field, and **`FACTS_FORMAT` is untouched** — it reads the
`FileFacts::references` records the index already keeps, which is why it can
answer at all. A linear walk over those records in `FileId` order.
Why it belongs here rather than in the caller: `reference_sites` is keyed by
`DefinitionKey`, so a use that resolved to **nothing** is in no posting — the
right shape for "who refers to this declaration", the wrong one for "which
files would notice if this name started meaning something". The second
question is what a rename must ask about the name it renames *to*, and the
records that answer it are `pub(crate)`. The alternative was for the server to
re-derive it by reading and analyzing every file, which is the workspace read
that round exists to remove.
The property callers now depend on, stated so it moves under supervision:
`facts_from_analysis` records a `ReferenceFact::External` for every
`ExternalCandidate`/`InheritedCandidate` with a non-empty path list,
*including the ones the index cannot resolve*. `merge_references` then drops
the unresolvable ones when building postings — that drop is what
`files_spelling` exists to see past. If the recording rule narrows, say so in
`docs/features/refactor-rename/README.md`'s Handshakes, whose rung 6 rests on
it. Tested by `tests/workspace.rs::files_spelling_finds_the_uses_no_posting_can_be_keyed_by`.
## QA log
**2026-08-19 — QA agent.** Verified against `crates/vlog_semantic/src/{lib,model,bind,resolve,scan}.rs`
@@ -0,0 +1,806 @@
# vscode-hierarchy-sidebar
## Goal
Give the lucisv VS Code extension its own Activity Bar container with a
**Hierarchy** view: a persistent fuzzy-search field above an alphabetical,
folder-like module-instance tree. LSP call hierarchy deliberately groups a
module's calls by target module *type*; this view needs the other reading of the
same facts — every individual instance name, its source range, and every
declaration its type may name — so the server answers a custom
`lucisv/moduleHierarchy` snapshot and notifies `lucisv/moduleHierarchyChanged`
whenever the installed index changes. The snapshot is **flat**: the client picks
roots and opens paths, which keeps recursion out of the protocol and lets one
answer serve both rendering and search. This is a textual design hierarchy, not
an elaborator: generate loops appear once as written, both preprocessor arms may
appear, parameters are not evaluated, and instance arrays are not expanded into
numeric elements.
For a design such as:
```systemverilog
module TB;
top dut ();
endmodule
module top;
block inst1 ();
endmodule
module block;
leaf inst2 ();
endmodule
```
the view begins collapsed at `TB` and opens, one level at a time, to
`TB` → `dut (top)` → `inst1 (block)` → `inst2 (leaf)`. The root label is a
module name; every child label leads with the instance name and includes its
module type, so both names are visible and both are searchable.
### Product behaviour (codex's specification, amended where noted)
**Tree and roots.**
- Show every uniquely declared module reachable from a root through instance
edges. Roots are modules with no resolved parent, sorted case-insensitively;
children are sorted by instance name, then module name, then source URI and
position for a deterministic tie-break.
- Show an unresolved instantiated type as a non-expandable warning row.
Navigation to the instance still works; "Show Definition" explains that no
definition is indexed.
- Keep an ambiguous type visible as a non-expandable warning row. "Show
Definition" offers a Quick Pick of candidates instead of guessing.
- After the ordinary zero-parent roots, add any declaration a root never
reaches because it sits in a recursive strongly connected component. Those
fallback roots are marked, and the repeated edge inside them is marked
`recursive` and does not open again, so `A -> B -> A` is visible without an
infinite tree.
- Two declarations of one module name in different files are distinct
definitions, identified by URI and position.
- The view reflects exactly the server's current index scope.
- **Amended, owner 2026-08-29: every level starts collapsed.** Nothing expands
on the view's behalf, on open or on refresh; the one exception is the ancestor
chain of a bookmarked row, which the user asked for by bookmarking.
**Search.**
- A real text input stays fixed above the tree — not a toolbar command, not an
InputBox.
- Matching is case-insensitive against exactly two fields, module name and
instance name. Never paths, filenames, directories, preview text, ports or
connection expressions.
- The scorer is a deterministic fuzzy subsequence with exact, prefix,
word-boundary and consecutive-character bonuses; an instance-name score wins a
tie against a module-name score by one.
- **Amended, owner 2026-08-29: a query renders a ranked, capped result list
rather than a filtered tree.** A flat model has no one path per instance, so a
match is one row that names the module writing it. The tree is not torn down
while searching, and clearing the query restores it — same rows open, no
snapshot re-request. Results cap at 200 with an `N more matches` line.
**Navigation, context menu and bookmark.**
- Clicking an instance selects its instance-name range at the instantiation;
clicking a root module selects its module declaration.
- The context menu is reachable with the mouse and with Shift+F10 / the Menu
key, and rows carry ARIA tree roles, levels, expanded state and labels:
- **Copy Full Path** — `TB.dut.inst1.inst2`; the root segment is the root
module name and every later segment an instance name. *Tree rows only.*
- **Show Definition** — opens the instantiated module's declaration and
selects its name; a Quick Pick when ambiguous, a concise warning when
unresolved.
- **Show Instance** — the normal instance click's destination.
- **Highlight / Bookmark** — one workspace-scoped bookmarked path, painted
with a yellow theme token, ancestors expanded and the row revealed. The
logical full path is persisted in `workspaceState`, re-resolved after every
refresh, and dropped with an explanation if it stops existing or stops being
unique. *Tree rows only.*
- **Open on the Right** — the module definition in `ViewColumn.Beside`, pinned
as a non-preview editor.
- **Removed, owner 2026-08-29: the five-line hover source preview.** See the
work log; it was the feature's last consumer of file text.
### UI architecture
One contributed `WebviewView`, not a `TreeDataProvider`: VS Code's native tree
API gives excellent rows and context menus but no persistent text input inside
the view, and a webview is the only stable API at the extension's VS Code floor
(`^1.82.0`) that satisfies the literal search-bar layout. `package.json`
contributes a `lucisv` Activity Bar container with a monochrome SVG icon, the
`lucisv.hierarchy` webview view, `onView:lucisv.hierarchy` activation, and
refresh / clear-bookmark commands.
`extension.js` stays the lifecycle owner; the feature lives in focused CommonJS
modules:
- `hierarchyModel.js` — response validation, the flat resident model, root
choice, lazy tree rows, cycle guards, full paths, sorting and the search
index. No `vscode` dependency, so plain Node tests cover it exhaustively.
- `hierarchyView.js` — the provider: server requests, the model, the expansion
set, navigation, clipboard, persistence and command dispatch.
- `media/hierarchy.js` / `hierarchy.css` — rendering, the search box, disclosure,
the accessible context menu and the message bridge.
- `images/hierarchy.svg` — the theme-neutral Activity Bar icon.
The webview uses a nonce-based CSP, `localResourceRoots`, `asWebviewUri`, HTML
escaping and a fixed allow-list of message types. Rows carry opaque ids and the
extension resolves an id against its current model; no source text, filesystem
path or executable command ever comes back from DOM data. All colours are VS
Code theme variables, with a high-contrast border fallback for the bookmark row.
### Explicit non-goals for the first delivery
- Full SystemVerilog elaboration, parameter evaluation, preprocessor branch
selection, generate-loop expansion, or simulator-specific library binding.
- Searching ports, signals, files, source text, or full hierarchy paths.
- Multiple simultaneous bookmarks, bookmark sync across machines, drag-and-drop,
hierarchy editing, or changing the selected top from the view.
- Replacing the standard LSP call hierarchy; this sidebar is an
instance-oriented companion to it.
## Assumptions
- **A recorded position is a fact about the same snapshot the span is.** A
declaration's byte span and its client position (`vlog_semantic::DeclPositions`)
are read off one text in one pass, so a range and a span can never name
different generations of a file. Where a file changed on disk with nothing
telling the server, both are stale together — the same bargain
`docs/features/hover-line-index/README.md` struck for `DeclLines`.
- **A client position is 0-based lines and UTF-16 code units**, which is what an
LSP `Position` counts in and *not* what `LineIndex::line_col` reports. Both
the index and the wire converter go through one function,
`vlog_parser::LineIndex::utf16_position`, so they cannot answer differently.
- **Only file-scope declarations carry client positions.** A member is a `Decl`
exactly as a unit is, and there are two orders of magnitude more of them; see
Handshakes for the measurement that decided it.
- **A module type resolves to the modules of that name in the same snapshot.**
The server no longer repeats those declarations on every instance; the client
looks them up in its own module table, which is the identical set.
- **The tree is a reading of the index's scope.** If `lucisv.index.scope`, a
filelist, excludes or the large-file policy keeps a file out, it is out of the
hierarchy too.
- **A row id is stable while its declaration does not move.** Ids are composed
from a URI and the declaration's own start position, so the user's expansion
state survives a refresh, a rescan and a restart.
## Handshakes
### `vlog_semantic` — `FACTS_FORMAT` 4 → 5, and what it now carries
One bump, three additions, all folded into the same number (this branch minted
5; nothing here mints a 6):
```rust
pub struct Def {
pub file: FileId,
pub name_span: TextRange,
pub decl_span: TextRange, // new in 5
pub kind: SymbolKind,
pub detail_span: Option<TextRange>,
pub lines: DeclLines,
}
pub struct DeclLines {
pub name: u32,
pub detail: Option<u32>,
pub positions: Option<DeclPositions>, // new in 5 — Some for a unit
}
/// 0-based line, UTF-16 code units — what a client counts in.
pub struct Utf16Pos { pub line: u32, pub character: u32 }
pub struct Utf16Range { pub start: Utf16Pos, pub end: Utf16Pos }
pub struct DeclPositions { pub name: Utf16Range, pub decl: Utf16Range }
pub struct InstantiationEdge {
pub file: FileId,
pub owner: DeclSite,
pub site_span: TextRange,
pub instances: Vec<InstanceOccurrence>, // new in 5
}
pub struct InstanceOccurrence {
pub name: String,
pub name_span: TextRange,
pub span: TextRange,
pub name_positions: Utf16Range, // new in 5
pub positions: Utf16Range, // new in 5
}
// Two added parameters, because a record now carries client positions:
impl FileFacts {
pub fn from_analysis(path, tree, defines, sem, src: &str, lines: &LineIndex) -> FileFacts;
}
pub const FACTS_FORMAT: u32 = 5; // was 4
```
`callHierarchy/incomingCalls`, outgoing calls and code-lens counts still read
the statement-level edge and its `site_span`, so `sub u1 (), u2 ();` remains
**one** call site there. The sidebar alone flattens `instances` into two rows.
There is no second instantiation census to drift from the first: `instances` is
populated from the same `instantiations::sites` walk the call hierarchy reads.
**The carrier extends by gaining a field, exactly as `hover-line-index`
predicted.** `DeclLines` was documented as "a column, or a rendered preview, is
another field written beside these two"; `DeclPositions` is the first of those
fields, written in `Writer::decl`'s group and read in `Reader`'s, with the
format bump any record change owes.
**Why only file-scope declarations carry positions.** Members — ports,
parameters, class fields — are `Decl`s exactly as units are, and on opentitan
there are 1 544 modules against hundreds of thousands of members. Giving every
declaration eight more numbers would have cost, by measurement of the record
shape, several megabytes on a 24.6 MB store to serve a caller that does not
exist. The units and the members are written in two separate groups of a record
(`U` and `M`), so "units carry positions, members do not" costs a member **no
field at all** — not even a presence flag. The day a member wants them, it is
the same eight fields in the other group plus a bump.
### `vlog_semantic` — `WorkspaceIndex::units_of`
```rust
pub fn units_of(&self, kind: SymbolKind) -> impl Iterator<Item = (&str, &Def)>;
```
The cheap half of `workspace_symbols("")` for a caller that wants units and
never members: it walks the unit table alone and sorts nothing, where
`workspace_symbols("")` walks every member of every unit and sorts the lot.
Measured on opentitan: **15 ms per call**, on every snapshot, gone.
### `vlog_parser` — `LineIndex::utf16_position`
```rust
pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32);
```
The byte-offset → (0-based line, UTF-16 column) conversion, moved down beside
the table it reads so that **two callers cannot disagree**: the semantic index
recording a declaration's position while a file is scanned, and
`lucisv_server::convert::Positions::position` converting a span for the wire.
`Positions::position` is now a two-line wrapper over it and its whole existing
test suite passed unmodified. Pinned across the crate boundary by
`design_hierarchy::tests::an_indexed_position_is_the_position_the_wire_converter_would_have_given`.
### `lucisv_server::state` — `Document::facts`
`FileFacts::from_analysis` grew a `src: &str` parameter, because a client
position cannot be read off a line table alone. Its one real caller
(`Document::facts`) already holds that text; the change is a straight
substitution.
### The wire — `lucisv/moduleHierarchy`, schema 2
```json
{
"schemaVersion": 2,
"revision": 42,
"complete": true,
"files": ["file:///w/top.sv", "file:///w/fifo.sv"],
"modules": [
{
"moduleName": "top",
"definition": { "file": 0, "range": [0,0,12,9], "selectionRange": [0,7,0,10] },
"instances": [
{ "instanceName": "u_fifo", "moduleName": "fifo",
"site": { "file": 0, "range": [3,2,3,20], "selectionRange": [3,7,3,13] } }
]
}
]
}
```
A range is `[startLine, startCharacter, endLine, endCharacter]` — an LSP
`Range` with its four field names left off. `range` covers the whole construct,
`selectionRange` its name, exactly the call-hierarchy contract. Modules and
instances are sorted on the server for deterministic protocol tests and sorted
again defensively in the client.
Four things left the wire deliberately, and the client rebuilds all four in
`hierarchyModel.js`'s `validateSnapshot` — see the work log for why:
| gone from the wire | rebuilt as |
|---|---|
| a `uri` on every location | an index into `files` |
| `{ start: { line, character }, end: … }` | four numbers |
| an `id` on every row | `` `${uri}#${line}:${character}` `` of its selection range |
| `definitions` copied onto every instance | the modules of that name, from the client's own table |
`lucisv/moduleHierarchyChanged { "revision": n }` still rides beside the
server's existing code-lens refresh point, so every index-mutation path is
covered once, and is still gated on `initializationOptions.hierarchyView` so no
other LSP client sees unsolicited traffic. A `-32601` from an older binary
renders a compatibility message and leaves every other extension feature
working.
### `complete` — what it promises, and the window it has to be honest about
`complete` is `Server::index_is_complete()`, which is `!scanning &&
!must_wait()`. Both clauses, not just `scanning`: `!scanning` alone answers "is
a scan running *this instant*", and a snapshot taken between a finished scan and
a rescan already asked for would call a stale index complete.
Today that window is unreachable, for two independent reasons, and the second
clause is written down anyway so the flag's honesty does not depend on either:
1. `rescan_wanted` is only ever **set while `scanning` is true**, and is
consumed inside the scan loop before `scanning` goes false.
2. `must_wait()` sets any request aside — held, unanswered — while
`answering_a_rescan` or `rescan_wanted` is set or anything is already
`held`. A snapshot therefore only ever *reaches* the flag with all three
clear. So `complete` is false exactly during the startup scan, which is the
one scan nothing asked for.
Pinned by `server::tests::a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`,
which asserts both halves: the flag is false with a rescan owed, and the request
is held rather than answered off the stale index.
## Status / TODO
- [x] `InstanceOccurrence` on the statement edge, populated through the shared
instantiation walk; call hierarchy and code lenses unchanged.
- [x] `Def::decl_span`, so a module's whole-construct range needs no reparse.
- [x] `DeclPositions` on `DeclLines` for file-scope declarations, and
`Utf16Range` on every instance occurrence — the snapshot's zero-I/O fix.
- [x] `LineIndex::utf16_position`, shared by the index and the wire converter.
- [x] `WorkspaceIndex::units_of`, so a snapshot does not walk every member.
- [x] Record codec: all of the above in `FACTS_FORMAT` 5, with round-trip and
old-format-rejection tests.
- [x] `lucisv/moduleHierarchy` + `lucisv/moduleHierarchyChanged`, gated on
`initializationOptions.hierarchyView`.
- [x] Schema 2: file table, four-number ranges, no ids, no per-instance
definition copies — 11.6 MB → 2.3 MB on opentitan.
- [x] `complete` tightened to `index_is_complete()` and written down.
- [x] Client: flat resident model, lazy tree levels, prebuilt search index.
- [x] Owner 2026-08-29: hover source preview removed.
- [x] Owner 2026-08-29: every level collapsed by default.
- [x] Owner 2026-08-29: search runs in memory, debounced, capped, and never
re-requests or rebuilds.
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`, and
all four node scripts.
- [ ] **Not done, deliberately: `locate::location` is not rewired onto
`DeclPositions`.** `textDocument/definition`, references, the lens and
both hierarchies still read a file to convert a `Def`'s span to a
`Location`, and every unit's range is now in the index for free. It is a
real second consumer and a real saving, and it is a different change to a
different feature's file — filed, not smuggled in.
- [ ] **Not done: members carry no client positions.** See Handshakes for the
cost that decided it; a port-oriented caller would add them to the `M`
group.
- [ ] Manual extension-host acceptance: themes, keyboard-only navigation, zoom,
screen-reader labels, an empty workspace, an old server binary, and both
universal and platform VSIX builds.
## Work log
### 2026-08-29 — codex (implementer of the feature)
The feature itself — the plan, the semantic facts, the custom request and
notification, the webview shell, navigation, the context menu, the bookmark, the
`FACTS_FORMAT` 4 → 5 bump and the committed node tests — was designed and built
by **codex** in this worktree on branch `codex/vscode-hierarchy-sidebar-plan`
from base commit `40094c4`. Everything below is a fix round on top of that work;
the shape of the feature, the flat-snapshot decision, the one-edge-per-statement
decision and the client module split are codex's and are unchanged.
### 2026-08-29 — dev (snapshot cost, `complete`, and three owner items)
**The lead's finding, reproduced first.** `snapshot()` read **every**
module-declaring file and built a `LineIndex` over each, per request, and the
client re-pulls on every index change. Over stdio against
`/Users/guoliangchen/repo/opentitan` (3 979 SV files, workspace scope, warm
store, `--release`, `--verbose` so the server times its own handler):
| | before | after |
|---|---:|---:|
| `lucisv/moduleHierarchy`, server-side handler, first | 197 ms | **34 ms** |
| — settled (the number that blocks the queue) | 145–167 ms | **17–20 ms** |
| — end to end over stdio, settled | 265–325 ms | **39–44 ms** |
| a `textDocument/definition` pipelined behind a snapshot | 263 ms | **41 ms** |
| a `didSave` plus the snapshot the client re-pulls | 366 ms | **141 ms** |
| the response itself | 11 559 498 B | **2 335 749 B** |
The requirement was ≤ ~20 ms warm; the settled handler is 17–20 ms, and no
snapshot reads a file at any point.
**(a), not (b), and the measurement says why.** Option (b) — a per-file
snapshot-fragment cache — would have made a *save* cheap and left the first
snapshot of every session paying the whole read (5.0 s cold on the lead's
measurement), and every rescan would have emptied it again. Option (a) makes
**every** snapshot zero-I/O, cold and warm alike, permanently. It is also the
cheaper thing to own: no cache, no invalidation points to keep in step with
`FileView`'s. So (a), and (b) was not needed.
**But (a) alone did not reach the target, and the measurement said so.**
With the reads gone the handler was still 92–130 ms. Instrumented, it split
three ways: `workspace_symbols("")` 15 ms, building the answer 9 ms, and
**~75 ms of JSON for an 11.6 MB response**. The I/O was never the whole bill.
So two more things had to happen, and both are named in the numbers above:
- `WorkspaceIndex::units_of` — the snapshot wanted 1 544 modules and was being
handed every declaration in the workspace, sorted.
- **Schema 2.** A `file:///…` URI was written 15 432 times, a range was four
nested objects with eight field names, every row carried an id built from that
same URI, and every instance carried a full copy of the declarations its type
resolves to. All four are redundant with something the client already has, and
the client rebuilds all four in `validateSnapshot` — so the *model* every
other line of client code reads is byte-for-byte the shape codex designed.
11.6 MB → 2.3 MB. This is the one place the brief's "keep codex's wire shape"
was overridden, and the measurement is the reason: at 11.6 MB the ≤20 ms
requirement is arithmetically out of reach.
**Store growth, measured both ways.** The client positions are the part this
round added:
| store | codex's format 5 | this round | delta |
|---|---:|---:|---:|
| 820-file corpus, workspace scope | 2 519 198 B | 2 561 773 B | **+42 575 B, +1.69 %** |
| opentitan, 3 979 files | 24 663 087 B | 25 122 252 B | **+459 165 B, +1.86 %** |
And against `master`'s format 4 for the whole of format 5 (codex's `decl_span`
plus occurrences, plus this round's positions), on the in-tree 860-file corpus
probe: **2 380 790 B → 2 593 082 B, +212 292 B / +8.9 %**. Scan times over that
corpus are inside their own noise (351 ms cacheless / 377 cold / 205 warm,
against the 350 / 374 / 200 the previous round recorded). This is what the
units-only decision bought: giving every declaration its positions would have
put the growth two orders of magnitude higher on the member count alone.
**One conversion function, not two.** The dangerous part of carrying positions
in the index is that the index's answer and the wire's could drift — a UTF-16
column is exactly the kind of thing two implementations get differently on a
CRLF line or a surrogate pair. So the conversion moved down into
`vlog_parser::LineIndex::utf16_position` and `convert::Positions::position`
became a wrapper over it; `convert`'s existing test suite passed unmodified,
and a cross-crate test now requires the index's recorded ranges to equal the
wire converter's over CRLF, two-, three- and four-byte characters, a name on a
last line with no trailing newline, and two instances in one statement.
**`complete`, tightened and written down** — both, because the brief allowed
either. `index_is_complete()` is `!scanning && !must_wait()`; the second clause
is unreachable today for two independent reasons (`rescan_wanted` is only set
while `scanning`, and `must_wait` holds any request owed a rescan), both spelled
out in Handshakes and pinned by a test that asserts the flag *and* the holding.
**The v4-store discard path covers format 5, confirmed.**
`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread`
loops `1..FACTS_FORMAT`, so it already discards a format-4 store by the header —
it was rewritten away from a pinned literal in the `hover-line-index` round for
exactly this. Its belt-and-braces half, though, had gone stale: its stripper
produced a record that was neither format 3 nor 4, so the test passed for the
wrong reason. Rewritten as `as_a_format_4_record`, which removes all three of
format 5's additions and yields the record format 4 genuinely wrote (verified by
hand against the encoded fixture); `decode` still returns `None`.
`vlog_semantic`'s two generalized strippers were corrected for the new field
widths in the same way.
#### Owner item 1 (2026-08-29) — the hover source preview is gone
Removed entirely: `HierarchyView.preview`, the `hover` message, the
`schedulePreview`/`showPreview`/`hidePreview` triplet and the `mouseenter`/
`mouseleave` listeners in the webview, the `#preview` element and its CSS. It
was **the last consumer of file text in the whole feature**: with it gone the
extension host opens a document only when the user navigates to one, and the
snapshot's zero-I/O property is now the whole story rather than half of it. The
view test asserts positively that a `hover` message posts nothing back and that
the popover is gone from the markup, so the code cannot quietly return.
#### Owner item 2 (2026-08-29) — every level collapsed by default
The webview used to expand every root whenever nothing was expanded; that is
gone. This is a `WebviewView`, not a `TreeDataProvider`, so the equivalent of
`collapsibleState: Collapsed` is that the host's `expanded` set starts empty and
only a user `toggle` adds to it. Two expansions survive, and both are the user's
own act rather than a default: the ancestor chain of a **bookmarked** row (the
feature's stated contract — bookmarking reveals) and, while a query is active,
nothing at all, because search now renders a flat list instead of a filtered
tree.
**Expansion state across a refresh — verified.** A row id is
`root:<uri>#<line>:<character>` for a module and `<parent id>><uri>#<line>:<character>`
per level below, composed in the client from the location itself. It does not
depend on array order, on a `FileId`, or on byte offsets, so a rescan that adds
or removes files elsewhere leaves every unaffected row's id identical and the
open rows stay open. Pinned by
`hierarchyModel_test.js::rowIdsSurviveARefresh`, which reverses the module order
in a second snapshot and requires the same ids and the same opened rows.
#### Owner item 3 (2026-08-29) — the search freeze, diagnosed and fixed
**The mechanism, named.** It was not a per-keystroke server request, and it was
not unbounded rendering alone. It was three things compounding, all synchronous
on the extension host and then again on the webview thread:
1. **`buildHierarchy` materialized the entire expanded tree** the moment a
snapshot arrived. `instanceNode` recursed into its target module's instances,
so a module instantiated in ten places duplicated its whole subtree ten
times. On a real design that is combinatorial in depth — opentitan's 1 544
modules and 13 888 instances expand to far more nodes than there are
instances.
2. **Every keystroke walked that whole tree.** `search` was posted on the raw
`input` event with **no debounce**; the host ran `filteredHierarchy`, which
visited every node and called `fuzzyScore` twice per node, each call
`toLowerCase()`-ing a name — one allocation per node per keystroke.
3. **Every keystroke then shipped the whole tree to the webview.**
`render()` posted `roots: model.roots.map(serializeNode)` — a deep copy of
every node, structured-cloned across the webview boundary — and the webview
rebuilt its `nodes` map and re-created DOM for everything visible, with no
cap.
**The fix, against each of the three.**
1. *Resident and flat.* `buildHierarchy` now keeps exactly the snapshot —
modules and their instances — plus a resolved `targetId` per instance and a
reachability pass over the **module** graph (one visit per module) to pick
roots. A tree row is built only when its parent is open: `treeRows(model,
expanded)` walks roots and descends only into expanded ids. A collapsed tree
over 100 000 instances is one row per root and costs **0.02 ms**.
2. *One prebuilt index, scanned once per query.* `searchIndex` builds one entry
per module and per instance at snapshot time, each carrying its two names
**already lowercased** and two character bit sets. A query lowercases and
splits itself once, then makes one pass: an entry whose bits do not cover the
query's cannot contain the query's characters and is never scored at all.
The top rows are found by **counting hits per score and walking down from the
top** rather than sorting — a one-letter query matches nearly every name, and
sorting 100 000 hits to show 200 of them was most of a frame by itself. Ties
break by index order, which is modules alphabetically and then instances
alphabetically, so the answer is deterministic without comparing any strings.
Input is debounced 60 ms in the webview.
3. *Only the rows shown cross the boundary.* The host posts a flat `rows` array
— the open part of the tree, or one capped page of results — never a tree.
The webview keeps two containers and a query swaps which is shown, so
searching never tears the tree down and clearing the search puts back exactly
the rows that were open, with no snapshot re-request. Results are capped at
200 with an `N more matches — narrow the search.` line.
**Before and after, on the generated fixture the node suite now carries**
(20 000 modules × 5 instances = 120 000 search entries, ~6× opentitan):
| | before | after |
|---|---:|---:|
| build the model from a snapshot | did not finish — the expanded tree is unbounded | 183 ms, once per revision |
| the collapsed tree's rows | (whole tree) | 0.02 ms |
| `u` (matches all 100 000 instances) | — | 3.0 ms |
| `u_inst` | — | 4.4 ms |
| `u_inst_1` (73 756 matches) | — | 8.2 ms |
| `mod_999` (444 matches) | — | 5.6 ms |
| `zzz` (no match) | — | 0.8 ms |
The owner asked for "microsecond level". Per entry that is what an array scan
gives — 3.0 ms over 120 000 entries is **25 ns each**; per *query* the honest
equivalent at that size is single-digit milliseconds, which is what the table
shows and what `searchOverAHugeHierarchyStaysInsideItsBudget` asserts. The
assertion itself is 60 ms, an order of magnitude of headroom, so a busy machine
cannot make a test that is about orders of magnitude flake.
**One behaviour changed as a consequence, and it is worth naming.** Codex's plan
had search *filter the tree*, keeping each match plus its ancestor chain. A flat
model has no one path per instance — an instance reached through three different
parents is one row, not three — so search now renders a ranked, capped result
list, each row saying which module writes it, and clicking navigates. The two
context actions that need a path (Copy Full Path, Highlight/Bookmark) stay
tree-only and say so when invoked from a result; Show Definition, Show Instance
and Open on the Right work from either. This is the shape the owner's
"cap rendered results with a N more… affordance" asks for.
**Files touched.** `crates/vlog_parser/src/line_index.rs`,
`crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/{design_hierarchy.rs,convert.rs,server.rs,state.rs,index_cache.rs}`,
`editors/vscode/{hierarchyModel.js,hierarchyView.js,hierarchyModel_test.js,hierarchyView_test.js,smoke.js,README.md,CHANGELOG.md}`,
`editors/vscode/media/{hierarchy.js,hierarchy.css}`, this README,
`docs/features/{workspace-index,index-persistence,hover-line-index}/README.md`,
`TOPO.md`, `TODO.md`. No new dependency, no `unsafe`, no `#[allow]`, no
`FACTS_FORMAT` 6, no version bump, no commits.
**Tests added.**
| test | where | pins |
|---|---|---|
| `a_file_scope_declaration_carries_its_client_ranges` | `vlog_semantic/tests/workspace.rs` | the extension: a unit's name and decl ranges, 0-based and UTF-16 |
| `client_ranges_count_utf16_units_not_bytes` | same | a four- and a two-byte character ahead of a name shift the client column away from the byte column |
| `every_instance_occurrence_carries_its_client_ranges` | same | both ranges on both instances of one statement |
| `a_member_carries_lines_but_no_client_ranges` | same | the units-only decision, stated as a property |
| `utf16_positions_are_zero_based_and_count_code_units` | `vlog_parser/src/line_index.rs` | surrogate pairs, mid-character flooring, clamping past the end |
| `a_crlf_is_not_part_of_its_lines_utf16_content` | same | the `\r` rule the wire converter has always had |
| `an_indexed_position_is_the_position_the_wire_converter_would_have_given` | `lucisv_server/src/design_hierarchy.rs` | **the round's central safety property**, across the crate boundary, over five awkward shapes |
| `a_snapshot_reads_no_files_at_all` | same | the round's central claim: delete every source file, get a byte-identical snapshot |
| `every_file_is_named_once_and_a_range_is_four_numbers` | same | the file table and the compact range, by counting URI occurrences in the serialized answer |
| `positions_are_zero_based_utf16_even_through_multibyte_text` | same | end to end, through the snapshot |
| `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed` | `lucisv_server/src/server.rs` | the flag is false with a rescan owed, *and* the request is held rather than answered |
| `rootsAreAlphabeticalAndEverythingStartsCollapsed` | `hierarchyModel_test.js` | owner item 2 |
| `openingOneLevelAtATimeWalksTheDesign` | same | lazy levels build the right rows in the right order |
| `rowIdsSurviveARefresh` | same | expansion state across a rescan, by reversing module order |
| `bookmarksResolveByPathWithoutATableOfEveryPath` | same | the bookmark walks down instead of consulting a table of every path |
| `searchScansTheFlatIndexAndKeepsAncestorContext` | same | one row per instance, names only, and what a result navigates to |
| `theNarrowWireIsRebuiltIntoTheWideModel` | same | schema 2 → the model codex's client code reads |
| `searchOverAHugeHierarchyStaysInsideItsBudget` | same | owner item 3's budget, on a generated 120 000-entry fixture |
| the view suite's collapsed/lazy/search/no-preview assertions | `hierarchyView_test.js` | owner items 1–3 through the real provider |
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` silent. `cargo test --workspace` green, 0 failed —
`lucisv_server` unit tests 1 297 passed / 33 ignored, its `e2e` suite 63 passed
/ 2 ignored, `vlog_semantic`'s `workspace` suite 77 passed. All four node
scripts OK: `hierarchyModel_test.js`, `hierarchyView_test.js`,
`restart_test.js` (44 checks), `smoke.js`.
## QA log
### 2026-08-29 — QA (adversarial pass on the dev round)
**Scope note first.** `git diff master` over-reports this round's footprint:
`master` has advanced two commits past this branch's own base (`40094c4`,
`37560ca` and a `--stdio` hotfix), so a plain diff against `master` makes it
look like `server.rs`/`state.rs` dropped
`a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds` and its
doc comment. They did not — that test was added by `37560ca`, a commit this
branch never had. `git diff HEAD` (this branch's own tip) is the correct
diff and shows only this round's real changes; verified with
`git merge-base HEAD master` = `40094c4`.
**Verdict: SHIP.** No corruption, no idempotency break, no widened
`verify.rs` forgiveness, nothing dropped silently. One real finding, low
severity, everything else confirmed by hand or by new regression tests.
**1. Position agreement (adversarial extension) — confirmed, no divergence.**
Extended `an_indexed_position_is_the_position_the_wire_converter_would_have_given`
(`crates/lucisv_server/src/design_hierarchy.rs:344`) with two more hostile
shapes: CRLF and bare LF mixed in one file, and an instance on the same
source line as its module header. Both agree with `convert::Positions`
exactly, as every other shape already did. Raised the fixture's own
`checked >= 11` premise to `>= 16` to keep counting honest against the two
new sources. `cargo test -p lucisv_server design_hierarchy::` — 8/8 pass.
**2. Schema-2 fidelity on a hostile workspace — confirmed, no bug; coverage
was missing and is now filled.** The client-side rebuild
(`theNarrowWireIsRebuiltIntoTheWideModel`,
`editors/vscode/hierarchyModel_test.js:204`) is a real check against a
hand-built wire fixture, not a self-reference — it does not call the server
or reuse `buildHierarchy`'s own output as its oracle. But nothing on the
*server* side had ever produced a wire snapshot from duplicate module
names, an escaped identifier, or a module with many instances of another —
exactly the hostile shapes the charter named. Added three tests to
`design_hierarchy.rs`:
- `duplicate_module_names_across_files_stay_two_distinct_rows` — two files
each declaring `module dup`; the wire keeps two separate rows keyed by
`(file, definition range)`, each with only its own file's instances.
- `an_escaped_identifier_names_a_module_and_an_instance` — `\weird$leaf ` and
`\u$inst ` (space-terminated, space not part of the name) round-trip
through the wire unmangled.
- `one_hundred_instances_of_one_module_are_one_hundred_sorted_rows` — caught
a bug in my *own* first draft, not the feature's: the fixture generator
wrote `leaf u_000 (), leaf u_001 (), …` (repeating the module keyword per
instance, invalid Verilog), which the parser silently produced zero
instances for. Fixed to `leaf u_000 (), u_001 (), …, u_099 ();` (one
module, 100 comma-separated instances); all 100 came back as sorted,
individual rows. Filed here as a QA-harness bug, not a feature bug — the
server encoder was never wrong.
**3. Format-5 discipline — confirmed by hand.** Walked the `as_a_format_4_record`
field-stripper (`crates/lucisv_server/src/index_cache.rs:600`) against the
actual encoder field order in `facts.rs` by counting fields myself: a unit's
group is `name, kind, name_span×2, decl_span×2, detail_span×2, lines×2` (10
fields) then `positions` (2 `Utf16Range`s × 4 = 8 fields) = 18, and an
instantiation's occurrence is `name, name_span×2, span×2, name_positions×4,
positions×4` = 13 fields behind its own count field. The two `drain` calls
remove exactly those, in descending index order so neither shifts the
other's target before it runs — `as_a_format_4_record` really does yield
what format 4 wrote, not a fabricated shape that merely fails to decode for
some other reason. `cargo test` confirms `a_format_4_record_without_instance_occurrences_is_rejected`
and the belt-and-braces assertion both still pass.
**4. Search honesty — confirmed by hand, previously untested at this
precision; two regression tests added to `hierarchyModel_test.js`.**
- `topKSearchMatchesWhatAFullSortWouldChoose` — five instances of one
module scored against `fifo` by the documented rule (exact/prefix/
substring/subsequence tiers, arithmetic shown in the test's own comment);
asserts the counting cutoff's capped-at-3 answer is `["fifo", "fifo_ctrl",
"ffifo"]` in that order with `truncated: 2`, and that an uncapped call
returns all five in the same relative order. This is the "same top
results a full sort would give" check the charter asked for; nothing like
it existed before (the 120k-entry budget test only measures speed and a
cap that is tautologically consistent with its own `truncated` field).
- `theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch` — an independent,
un-bitmasked `isSubsequence` checker (does not call `maskOf`) confirms six
adversarial (haystack, needle) pairs really are subsequence matches,
including escaped-identifier-shaped names with `$`, `.` and `[]` (all of
which fold onto the same "other" bit in `maskOf`'s coarse classification),
then asserts `fuzzyScore` and `searchHierarchy` both find them too. By
construction (every character sets some bit, and the "other" bucket can
only make the prefilter more permissive, never less) this class of bug is
not reachable, but it was previously asserted nowhere.
- The existing 120k-entry fixture's `N more matches` check
(`found.truncated === found.total - SEARCH_LIMIT`) is real but narrower
than it looks: `truncated` is *defined* as `total - rows.length`, so the
assertion is actually pinning `rows.length === SEARCH_LIMIT` exactly when
over the cap, not independently verifying `total`'s own correctness. Not a
bug — `total` comes from the same counting pass the charter already asked
me to hand-verify above — but worth recording so a future reader does not
mistake it for a hand-checked "right N".
**5. Complete/held semantics — confirmed as documented, not independently
re-driven through the widen machinery.**
`a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`
(`server.rs:5523`) sets `rescan_wanted = true` directly rather than
triggering a real scope widen, but `rescan_wanted` is exactly, and only, the
flag every real widen path sets (`server.rs:1833,1870,1927`, all three
verified by inspection) before `must_wait` holds the request — so the test
exercises the true mechanism, not a stand-in for it. Did not add a
heavier end-to-end "trigger a real widen, then race a snapshot against it"
test; diminishing returns against the direct flag test already there.
**6. Perf reproduction — independently reproduced on
`/Users/guoliangchen/repo/opentitan`, matches the claimed numbers closely.**
Built `--release`, drove a hand-rolled LSP client over stdio (workspace
scope pulled via `workspace/configuration`, `--verbose` for server-side
handler timing), no test dependency. Settled:
- 1 544 modules (README claims 1 544 — exact match).
- Snapshot 2 335 713 B (README: 2 335 749 B on its own run — 36 B apart,
consistent with ordinary opentitan corpus drift between runs).
- Server-reported handler time settled at 16.3–17.98 ms across two runs
(README: 17–20 ms — inside range, in fact slightly faster).
- Client round trip over stdio settled at 29.9–36.7 ms (README's "end to
end… settled" is 39–44 ms; this machine is somewhat faster end to end,
same order of magnitude, same conclusion: no file is read per snapshot).
- First request after the real workspace-scope index landed (the
cold/rescan-blocked one) took 1.2–3.1 s across two runs — consistent with
"a request pipelined behind a rescan waits for the rescan," not a
regression, since the round only claims the *settled* number.
Did not separately reproduce the `didSave`-plus-re-pull ~141 ms figure
(would need a second harness pass simulating an editor save); the settled
snapshot and rescan-blocked numbers above exercise the same code paths that
number is built from.
**7. Full gates — all green, including new tests.**
- `cargo fmt --all -- --check` clean (after `cargo fmt` on my own new test
code).
- `cargo clippy --all-targets --workspace` silent.
- `cargo test --workspace`: 0 failed. `lucisv_server` unit tests
1 300 passed / 33 ignored (1 297 + 3 new design_hierarchy tests), `e2e`
63 passed / 2 ignored, `vlog_semantic` `workspace` suite 77 passed —
matching the work log's counts plus my additions.
- `hierarchyModel_test.js`, `hierarchyView_test.js`, `restart_test.js`
(44 checks), `smoke.js` (against a `--release` build) — all OK.
**Tests added this pass.**
| test | where | pins |
|---|---|---|
| two new sources in `an_indexed_position_is_the_position_the_wire_converter_would_have_given` | `design_hierarchy.rs` | CRLF+LF mixed in one file; instance on the module header's own line |
| `duplicate_module_names_across_files_stay_two_distinct_rows` | same | two `module dup` declarations stay two wire rows, never merged |
| `an_escaped_identifier_names_a_module_and_an_instance` | same | `\weird$leaf `/`\u$inst ` round-trip the wire unmangled |
| `one_hundred_instances_of_one_module_are_one_hundred_sorted_rows` | same | 100 instances of one statement are 100 sorted rows |
| `topKSearchMatchesWhatAFullSortWouldChoose` | `hierarchyModel_test.js` | the counting cutoff picks the same top-K a full sort would, checked by hand |
| `theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch` | same | an independent, un-bitmasked subsequence check against escaped-identifier-shaped names |
**Findings.**
| severity | finding |
|---|---|
| low (harness/process, not code) | `git diff master` on this worktree conflates two unrelated upstream commits with this round's own changes; use `git diff HEAD` (`merge-base HEAD master` = `40094c4`, this branch's own base) — flagged so the lead doesn't review a phantom deletion of `a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`. |
| informational | The 120k-entry `N more matches` assertion is tautologically tied to its own `total`/`rows.length` definitions rather than an independent oracle; not wrong, now supplemented by a hand-checked small fixture (finding 4 above). |
| informational | `complete`/`must_wait` is pinned via a direct flag set rather than a live-triggered widen; the flag is the real mechanism's own signal, so this is a documentation note, not a gap requiring more test weight. |
No masked-corruption risk, no `verify.rs` change, no `unsafe`, no new
dependency, no `FACTS_FORMAT` 6, no commits made.
## Review
**2026-08-29 — lead.** Reviewed across the whole arc: codex's
implementation (externally contributed; UI architecture and the
flat-snapshot/client-tree split were right from the start), the lead's
own QA pass that measured the 5 s / 300 ms-per-save snapshot cost, the
fix round (index-carried positions folded into the format 5 codex was
already minting — one bump, not two; schema 2 forced by arithmetic,
with codex's client model rebuilt byte-for-byte behind validateSnapshot),
the owner's three UI rulings (preview removed, collapsed by default,
resident-model search with the freeze diagnosed three ways), and QA's
SHIP with independent oracles added where the round's own tests were
self-consistent. Gates re-run by the lead on the worktree. The wire
break from codex's schema 1 is accepted: no shipped client ever spoke
it, and the model layer preserves the contract where code actually
reads it. Search-as-ranked-list instead of filtered tree is accepted
as the necessary consequence of the flat model the owner asked for,
with the tree-only actions honestly labeled. The --stdio hotfix is
mirrored here and merges clean with master's. Accepted; merged by the
lead. Credit: codex (implementation), Opus dev (integration fixes),
Sonnet QA, the owner's live UI feedback.
_(reserved for the lead.)_
+13 -2
View File
@@ -41,13 +41,24 @@ impl WorkspaceIndex {
fn fingerprint(&self) -> String; // 2026-08-27
fn find_define(&self, name: &str) -> Vec<(FileId, &Define)>;
fn workspace_symbols(&self, query: &str) -> Vec<WorkspaceSymbol<'_>>;
fn units_of(&self, SymbolKind) -> impl Iterator<Item = (&str, &Def)>; // 2026-08-29
fn counts(&self) -> IndexCounts;
}
struct Def { file: FileId, name_span: TextRange, kind: SymbolKind,
struct Def { file: FileId, name_span: TextRange, decl_span: TextRange, // 2026-08-29, hierarchy sidebar
kind: SymbolKind,
detail_span: Option<TextRange>, // 2026-08-28, port-detail-spans
lines: DeclLines } // 2026-08-28, hover-line-index
struct DeclLines { name: u32, detail: Option<u32> } // 1-based source lines
struct DeclLines { name: u32, detail: Option<u32>, // 1-based source lines
positions: Option<DeclPositions> } // 2026-08-29, hierarchy sidebar
// Where a *file-scope* declaration sits as a client counts positions, so an
// editor can be pointed at a module in a closed file with no read at all.
// `None` for a member: members outnumber units by two orders of magnitude and
// nothing wants theirs, and the record's `U` and `M` groups are separate, so a
// member spends no field on the absence.
struct DeclPositions { name: Utf16Range, decl: Utf16Range }
struct Utf16Range { start: Utf16Pos, end: Utf16Pos }
struct Utf16Pos { line: u32, character: u32 } // 0-based line, UTF-16 units
struct WorkspaceSymbol<'a> { name: &'a str, container: Option<&'a str>, def: &'a Def }
struct IndexCounts { files, modules, packages, typedefs, members, defines }
+454 -4
View File
@@ -348,6 +348,367 @@ file (resolve the scope, read all 200 files, open the store) against 4.0 ms for
one file — so reading the files lazily is what a single-digit number would take,
and it is filed as a deliberate not-done in that feature's README.
## Before / after — round 5 (2026-08-28)
`docs/features/index-scope/README.md`: the owner's opentitan report. Every F12
into a folder the scope had not reached ran a whole rescan of every folder
reached so far, and `must_wait` holds the next request behind it — so the wait
grew with the session. A widen now indexes the folders it added and folds them
in. Measured over the real checkout (3 979 SV files, warm store, folder scope,
`--release` over stdio, the `HEAD` binary and this one alternated in one
session), timing the `textDocument/definition` sent straight after each
`didOpen`:
| the next request after a jump | before | after |
|---|---:|---:|
| `didOpen hw/ip/aes/rtl` | 120 ms | **22 ms** |
| `didOpen hw/ip/kmac/rtl` | 132 ms | **18 ms** |
| `didOpen hw/ip/hmac/rtl` | 137 ms | **12 ms** |
| `didOpen hw/ip/spi_device/rtl` | 169 ms | **44 ms** |
| the session's first definition (waits for the first widen) | 99.7 ms | **0.9 ms** |
| a definition once the scope has settled | 0.06–0.11 ms | 0.05–0.06 ms |
**The shape is the claim, not the ratio.** What is left is proportional to the
folder being opened — `spi_device/rtl` is the big one and costs the most, every
time — and no longer to how long the user has been browsing. Two thirds of the
first row is not parsing at all: `begin_scan` re-opens the persistent store on
every whole rescan, and decoding 3 979 records is ~90 ms of it, which a widen
does not pay because it keeps the handle the last whole rescan left.
Reproducible without that checkout:
`perf::what_a_jump_into_a_new_folder_costs_before_and_after` generates 40
folders × 25 files of 200 lines and runs **both shapes over the same tree in
the same run**, asserting after every jump that the two indexes fingerprint
identically:
| jump | files in scope after it | whole rescan | incremental widen |
|---|---:|---:|---:|
| 0 | 25 | 18.2 ms | 17.8 ms |
| 1 | 50 | 37.1 ms | 18.1 ms |
| 3 | 100 | 71.7 ms | 18.7 ms |
| 5 | 150 | 107.1 ms | 19.2 ms |
The first row being equal is the honest baseline: with nothing indexed yet the
two paths do the same work.
**What it cost the whole scan: nothing measurable.** The include graph now
re-spells every held edge on each `relearn`, which is the one thing this round
added to a path a whole scan runs.
`state::tests::qa_perf_cold_warm_and_half_warm_scans`, 860-file corpus, after:
**361 / 381 / 202 ms** (no cache / cold / warm) against the 322 / 353 / 189 ms
recorded above and the 347 / 387 / 203 ms QA measured on a busier machine — the
same band, and the store is byte-identical at **2 380 790 bytes**, which is the
number machine load cannot move.
## Before / after — round 6 (2026-08-28)
`docs/features/refactor-ports/README.md`: the rest of the owner's "goto
definition is slow" report. The definition itself answered in microseconds —
it was queued behind `textDocument/codeAction`, which VS Code sends on nearly
every cursor move and which read the whole in-scope file set from disk and ran
the refactor engine over it whenever the cursor sat on an instantiation or a
port. The owner's instrumented session: **3 111 ms** and **3 014 ms** per code
action, against 0.01–0.44 ms for every other request. The file set is now the
cursor's module's own fan-out through the index — definers, instantiation
edges, reference postings, open buffers — instead of the workspace.
Measured over the real checkout (3 976 files indexed, `--release`):
| cursor | before | after |
|---|---:|---:|
| a port of `adc_ctrl_core` (action offered, 2 files edited) | 4.56 s | **7.1 ms** |
| a `prim_fifo_sync` instantiation (36-file fan-out) | 2.93 s | **83 ms** |
Both were checked to give the *same* answer as the whole-workspace
computation, which is the point: this is a smaller input to the same engine,
not a cheaper approximation. The second row is the ceiling — a module
instantiated all over OpenTitan really does need its 36 files, and the engine
parses them twice (plan, then verify); 1.3 ms of that 83 ms is reading them.
Reproducible without that checkout:
`perf::a_code_action_at_an_instantiation_before_and_after` generates 500 files
of 200 lines plus a module instantiated in three of them, and runs both shapes
over the same workspace in the same run:
| | |
|---|---:|
| whole workspace (what the handler did until this round) | 725 ms |
| the module's fan-out | **0.41 ms** |
| `sources()` alone — the read, without the engine | 14.5 ms |
| `prepare_rename`, deliberately untouched this round | 249 ms |
The last row is the follow-up this round did not take: a rename must see every
file that could name the symbol, so its subset is a different argument. It is
sent when the user presses the rename key, not per cursor move.
## Before / after — round 7, Lane B (2026-08-28)
`performance.md` §6d: `textDocument/completion` cost **34–66 ms and fired on
every keystroke**, worst at 0–4 typed characters — the beginning of every
identifier. Typing `aes_reg_top` one character at a time cost **201 ms** of
blocked single-threaded loop. The report guessed the cost was "scanning the
3 976-file symbol table"; the probe says otherwise.
**Where it actually was.** `perf::completing_one_keystroke_at_a_time` runs the
same request at the same prefixes with the cursor at module-item position
(every tier runs) and inside an expression (tier 0 is gated off). Over a
generated corpus of 4 000 files:
| prefix | at an item, before | in an expression (no tier 0) |
|---|---:|---:|
| `` (empty) | 53.2 ms | 0.19 ms |
| `aes_` | 49.7 ms | 0.19 ms |
Everything that is not tier 0 — the index tier, the word tier, the scope
gates, building and serialising 512 items — is **0.19 ms**. The whole cost was
**tier 0, the module skeletons**: up to 64 per keystroke, each one a read of
the declaring file and a `parse_source_tolerant` over **all** of it, to read a
header a few hundred bytes long. One skeleton off a 1 214-line file: 2.71 ms
of parse for 16 µs of planning.
Two changes, both of which must leave the items byte-identical (pinned by
`completion::tests::the_header_slice_plans_exactly_what_the_whole_file_plans`
and `candidates::tests::the_module_table_answers_exactly_what_module_names_answers`):
1. **Parse the header, not the file.** `completion::module_header` slices the
declaring file at the `;` that ends the module header — anchored on the
index's own `name_span`, found by lexing a bounded window, and refused
outright for any header shape it does not recognise. The prefix is kept
byte for byte so every span the plan reads still points where it did.
2. **Table the module names.** Tier 0 asked `vlog_refactor::module_names`,
which calls `WorkspaceIndex::workspace_symbols("")` — building and sorting
a record per declaration in the workspace, **per keystroke**.
`Candidates::modules` is that list, built once beside the index.
| generated corpus, 4 000 files of 1 200 lines | before | after |
|---|---:|---:|
| completion at the empty prefix | 53.2 ms | **3.17 ms** |
| at `a` | 52.4 ms | **3.14 ms** |
| at `aes_` | 49.7 ms | **3.26 ms** |
| at `aes_0001` (1 item) | 0.31 ms | **0.017 ms** |
| one skeleton: `instantiation_plan` over the whole file | 2.71 ms | — |
| one skeleton: over its header alone | — | **16.5 µs** (slicing it: 7.1 µs) |
Over the real checkout, driven through the shipped binary with
`performance.md`'s own client (3 976 files, workspace scope, warm):
| request | before (`performance.md` §6d) | after |
|---|---:|---:|
| completion, empty prefix | 63–66 ms | **13.1–15.0 ms** |
| completion, `a` | 58–61 ms | **13.2–13.5 ms** |
| completion, `aes_` | 35 ms | **15.0–15.7 ms** |
| completion, `prim_` | 16–19 ms | **5.8–6.9 ms** |
| completion, `clk` | 5.7–6.0 ms | **2.4–2.8 ms** |
| completion, `aes_reg` | 5.0 ms | **0.32–0.69 ms** |
| completion, `zzzz` | 1.4–2.0 ms | **0.06–0.31 ms** |
| typing `aes_reg_top`, 11 keystrokes | **200.9 ms** | **64.5 ms** |
**The generated corpus is 3.2 ms and the real one is 13 ms, and the difference
is real rather than noise.** `perf::completing_over_a_real_project` — the same
measurement pointed at whatever `LUCISV_PERF_CORPUS` names, skipped when it is
unset — breaks tier 0's remaining bill down over opentitan's own modules:
| prefix | modules planned | read each | slice each | plan each |
|---|---:|---:|---:|---:|
| `` (empty) | 64 | 16.8 µs | 62.2 µs | 68.2 µs |
| `aes_` | 59 | 15.0 µs | 63.8 µs | 101.6 µs |
| `prim_` | 64 | 12.3 µs | 23.5 µs | 19.2 µs |
| `clk` | 34 | 2.1 µs | 0.7 µs | 1.1 µs |
opentitan's headers are simply bigger: `aes_control_fsm_n`'s is 6.6 KB of
commented ports. That measurement is also what set `HEADER_WINDOWS`: at the
first ladder tried (top rung 4 KB) four of the 64 `aes*` modules overflowed it
and paid a whole-file parse of a 24–52 KB file — 10 ms of the 12. Raising the
top rung to 16 KB removed every fallback and cost the common case nothing,
because the common header still ends inside the first 256-byte rung (59% of
opentitan's 344 RTL modules do).
**What is left, and why it was not taken.** ~10 ms of a worst-case opentitan
completion is 64 real header parses, and the items are required to be
identical, so the only ways down are a cache or a protocol change:
- memoize the plan per (module, index generation) — correct only if the cache
is dropped on every unsaved edit to a declaring buffer, which
`Candidates` currently is not (it is rebuilt at `didSave`), so it would need
a new invalidation rule rather than an existing one;
- `completionItem/resolve`: send tier 0's items with labels only and compute
the skeleton on the lightbulb — ~0 ms per keystroke, but it changes what the
first response contains and needs `resolveProvider` in the capabilities.
Both are the same shape as the deferred `codeAction/resolve` item in
`TODO.md` §10 and belong with it.
**`documentHighlight`, `performance.md` §7 — a functional bug, not a perf
one.** It answered 0 results at every position tried while `references`
answered 7 and 10 at the same positions. Root cause and fix are in
`docs/features/references-nav/README.md`; the number here is only that it is
still fast now that it answers: **0.05–0.15 ms** against the 0.03–0.12 ms it
took to answer nothing.
**The scope-depth default, `performance.md` §4.** The shipped
`lucisv.index.scopeDepth` moves 0 → 2.
`perf::what_the_scope_depth_default_costs` measures every rung over an
opentitan-shaped tree (12 blocks of 20 `rtl/` files plus a `dv/tb/` file, the
buffer opened three levels down):
| depth | files indexed | index names | scan |
|---:|---:|---:|---:|
| 0 | **1** | 5 | 0.6 ms |
| 1 | 1 | 5 | 0.3 ms |
| 2 | **21** | 25 | 15.0 ms |
| 3 | 252 | 256 | 185.0 ms |
Depth 0 reproduces the trap exactly: one file indexed, so every cross-file
answer is empty. Depth 2 is the block the file belongs to — 21 files for 15 ms
of scan, once — and depth 3 is the whole of `hw/ip`, which is why the default
is 2 and not 3.
## Before / after — round 7, Lane A (2026-08-28)
`docs/features/refactor-rename/README.md` and
`docs/features/file-operations/README.md`: the three remaining `ws.sources()`
callers, and the two worst rows in `performance.md`'s table.
The framing round 6 inherited — "a rename is user-initiated, so it may be
slow" — was half wrong. **`prepareRename` is what the rename key sends before
the box opens**, and it was the second-worst number in the whole report: 2.5–
3.0 s of a wholly frozen single-threaded server on a keypress that had
committed to nothing, taking hover, definition and highlight down with it.
Its entire answer — the identifier's range and its placeholder — is in the
open buffer already.
Three fixes, three shapes:
- **`prepareRename`** is answered from the buffer's own `Semantics`, the
`ExternalResolutions` overlay beside it and the index. No file is read,
nothing is parsed. The refusal-by-refusal parity table is in the rename
README; four refusals that need the *declaring file's* own text are deferred
to `rename`, which is what LSP's optimistic `prepareRename` is for.
- **`rename`** is computed over the symbol's fan-out through the index — every
declarer of the old *and* the new name (units and members), every reference
posting, every instantiation edge, every macro definition, the containing
units and their fan-out, every file that *spells* the new name in a use the
index had to look outside that file to answer, plus every open buffer. The
sufficiency argument, the escape hatch for an ambiguously-referenced
declaration, and the named residue are in the rename README.
- **`willRenameFiles`** reads the include graph's includers instead of the
workspace: a file with no edge writes no `` `include`` this workspace can
resolve, so its turn in the sweep could only ever `continue`.
Measured over the real OpenTitan checkout (3 976 files indexed, `--release`,
same machine and corpus as `performance.md`):
| request | before | after |
|---|---:|---:|
| `textDocument/prepareRename` on the `aes` instantiation | 1.663 s | **139 ns** |
| `textDocument/rename` of `aes` (7 files edited) | 3.467 s | **105.5 ms** (7-file fan-out) |
| `workspace/willRenameFiles` for one header | 249 ms of `sources()` alone | **14.1 ms**, whole answer (331 includers of 3 976) |
The remaining 105.5 ms is the engine over 7 real files — index build, then an
analysis of each before and after the edit — not the workspace read:
`sources()` alone was 200–241 ms across runs, which is the row with the most
run-to-run spread on a machine that is not quiet. Building the fan-out itself
is **4.75 ms**, of which the one rung that scans the whole index rather than
looking a key up — `WorkspaceIndex::files_spelling`, the dangling-use rung
added in the QA-driven rework — is **852 µs at its worst** (a name nothing
spells, where the walk cannot short-circuit) and 402 µs for `clk_i`, which 681
files spell.
Every row was also checked for **equality** against the whole-workspace
computation, which is the point: this is a smaller input to the same engine,
not a cheaper approximation. Four real cursors in `tb.sv`:
| cursor | fan-out | result |
|---|---:|---|
| `aes` → `aes_core_top` | 7 of 3 976 | edits identical (7 files, 7 edits); **7 macro-invocation warnings lost** — the one accepted residue, see the rename README |
| `aes` → `prim_fifo_sync` | 7 | both refused, verbatim: *"renaming `aes` to `prim_fifo_sync` would change what `prim_fifo_sync` means in tb.sv"* |
| `clk_rst_if` → `clk_rst_thing` | 116 | edits identical (114 files, 275 edits); 64 → 61 warnings |
| `.clk_i` → `clock_in` | **3 976** | edits identical (4 files, 5 edits), all 652 warnings identical — the ambiguity escape hatch fired, so this cursor is correct but not faster |
and `prepare_rename_here` was swept against `prepare_rename` at every 7th byte
of the same file: **564 offsets, all identical, zero deferrals.**
Reproducible without that checkout, over 500 generated files of 200 lines plus
a module instantiated in three of them
(`perf::a_rename_before_and_after`, `perf::a_will_rename_before_and_after`):
| | before | after |
|---|---:|---:|
| `prepareRename` on the module name | 251 ms | **212 ns** |
| `rename` to a new name (4 files edited, 4-file fan-out) | 486 ms | **370 µs** |
| — building that file set | — | 128.7 µs, of which `files_spelling` 49.8 µs |
| `willRenameFiles`, reading the scope vs the includers | 16.1 ms | **18.9 µs** (whole answer 35.4 µs) |
Every OpenTitan and synthetic figure above was re-taken after the QA-driven
rework, so the tables describe the shipped code. The pre-rework round measured
1.604 s → 135 ns, 3.284 s → 103.6 ms, 238 ms → 200 ns and 465 ms → 294 µs on
the same corpora: the sixth rung is inside the run-to-run noise, which the
separate rung measurement says directly rather than by subtraction.
## Before / after — round 8 (2026-08-29)
`performance_take2.md` §5b: the first F12 from a testbench into its own RTL at
the shipped `scopeDepth: 2` raises the scope from one IP block to the whole of
`hw/ip`, and take 2 measured 1.4–1.7 s of frozen loop for it.
**The diagnosis in the brief did not survive the measurement, and that is the
first result.** The widen was *not* falling back to a whole rescan and was *not*
re-indexing the block it already held: with `hw/ip/aes` already in scope, the
jump's bar reads **1 685 files, not 1 807**, and every one of them is a file the
index did not hold. `widen_of` sees an add (the contained directory stays in the
list beside the containing one) and `begin_widen` diffs **by file against the
index**. Both are pinned by tests this round rather than left to be re-derived.
**What the second was actually paying for**, `hw/ip` at the default scope, warm
store, stage by stage:
| stage of the 1 807-file widen | before | after |
|---|---:|---:|
| walk the added folder and read the new files | 100 ms | 100 ms |
| the scan loop (hash, decode the records, **lex for words**) | 405 ms (325 of it the lex) | 405 ms |
| `index.absorb` | 31 ms | 31 ms |
| **`candidates.absorb`** | **403 ms** | **43 ms** |
| `includes.absorb` | 20 ms | 20 ms |
The word table is a sorted `Vec`, and the widen inserted each new word into it
on its own — one memmove of the table's tail per word, quadratic in the batch.
Counted per batch and merged in one pass, it is 9× cheaper and the answer is
the same table `Candidates::build` sorts from the same counts.
End to end, `/Users/guoliangchen/repo/opentitan`, `--release` over stdio, the
`HEAD` binary and this one alternated in one session, timing the request sent
straight after each `didOpen`:
| `didOpen` at `scopeDepth: 2` | before | after |
|---|---:|---:|
| `hw/ip/aes/dv/tb/tb.sv` (widens to `hw/ip/aes`, 124 files) | 51 / 60 ms | 52 / 55 ms |
| `hw/ip/aes/rtl/aes.sv` (raises to `hw/ip`, **1 685 new**) | 935 / 881 ms | **555 / 564 ms** |
| the same jump on a **cold** store (1 683 parses) | 1 529 ms | **1 175 ms** |
| `kmac`, `hmac`, `spi_device` after it (already in scope) | 3–6 ms | 3–6 ms |
The cold row is take 2's own 1.4–1.7 s reproduced. **What is left is real
work**: 1 683 files this index has never seen, of which 325 ms is re-lexing
them for the completion word table — the persistent store holds a file's facts
but not its words, and putting them there is a `FACTS_FORMAT` change, filed in
`TODO.md` §10. The widen still does not interleave, so this is one bar the user
watches, once per session per big widen.
Reproducible without that checkout:
`perf::what_a_widen_that_subsumes_the_old_scope_costs` generates 20 blocks ×
(25 rtl + 10 dv) files whose every name is its own file's, opens a testbench and
then its RTL sibling at depth 2, and asserts the widened index fingerprints
identically to the whole rescan's:
```text
scope 35 -> 700 files; the widen read 667 of them (the 35 already indexed are not re-read)
whole rescan 664 ms, subsuming widen 653 ms (landing it: 62.9 ms before, 51.8 ms after)
```
The two columns being close is honest and is the point of the shape: when the
subsuming folder is twenty times the old scope, skipping the overlap saves 5 %.
What the round bought is in the landing figure, and it grows with the workspace's
vocabulary — which is why the opentitan table above is the one that matters.
## What it would take to go faster
Ranked by what the measurements above say is there, with what each would
@@ -428,6 +789,12 @@ cost. None of these were attempted; each is a future round.
drain can break up (`perf::what_a_scan_does_before_its_first_file`).
The e2e probe above was flipped to
`a_hover_issued_during_the_initial_scan_is_answered_during_it`.
- [x] **Added in round 7, Lane A (2026-08-28):** the rename family's
before/after, over the same generated corpus round 6 uses
(`perf::a_rename_before_and_after`,
`perf::a_will_rename_before_and_after`), with the OpenTitan column and
the parity/equality sweeps taken by throwaway probes against the local
checkout and deleted.
- [ ] **Round 1's second open TODO, restated and still open:** memory.
Nothing in the repo measures resident size. Round 2 added no data
structure — two free functions and no state — so the figure it would
@@ -435,10 +802,25 @@ cost. None of these were attempted; each is a future round.
symbol. Worth doing before anything interns tokens, which is item 2 of
*What it would take to go faster* and is a memory trade as much as a
time one.
- [ ] Not measured: the per-request handlers themselves (hover aside).
Completion, signature help and semantic tokens each have a
whole-buffer pass somewhere; only their token lookups were measured
this round, not the requests end to end.
- [x] **Round 1's last "not measured", closed for completion (round 7,
2026-08-28):** `perf::completing_one_keystroke_at_a_time` measures the
whole request at nine prefixes, in both positions that gate tier 0, over
a 4 000-file corpus — which is how the cost was found to be tier 0 and
not the symbol table `performance.md` suspected.
`perf::completing_over_a_real_project` does the same over a corpus named
by `LUCISV_PERF_CORPUS`, and skips when it is unset.
- [x] **Added in round 7 (2026-08-28):** what the shipped
`lucisv.index.scopeDepth` costs and buys, rung by rung, on an
opentitan-shaped tree (`perf::what_the_scope_depth_default_costs`).
- [x] **Added in round 8 (2026-08-29):** what a widen that *subsumes* the
folder already in scope costs, at the shipped depth, with the files it
actually reads reported beside the scope's size and the landing of the
scan timed on its own — the stage the round's fix is in
(`perf::what_a_widen_that_subsumes_the_old_scope_costs`).
- [ ] Not measured: signature help and semantic tokens end to end. Each has a
whole-buffer pass somewhere; only their token lookups have ever been
measured. Completion was the third of that list and is now done — and it
was 34–66 ms, which is the reason to finish the other two.
## Work log
@@ -496,6 +878,74 @@ copy in `tests/e2e.rs` — a binary crate's modules are not reachable from an
integration test — and the two must stay the same shape or the in-crate table
and the over-the-wire table stop being readable against one another.
**2026-08-28 — dev (round 7, Lane B).** Added three measurements and one
before/after section, all under *Before / after — round 7*:
- `perf::completing_one_keystroke_at_a_time` — the completion request at nine
prefixes, in both positions that gate tier 0, over a generated 4 000-file
corpus. The two columns are the whole finding: everything that is not the
module-skeleton tier is 0.19 ms, at every prefix, before and after.
- `perf::completing_over_a_real_project` — the same, over `LUCISV_PERF_CORPUS`,
with tier 0's per-module bill split into read / slice / plan. **Skipped when
the variable is unset**, so this crate still depends on no checkout it does
not ship. It is what caught the four `aes_control*` modules whose 6.6 KB
headers overflowed the first window ladder and paid a whole-file parse; the
shipped `HEADER_WINDOWS` top rung of 16 KB comes from that measurement and
from a survey of opentitan's 344 RTL headers, not from a guess.
- `perf::what_the_scope_depth_default_costs` — every rung of the scope ladder
over an opentitan-shaped tree, which is the number behind the
`lucisv.index.scopeDepth` default moving 0 → 2.
`completion_corpus`'s files are 1 200 lines rather than the 300 first tried:
at 300 the generated corpus reproduced `performance.md`'s 34–66 ms almost
exactly, and going bigger showed the *shape* of the cost (a whole-file parse
per skeleton) far more clearly — 2.71 ms of parse for 16 µs of planning.
No figure in any earlier round was re-measured: nothing on those paths
changed. `completion.rs`'s tier 0 and `candidates.rs`'s tables are on no
earlier table.
**2026-08-28 — dev (round 7, Lane A).** Two probes added,
`a_rename_before_and_after` and `a_will_rename_before_and_after`, both over
the same 500-file generated corpus `a_code_action_at_an_instantiation_before_and_after`
uses — factored into `rename_corpus` so the three read against one another.
Each prints a before column computed the way the handler computed it until
this round (`vlog_refactor::rename` over `ws.sources()`) and an after column
that calls the real handler, so the comparison is one workspace, one cursor,
one run.
The OpenTitan column of round 7's table came from throwaway probes against
the owner's local checkout, run and deleted — no test may depend on a
checkout this repository does not carry. Three of them: the timings, a
**parity sweep** over every 7th byte of `tb.sv` comparing
`prepare_rename_here` against `prepare_rename` (564 offsets, all identical,
zero deferrals), and an **equality sweep** over four real cursors comparing
the fan-out rename against the whole-workspace one. The last is what earned
its keep: it showed the edit sets byte-identical everywhere (7 files at `aes`,
114 at `clk_rst_if`, 4 at `.clk_i`) and the capture refusal firing verbatim on
`aes` → `prim_fifo_sync`, **and** it found the one thing the synthetic suite
could not — the macro-invocation warnings the fan-out cannot see. That finding
is written up in `docs/features/refactor-rename/README.md`; it is also why the
`` `define`` rung of the fan-out is a walk over the index's tables rather than
a `find_define` lookup, which recovered two of the five warnings the
`clk_rst_if` cursor was losing.
Note on `a_rename_before_and_after`'s before column: it is ~480 ms rather than
the 249 ms `a_code_action_…` records for `prepare_rename` on the same corpus,
because a rename does the analysis twice — once to collect, once to verify —
where a prepare stops after locating the cursor. Both rows are printed by the
same run so neither has to be trusted from memory.
**2026-08-28 — dev (round 7 rework).** QA found a lost refusal in the fan-out
and the lead ruled it not shippable; the fix added a sixth rung
(`WorkspaceIndex::files_spelling`) whose cost, unlike the other five, grows
with the workspace rather than with the symbol. So `a_rename_before_and_after`
grew two lines — the whole file-set build, and that rung on its own — because
"the rung is free" is a claim, and a claim in this document needs a number
beside it. Every figure in round 7's tables was re-taken against the reworked
code rather than carried over; the pre-rework numbers are quoted underneath so
the rung's cost can be read as a difference as well as directly.
## QA log
**2026-08-28 — QA.** No findings — every number reproduces within reason.
+46
View File
@@ -153,6 +153,52 @@ 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.
## When it feels slow: `--verbose`
The server takes one argument, and it is the only one it takes. Start it with
`--verbose` and every operation says how long it took, as ordinary
`window/logMessage` lines in your client's LSP log:
```lua
vim.lsp.config('lucisv', {
cmd = { 'lucisv-server', '--verbose' }, -- the one argument the server takes
filetypes = { 'verilog', 'systemverilog' },
root_markers = { 'lucisv.toml', '.lucisv.toml', '.git' },
})
```
```
timing: textDocument/hover answered in 0.42 ms
timing: textDocument/didChange handled in 0.03 ms
timing: flush of 1 dirty buffer took 1.87 ms
timing: scan started: 862 files, interleaved
timing: scan finished: 862 files (2 skipped, 858 from cache) in 141.20 ms
timing: workspace/symbol HELD behind a rescan (answering=true, wanted=false, already held=0)
```
That last line is the one worth knowing: the request was not slow, it had not
*started* — the loop was rebuilding the index and the order contract makes a
request queued behind a rebuild wait for it.
Neovim's built-in handler writes `window/logMessage` to the LSP log file at
*info* level, and the default log level is `WARN` — so raise it once, or the
lines are dropped before they are written:
```lua
vim.lsp.set_log_level('info')
-- then: :lua vim.cmd('edit ' .. vim.lsp.get_log_path())
```
coc.nvim puts them in its own output channel instead
(`:CocCommand workspace.showOutput`); these are the same lines the VS Code
extension shows when you turn on `lucisv.verbose`.
Anything other than `--verbose` is refused: the server prints one usage line on
stderr and exits 2, so a misspelled flag shows up as a server that will not
start rather than as a session that quietly logs nothing. Without the flag not
one `timing:` line is ever sent — this is a diagnostic, not a default, and a
busy session logs a line per keystroke.
## Checking it works
```
+5 -1
View File
@@ -1,4 +1,8 @@
# The smoke test is a pre-publish check, not part of the shipped extension.
# The two checks are pre-publish/developer checks, not part of the shipped
# extension. `restart.js` itself IS shipped — `extension.js` requires it.
smoke.js
restart_test.js
hierarchyModel_test.js
hierarchyView_test.js
.vscode/**
.gitignore
+42
View File
@@ -5,6 +5,48 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## Unreleased
- Added a dedicated **lucisv Hierarchy** Activity Bar view with a persistent
fuzzy search field for module and instance names, alphabetical instance
paths, exact source navigation, full-path copy, definition/instance actions,
yellow workspace bookmarks, and split-right definition opening.
- Every level of the hierarchy starts collapsed; nothing expands on its own,
and what you open stays open across a refresh or a rescan.
- Searching the hierarchy runs entirely in memory over a prebuilt name index:
it never asks the server per keystroke and never rebuilds the tree. Results
are ranked and capped, with a count of the matches not shown.
- The workspace index now retains each individual instance name and source
span while preserving the existing statement-level call-hierarchy and code-
lens counts, and it records the editor positions of every module declaration
and instance — so the hierarchy snapshot reads no files at all. On a
4 000-file workspace the snapshot went from ~300 ms and 11.6 MB to ~40 ms
and 2.3 MB, and a go-to-definition sent behind one no longer waits a
quarter of a second. The index cache rebuilds once because its facts format
changed.
## 0.15.0 — 2026-08-29
The interactive-latency release.
- **Everything on the cursor's path is fast now**, measured on a
3 976-file opentitan checkout: the lightbulb 3.1 s → 7 ms, F2
2.9 s → instant, rename 6.4 s → ~0.1 s, completion 34–66 → 3–15 ms
per keystroke, and occurrence highlighting actually works on
cross-file names.
- **A new design-hierarchy sidebar** (contributed by codex): modules
and their instances in the Activity Bar, instant search over the
whole design, bookmarks, click-to-jump. Collapsed by default; your
expansion survives refreshes.
- **Out-of-box answers:** `lucisv.index.scopeDepth` now defaults to 2,
so opening a file indexes its whole block — cross-file hover,
definition and references work immediately. Set it to 0 for the old
single-folder behavior.
- **`lucisv.verbose`**: flip it on and every operation logs its cost
in the lucisv output channel; flipping it restarts the server safely.
- One-time index rebuild on first open after updating (store format
gained the sidebar's position data).
## 0.14.0 — 2026-08-28
The first-hover release.
+19 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.14.0**. Its platform packages include both
The current release is **0.15.0**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -60,6 +60,9 @@ way the extension finds them and makes them executable on first activation.
Most features work as soon as a supported file opens:
- Open the **lucisv** Activity Bar icon for an instance-oriented design tree.
Every level starts collapsed; its fixed search field fuzzy-matches module and
instance names in memory, and click or the instance context menu navigates.
- Hover a symbol, press `F12`, find references, search workspace symbols, or
open the call/type hierarchy using VS Code's standard commands.
- Type a module name at module-item scope to insert a complete instance. Inside
@@ -130,6 +133,7 @@ enabling both paths formats twice.
| Inlay hints | Adds port and parameter names to ordered instantiations without guessing at ambiguous sites |
| Code lenses | Shows the workspace-wide instantiation count above every module/interface; click to jump to a site |
| Call hierarchy | Incoming calls answer “who instantiates this?”; outgoing calls answer “what does this instantiate?” |
| Design hierarchy sidebar | Alphabetical instance paths from every top-level module, collapsed until you open them, in-memory fuzzy module/instance search, exact instance/definition jumps, path copy, bookmark highlighting, and split-right opening |
| Type hierarchy | Walks class `extends` relationships to supertypes and workspace subtypes |
### Highlighting and presentation
@@ -276,6 +280,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.largeFile.threshold` | `4 MiB` | Size in bytes above which an opened file gets viewport-only highlighting and nothing else — no parsing, diagnostics, formatting, or indexing; `0` analyzes everything |
| `lucisv.formatOnSave` | `false` | Protocol save hook for editors without native format-on-save; keep off in VS Code. Its indent comes from `lucisv.toml` or `lucisv.indent`, never from the editor tab size, which the protocol does not send on this path |
| `lucisv.serverPath` | bundled | Explicit server override for advanced use; an unchanged setting uses the bundled server |
| `lucisv.verbose` | `false` | Print how long every operation took in the lucisv output channel — one `timing:` line per request, notification, scan, widen, buffer flush, and per request that had to wait behind a rescan. **Restarts the language server when changed**, because it is an argument the server is started with |
The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with
the [large workspaces](#large-workspaces) work; everything else ships in
@@ -320,6 +325,19 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.15.0 highlights
Version 0.15.0 is the interactive-latency release:
- The lightbulb, F2, rename, completion and highlighting are all
measured-fast on a 4 000-file SoC — nothing on the cursor's path
blocks the server for more than a few milliseconds.
- A design-hierarchy sidebar (contributed by codex): instances,
instant design-wide search, bookmarks, click-to-jump.
- Opening a file indexes its whole block by default, so cross-file
answers work immediately; `lucisv.verbose` logs per-operation
timings when you want them.
## Release 0.14.0 highlights
Version 0.14.0 is the first-hover release:
+89 -11
View File
@@ -12,10 +12,21 @@ const fs = require('fs');
const path = require('path');
const vscode = require('vscode');
const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node');
const { createRestarter } = require('./restart');
const { HierarchyView } = require('./hierarchyView');
/** The single client, kept only so `deactivate` can stop it. */
let client;
/**
* The one thing that starts or restarts the server, so that no two transitions
* ever overlap. Created in `activate`; see `restart.js`.
*/
let restarter;
/** The instance-oriented design hierarchy hosted in lucisv's sidebar. */
let hierarchyView;
/** The languages this extension attaches to. */
const LANGUAGES = ['verilog', 'systemverilog'];
@@ -139,11 +150,15 @@ function activate(context) {
// install have always used.
const serverPath = userServerPath() || bundledServer || 'lucisv-server';
// No arguments: `lucisv-server` takes none and speaks LSP on stdin/stdout.
// `editors/vscode/smoke.js` spawns it exactly this way.
// `lucisv-server` needs no arguments and speaks LSP on stdin/stdout —
// `editors/vscode/smoke.js` spawns it exactly that way. The one argument it
// takes is `--verbose`, and only when the user asked for it
// (docs/features/verbose-timing/README.md). The object is kept so the
// restart below can put new arguments in it: every `start()` reads it
// afresh.
const serverOptions = {
command: serverPath,
args: [],
args: serverArgs(),
transport: TransportKind.stdio,
};
@@ -168,6 +183,9 @@ function activate(context) {
// neither reaches it, and to no cache at all if it cannot work one out.
initializationOptions: {
storagePath: (context.storageUri || context.globalStorageUri || {}).fsPath,
// Opt into the custom invalidation notification. Other LSP clients can
// still request a snapshot, but receive no unsolicited lucisv traffic.
hierarchyView: true,
},
};
@@ -182,6 +200,20 @@ function activate(context) {
client.registerFeatures(ProposedFeatures.createAll(client));
context.subscriptions.push(client);
hierarchyView = new HierarchyView(context, client);
// Built before anything can ask it for a restart — the settings listener
// below calls it, and nothing may reach that listener with this unset.
restarter = createRestarter({
client,
serverOptions,
onStarted: () => {
repaintVisible();
hierarchyView.onStarted();
},
onStartFailed: reportStartFailure,
});
// Every colour is one this extension contributes, so every one of them has
// an opaque default in every theme kind: a theme that says nothing about
// `lucisv.rainbowN` gets our default, and a theme or user that overrides it
@@ -214,6 +246,11 @@ function activate(context) {
if (isVerilog(event.document)) scheduleRepaint();
}),
vscode.workspace.onDidChangeConfiguration((event) => {
// A spawn argument can only change by spawning again, so this one
// setting restarts the server. Nothing else here does. What the toggle
// wants is recorded *now*, synchronously; the restarter decides when it
// can act, and reconciles to whatever was asked for last.
if (event.affectsConfiguration('lucisv.verbose')) restarter.want(serverArgs());
if (!event.affectsConfiguration('lucisv.rainbowBeginEnd')) return;
rainbowEnabled = readRainbowSetting();
// Honoured immediately, both ways: turning it off has to take the
@@ -226,19 +263,26 @@ function activate(context) {
// clear on close; the only explicit clearing is turning the setting off,
// which `repaintVisible` does by painting empty ranges.
client.start().then(
() => repaintVisible(),
// The client reports a server that will not start, in its own output
// channel and its own words. Decorations are cosmetic; there is nothing
// useful to add here, and a second error popup would only be noise.
() => {},
);
// The first spawn goes through the restarter rather than around it, and that
// is the whole of the fix for QA finding 1: a `lucisv.verbose` toggle that
// lands while this start is still in flight — a large workspace's first scan
// can hold it for a while — queues behind it instead of racing it, and is
// then reconciled by a real restart. Calling `client.start()` here directly
// would put one transition outside the chain again.
restarter.start();
}
/** Stop the server; VS Code waits on the returned promise. */
function deactivate() {
clearTimeout(repaintTimer);
return client ? client.stop() : undefined;
// Through the restarter, never around it. A `client.stop()` here would be a
// transition outside the chain — and a `lucisv.verbose` toggle landing in the
// same tick would queue a whole reconcile *beside* it, spawning a server with
// nothing left to await or stop it (QA finding 3). `dispose()` shuts the door
// first, so any such toggle is a no-op, and puts the final stop on the same
// chain as everything else. No client means no restarter and nothing spawned:
// every start this extension makes goes through one of them.
return restarter ? restarter.dispose() : undefined;
}
/** True for the documents this extension knows about. */
@@ -250,6 +294,40 @@ function readRainbowSetting() {
return vscode.workspace.getConfiguration('lucisv').get('rainbowBeginEnd') !== false;
}
/**
* The arguments to spawn the server with: `--verbose` when `lucisv.verbose` is
* on, and none otherwise — which is the spawn every version before this used.
*
* `=== true` rather than a truthy test: the setting is a boolean, and anything
* else in it is somebody's mistake, not a request for a noisy log.
*/
function serverArgs() {
return vscode.workspace.getConfiguration('lucisv').get('verbose') === true ? ['--verbose'] : [];
}
/**
* A server that would not start — at activation or at a `lucisv.verbose`
* restart, which is why both go through here rather than through an anonymous
* `catch {}` that drops it.
*
* The language client says plenty about a server that will not spawn, in its
* own output channel and its own words, so there is no popup here: at
* activation there never was one, and a restart is not more alarming. What it
* does *not* say is that a toggle asked for this, so one line goes into the
* same channel the user is already reading. The restart chain survives, so the
* next toggle tries again.
*/
function reportStartFailure(error) {
const reason = (error && error.message) || error;
try {
client.outputChannel.appendLine(`lucisv: the server did not start: ${reason}`);
} catch {
// No channel to write to — no client yet, or one already disposed. The
// client's own report is then all there is, which is exactly what
// activation has always given.
}
}
/** Coalesce a burst of edits into one repaint. */
function scheduleRepaint() {
clearTimeout(repaintTimer);
+574
View File
@@ -0,0 +1,574 @@
// Pure model for the lucisv hierarchy webview. No VS Code dependency: the
// graph, sorting, fuzzy matching and bookmark rules are driven by plain Node
// tests and the extension host only performs I/O/navigation.
//
// **The hierarchy is held flat and expanded lazily.** The first shape of this
// file materialized every path of the whole design the moment a snapshot
// arrived — a module instantiated in ten places duplicated its entire subtree
// ten times — and then walked that tree, scored two names per node and shipped
// the whole thing to the webview on *every keystroke*. That is the freeze the
// owner hit (2026-08-29). What is resident now is exactly the snapshot: modules
// and their instances, plus one prebuilt lowercased search index. A tree row is
// built only when the user opens its parent, and a query is answered by one
// pass over the flat index. See
// docs/features/vscode-hierarchy-sidebar/README.md.
// The wire is deliberately narrow — a file table, four-number ranges, no ids
// and no per-instance definition copies — because the whole design is re-sent
// on every index change and 11.6 MB of it blocked the server's request queue.
// Everything below `validateSnapshot` works on the wide shape
// (`{ uri, range: { start, end }, selectionRange }`, an id per row, a
// `definitions` array per instance), which this file rebuilds once per
// snapshot.
const SCHEMA_VERSION = 2;
/** How many search rows are rendered before the view says "N more…". */
const SEARCH_LIMIT = 200;
/** One `[startLine, startCharacter, endLine, endCharacter]` from the wire. */
function isWireRange(value) {
return Array.isArray(value) && value.length === 4
&& value.every((n) => Number.isInteger(n) && n >= 0);
}
function toRange(wire) {
return {
start: { line: wire[0], character: wire[1] },
end: { line: wire[2], character: wire[3] },
};
}
function isWireLocation(value, files) {
return value && Number.isInteger(value.file) && value.file >= 0 && value.file < files.length
&& isWireRange(value.range) && isWireRange(value.selectionRange);
}
function toLocation(wire, files) {
return {
uri: files[wire.file],
range: toRange(wire.range),
selectionRange: toRange(wire.selectionRange),
};
}
/** The row id the server used to send: unique because two declarations cannot
* begin at one position in one file, and stable across refreshes. */
function idOf(location) {
return `${location.uri}#${location.selectionRange.start.line}:${location.selectionRange.start.character}`;
}
function locationKey(location) {
const start = location.selectionRange.start;
const end = location.selectionRange.end;
return `${location.uri}|${start.line}:${start.character}-${end.line}:${end.character}`;
}
function compareText(a, b) {
const foldedA = a.toLowerCase();
const foldedB = b.toLowerCase();
if (foldedA < foldedB) return -1;
if (foldedA > foldedB) return 1;
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
function compareModules(a, b) {
return compareText(a.moduleName, b.moduleName)
|| compareText(a.definition.uri, b.definition.uri)
|| a.definition.selectionRange.start.line - b.definition.selectionRange.start.line
|| a.definition.selectionRange.start.character - b.definition.selectionRange.start.character;
}
function compareInstances(a, b) {
return compareText(a.instanceName, b.instanceName)
|| compareText(a.moduleName, b.moduleName)
|| compareText(a.site.uri, b.site.uri)
|| a.site.selectionRange.start.line - b.site.selectionRange.start.line
|| a.site.selectionRange.start.character - b.site.selectionRange.start.character;
}
function validateSnapshot(value) {
if (!value || value.schemaVersion !== SCHEMA_VERSION || !Number.isInteger(value.revision)
|| typeof value.complete !== 'boolean' || !Array.isArray(value.modules)
|| !Array.isArray(value.files) || !value.files.every((uri) => typeof uri === 'string')) {
throw new Error('The language server returned an unsupported hierarchy snapshot.');
}
const files = value.files;
const ids = new Set();
const modules = value.modules.map((module) => {
if (!module || typeof module.moduleName !== 'string' || module.moduleName === ''
|| !isWireLocation(module.definition, files) || !Array.isArray(module.instances)) {
throw new Error('The language server returned a malformed hierarchy module.');
}
const definition = toLocation(module.definition, files);
const id = idOf(definition);
if (ids.has(id)) throw new Error('The hierarchy snapshot contains a duplicate module id.');
ids.add(id);
const instances = module.instances.map((instance) => {
if (!instance || typeof instance.instanceName !== 'string' || instance.instanceName === ''
|| typeof instance.moduleName !== 'string' || instance.moduleName === ''
|| !isWireLocation(instance.site, files)) {
throw new Error('The language server returned a malformed hierarchy instance.');
}
const site = toLocation(instance.site, files);
return {
id: idOf(site),
instanceName: instance.instanceName,
moduleName: instance.moduleName,
site,
definitions: [],
};
});
instances.sort(compareInstances);
return { id, moduleName: module.moduleName, definition, instances };
});
modules.sort(compareModules);
// What the server used to repeat on every instance: the declarations its
// module name resolves to. Every one of them is a module in this same
// snapshot, so the lookup is exact rather than an approximation of it — and
// the answer is deterministic because `modules` is already sorted.
const byName = new Map();
for (const module of modules) {
const found = byName.get(module.moduleName) || [];
found.push(module.definition);
byName.set(module.moduleName, found);
}
for (const module of modules) {
for (const instance of module.instances) {
instance.definitions = (byName.get(instance.moduleName) || []).slice();
}
}
return { schemaVersion: SCHEMA_VERSION, revision: value.revision, complete: value.complete, modules };
}
function buildHierarchy(raw) {
const snapshot = validateSnapshot(raw);
const byId = new Map(snapshot.modules.map((module) => [module.id, module]));
const moduleAt = new Map(snapshot.modules.map((module) => [
locationKey(module.definition), module,
]));
// An instance resolves to a module exactly when its type names one
// declaration. Resolved once here, not once per render.
for (const module of snapshot.modules) {
for (const instance of module.instances) {
const target = instance.definitions.length === 1
? moduleAt.get(locationKey(instance.definitions[0]))
: undefined;
instance.targetId = target ? target.id : undefined;
instance.unresolved = instance.definitions.length === 0;
instance.ambiguous = instance.definitions.length > 1;
}
}
const parented = new Set();
for (const module of snapshot.modules) {
for (const instance of module.instances) {
if (instance.targetId) parented.add(instance.targetId);
}
}
// Reachability over the *module* graph, not over the expanded tree: the
// question "is this module already shown somewhere" needs one visit per
// module, and the expanded tree has no bound.
const reached = new Set();
function reach(start) {
const stack = [start];
while (stack.length > 0) {
const module = stack.pop();
if (reached.has(module.id)) continue;
reached.add(module.id);
for (const instance of module.instances) {
const target = instance.targetId && byId.get(instance.targetId);
if (target) stack.push(target);
}
}
}
const roots = [];
for (const module of snapshot.modules) {
if (parented.has(module.id)) continue;
roots.push({ module, fallback: false });
reach(module);
}
// Whatever a root never reaches is inside a recursive component: show it,
// marked, so `A -> B -> A` is visible without an infinite tree.
for (const module of snapshot.modules) {
if (reached.has(module.id)) continue;
roots.push({ module, fallback: true });
reach(module);
}
const entries = searchIndex(snapshot.modules);
return {
revision: snapshot.revision,
complete: snapshot.complete,
modules: snapshot.modules,
byId,
roots,
entries,
// Reused per query rather than allocated per keystroke.
scores: new Int32Array(entries.length),
counts: new Int32Array(MAX_SCORE + 1),
};
}
/// One flat, prelowered row per module and per instance — built once per
/// snapshot, scanned once per query. Nothing here is per-path: an instance
/// appears once however many times the tree would show it.
function searchIndex(modules) {
const entries = [];
for (const module of modules) {
const lowerModule = module.moduleName.toLowerCase();
const [moduleLetters, moduleDigits] = maskOf(lowerModule);
entries.push({
kind: 'module',
module,
instance: undefined,
lowerModule,
lowerInstance: '',
moduleLetters,
moduleDigits,
instanceLetters: 0,
instanceDigits: 0,
});
for (const instance of module.instances) {
const type = instance.moduleName.toLowerCase();
const name = instance.instanceName.toLowerCase();
const [typeLetters, typeDigits] = maskOf(type);
const [nameLetters, nameDigits] = maskOf(name);
entries.push({
kind: 'instance',
module,
instance,
lowerModule: type,
lowerInstance: name,
moduleLetters: typeLetters,
moduleDigits: typeDigits,
instanceLetters: nameLetters,
instanceDigits: nameDigits,
});
}
}
return entries;
}
// A deterministic subsequence score. Higher wins; -1 is no match. The first
// tier keeps the ordering intuitive, the bonuses make `u_f` prefer `u_fifo`
// over a scattered set of the same letters. Both sides are already lowercase,
// and `needle` arrives split into characters: lowercasing and re-splitting per
// call is what made one keystroke allocate once per name in the workspace.
function scoreLower(haystack, needle, chars) {
if (needle === '') return 0;
if (haystack === needle) return 10000;
if (haystack.startsWith(needle)) return 8000 - (haystack.length - needle.length);
const at = haystack.indexOf(needle);
if (at >= 0) return 6000 - at * 10 - (haystack.length - needle.length);
let cursor = 0;
let score = 0;
let previous = -2;
for (let k = 0; k < chars.length; k += 1) {
const found = haystack.indexOf(chars[k], cursor);
if (found < 0) return -1;
score += 10;
if (found === previous + 1) score += 18;
if (found === 0 || !isWordCharacter(haystack.charCodeAt(found - 1))) score += 12;
score -= found;
previous = found;
cursor = found + 1;
}
return score;
}
/// `a`–`z` or `0`–`9`, on an already-lowercased string. A character that is
/// neither opens a word, which is where the word-boundary bonus is paid.
function isWordCharacter(code) {
return (code >= 97 && code <= 122) || (code >= 48 && code <= 57);
}
/// Which characters a name contains, as two bit sets: letters, `_` and
/// "something else" in the first, digits in the second. A subsequence match
/// needs every one of the query's characters to be present, so a name whose
/// bits do not cover the query's cannot match and is never scored — which is
/// what keeps a query that matches almost nothing as cheap as one that matches
/// almost everything.
function maskOf(lower) {
let letters = 0;
let digits = 0;
for (let at = 0; at < lower.length; at += 1) {
const code = lower.charCodeAt(at);
if (code >= 97 && code <= 122) letters |= 1 << (code - 97);
else if (code >= 48 && code <= 57) digits |= 1 << (code - 48);
else if (code === 95) letters |= 1 << 26;
else letters |= 1 << 27;
}
return [letters, digits];
}
function fuzzyScore(text, query) {
const needle = query.trim().toLowerCase();
return scoreLower(text.toLowerCase(), needle, [...needle]);
}
/// The highest score `scoreLower` can return, plus the instance-name tie-break
/// point. Scores are small non-negative integers, which is what lets the top of
/// a very large result set be found by counting rather than by sorting.
const MAX_SCORE = 10001;
/// Every entry the query matches, best first, capped at `limit`.
///
/// **No sort over the whole result set.** A one-letter query matches nearly
/// every name in the workspace, and sorting 100 000 hits to show 200 of them is
/// most of a frame on its own. Scores are bounded integers, so the cutoff is
/// found by counting hits per score and walking down from the top — one extra
/// pass over an array, and only the rows actually shown are ever built. Ties
/// are broken by index order, which is modules alphabetically and then
/// instances alphabetically, so the answer is deterministic without comparing
/// any strings.
function searchHierarchy(model, query, limit = SEARCH_LIMIT) {
const needle = query.trim().toLowerCase();
if (needle === '') return { rows: [], total: 0, truncated: 0 };
const entries = model.entries;
const scores = model.scores;
const counts = model.counts;
counts.fill(0);
const chars = [...needle];
const [wantLetters, wantDigits] = maskOf(needle);
let total = 0;
for (let at = 0; at < entries.length; at += 1) {
const entry = entries[at];
let score = -1;
if ((entry.moduleLetters & wantLetters) === wantLetters
&& (entry.moduleDigits & wantDigits) === wantDigits) {
score = scoreLower(entry.lowerModule, needle, chars);
}
if (entry.kind === 'instance'
&& (entry.instanceLetters & wantLetters) === wantLetters
&& (entry.instanceDigits & wantDigits) === wantDigits) {
const own = scoreLower(entry.lowerInstance, needle, chars);
// An instance-name tie wins by one, as the UI contract specifies.
if (own >= 0 && own + 1 > score) score = own + 1;
}
if (score > MAX_SCORE) score = MAX_SCORE;
scores[at] = score;
if (score >= 0) {
counts[score] += 1;
total += 1;
}
}
// The lowest score that still fits inside `limit`, and how many rows of
// exactly that score may be taken.
let cutoff = 0;
let above = 0;
for (let score = MAX_SCORE; score >= 0; score -= 1) {
if (above + counts[score] >= limit || score === 0) {
cutoff = score;
break;
}
above += counts[score];
}
let roomAtCutoff = Math.max(0, limit - above);
const taken = [];
for (let at = 0; at < entries.length && taken.length < limit; at += 1) {
const score = scores[at];
if (score < cutoff) continue;
if (score === cutoff) {
if (roomAtCutoff === 0) continue;
roomAtCutoff -= 1;
}
taken.push({ at, score });
}
taken.sort((a, b) => b.score - a.score || a.at - b.at);
const rows = taken.map(({ at }) => searchRow(entries[at]));
return { rows, total, truncated: Math.max(0, total - rows.length) };
}
function searchLabel(entry) {
return entry.kind === 'module'
? entry.module.moduleName
: `${entry.instance.instanceName} (${entry.instance.moduleName})`;
}
function searchId(entry) {
return entry.kind === 'module'
? `find:${entry.module.id}`
: `find:${entry.module.id}>${entry.instance.id}`;
}
function searchRow(entry) {
return {
id: searchId(entry),
kind: entry.kind,
label: searchLabel(entry),
// Where the row lives, since a flat hit has no one path to show.
detail: entry.kind === 'module' ? 'module' : `in ${entry.module.moduleName}`,
depth: 0,
hasChildren: false,
expanded: false,
warning: entry.kind === 'instance' && (entry.instance.unresolved || entry.instance.ambiguous),
};
}
/// What a search row points at, for navigation and the context menu.
function searchTarget(model, id) {
if (typeof id !== 'string' || !id.startsWith('find:')) return undefined;
const [moduleId, instanceId] = id.slice('find:'.length).split('>');
const module = model.byId.get(moduleId);
if (!module) return undefined;
if (instanceId === undefined) {
return {
kind: 'module',
moduleName: module.moduleName,
definition: module.definition,
definitions: [module.definition],
site: undefined,
};
}
const instance = module.instances.find((candidate) => candidate.id === instanceId);
if (!instance) return undefined;
const target = instance.targetId && model.byId.get(instance.targetId);
return {
kind: 'instance',
moduleName: instance.moduleName,
instanceName: instance.instanceName,
definition: target && target.definition,
definitions: instance.definitions,
site: instance.site,
};
}
/// The rows the tree shows: every root, then the children of every row the
/// user has opened. Nothing below a closed row is built at all.
function treeRows(model, expanded, bookmarkPath) {
const rows = [];
const nodes = new Map();
const bookmarkId = bookmarkPath ? idForPath(model, bookmarkPath) : undefined;
function push(node) {
nodes.set(node.id, node);
rows.push({
id: node.id,
kind: node.kind,
label: node.label,
detail: node.detail,
depth: node.depth,
hasChildren: node.hasChildren,
expanded: expanded.has(node.id),
warning: node.warning,
bookmarked: node.id === bookmarkId,
});
if (!expanded.has(node.id) || !node.hasChildren) return;
for (const child of childrenOf(model, node)) push(child);
}
for (const { module, fallback } of model.roots) push(rootNode(model, module, fallback));
return { rows, nodes, bookmarkId };
}
function rootNode(model, module, fallback) {
return {
id: `root:${module.id}`,
kind: 'module',
moduleName: module.moduleName,
label: module.moduleName,
detail: fallback ? 'recursive' : '',
depth: 0,
parentId: null,
fullPath: module.moduleName,
hasChildren: module.instances.length > 0,
warning: fallback,
definition: module.definition,
definitions: [module.definition],
site: undefined,
moduleId: module.id,
seen: new Set([module.id]),
};
}
function childrenOf(model, node) {
const module = model.byId.get(node.moduleId);
if (!module) return [];
return module.instances.map((instance) => instanceNode(model, node, instance));
}
function instanceNode(model, parent, instance) {
const target = instance.targetId && model.byId.get(instance.targetId);
const recursive = Boolean(target && parent.seen.has(target.id));
const seen = new Set(parent.seen);
if (target) seen.add(target.id);
return {
id: `${parent.id}>${instance.id}`,
kind: 'instance',
moduleName: instance.moduleName,
instanceName: instance.instanceName,
label: `${instance.instanceName} (${instance.moduleName})`,
detail: instance.unresolved ? 'unresolved'
: (instance.ambiguous ? 'ambiguous' : (recursive ? 'recursive' : '')),
depth: parent.depth + 1,
parentId: parent.id,
fullPath: `${parent.fullPath}.${instance.instanceName}`,
hasChildren: Boolean(target) && !recursive && target.instances.length > 0,
warning: instance.unresolved || instance.ambiguous || recursive,
definition: target && target.definition,
definitions: instance.definitions,
site: instance.site,
moduleId: target && !recursive ? target.id : undefined,
seen,
};
}
/// The chain of row ids leading to a full path such as `TB.dut.inst1`, or
/// `undefined` when the path no longer exists or no longer names one row.
///
/// Walked from the roots rather than looked up in a table of every path,
/// because that table is the thing this file stopped building.
function bookmarkChain(model, path) {
if (typeof path !== 'string' || path === '') return undefined;
const [head, ...rest] = path.split('.');
let found;
for (const { module, fallback } of model.roots) {
if (module.moduleName !== head) continue;
const chain = descend(model, rootNode(model, module, fallback), rest);
if (!chain) continue;
if (found) return undefined; // the path names more than one row
found = chain;
}
return found;
}
function descend(model, node, names) {
const chain = [node.id];
let current = node;
for (const name of names) {
const matches = childrenOf(model, current).filter((child) => child.instanceName === name);
if (matches.length !== 1) return undefined;
[current] = matches;
chain.push(current.id);
}
return chain;
}
function idForPath(model, path) {
const chain = bookmarkChain(model, path);
return chain && chain[chain.length - 1];
}
module.exports = {
SEARCH_LIMIT,
bookmarkChain,
buildHierarchy,
childrenOf,
fuzzyScore,
idForPath,
locationKey,
searchHierarchy,
searchTarget,
treeRows,
validateSnapshot,
};
+409
View File
@@ -0,0 +1,409 @@
const assert = require('assert/strict');
const {
SEARCH_LIMIT,
bookmarkChain,
buildHierarchy,
childrenOf,
fuzzyScore,
idForPath,
searchHierarchy,
searchTarget,
treeRows,
} = require('./hierarchyModel');
// The schema-2 wire the server sends: a file table, four-number ranges, no ids
// and no per-instance `definitions` — the model rebuilds all three.
const FILES = [
'file:///tb.sv',
'file:///top.sv',
'file:///block.sv',
'file:///leaf.sv',
'file:///alpha.sv',
];
function site(file, line, start, end) {
return { file, range: [line, 0, line, end + 3], selectionRange: [line, start, line, end] };
}
function fixture() {
return {
schemaVersion: 2,
revision: 3,
complete: true,
files: FILES,
modules: [
{ moduleName: 'top', definition: site(1, 0, 7, 10), instances: [
{ instanceName: 'inst1', moduleName: 'block', site: site(1, 1, 8, 13) },
] },
{ moduleName: 'leaf', definition: site(3, 0, 7, 11), instances: [] },
{ moduleName: 'TB', definition: site(0, 0, 7, 9), instances: [
{ instanceName: 'dut', moduleName: 'top', site: site(0, 1, 6, 9) },
] },
{ moduleName: 'block', definition: site(2, 0, 7, 12), instances: [
{ instanceName: 'inst2', moduleName: 'leaf', site: site(2, 1, 7, 12) },
] },
{ moduleName: 'alpha_root', definition: site(4, 0, 7, 17), instances: [] },
],
};
}
/** The rows a view would show with `open` expanded, by label. */
function labels(model, open = []) {
return treeRows(model, new Set(open), '').rows.map((row) => row.label);
}
function rootsAreAlphabeticalAndEverythingStartsCollapsed() {
const model = buildHierarchy(fixture());
assert.deepEqual(
model.roots.map(({ module }) => module.moduleName),
['alpha_root', 'TB'],
'the two modules nothing instantiates, case-insensitively alphabetical',
);
// Owner, 2026-08-29: no level auto-expands. Opening the view shows the roots
// and nothing under them.
assert.deepEqual(labels(model), ['alpha_root', 'TB']);
const [, tb] = treeRows(model, new Set(), '').rows;
assert.equal(tb.hasChildren, true, 'but the twisty says there is more');
assert.equal(tb.expanded, false);
}
function openingOneLevelAtATimeWalksTheDesign() {
const model = buildHierarchy(fixture());
const open = [];
const openTo = (label) => {
const row = treeRows(model, new Set(open), '').rows
.find((candidate) => candidate.label === label);
assert(row, `${label} is not on screen: ${labels(model, open).join(', ')}`);
open.push(row.id);
return row;
};
openTo('TB');
assert.deepEqual(labels(model, open), ['alpha_root', 'TB', 'dut (top)']);
openTo('dut (top)');
openTo('inst1 (block)');
assert.deepEqual(labels(model, open), [
'alpha_root', 'TB', 'dut (top)', 'inst1 (block)', 'inst2 (leaf)',
]);
const deep = treeRows(model, new Set(open), '').nodes.get(open[open.length - 1]);
assert.equal(childrenOf(model, deep)[0].fullPath, 'TB.dut.inst1.inst2');
assert.equal(childrenOf(model, deep)[0].definition.uri, 'file:///leaf.sv');
}
function rowIdsSurviveARefresh() {
// What keeps the user's expansion state across a rescan: an id is composed
// from URIs and declaration positions, not from array order.
const first = buildHierarchy(fixture());
const shuffled = fixture();
shuffled.modules.reverse();
shuffled.revision = 4;
const second = buildHierarchy(shuffled);
const open = treeRows(first, new Set(), '').rows.map((row) => row.id);
assert.deepEqual(treeRows(second, new Set(), '').rows.map((row) => row.id), open);
assert.deepEqual(labels(second, open), labels(first, open));
}
function bookmarksResolveByPathWithoutATableOfEveryPath() {
const model = buildHierarchy(fixture());
const chain = bookmarkChain(model, 'TB.dut.inst1.inst2');
assert.equal(chain.length, 4);
assert.equal(idForPath(model, 'TB.dut.inst1.inst2'), chain[3]);
assert.equal(idForPath(model, 'TB.dut.nope'), undefined);
assert.equal(idForPath(model, ''), undefined);
// Expanding the chain's ancestors is what reveals the row.
const { rows } = treeRows(model, new Set(chain.slice(0, -1)), 'TB.dut.inst1.inst2');
assert.equal(rows.filter((row) => row.bookmarked).length, 1);
assert.equal(rows.find((row) => row.bookmarked).label, 'inst2 (leaf)');
}
function searchScansTheFlatIndexAndKeepsAncestorContext() {
const model = buildHierarchy(fixture());
const found = searchHierarchy(model, 'is2');
assert.equal(found.rows.length, 1, 'one row per instance, not one per path');
assert.equal(found.rows[0].label, 'inst2 (leaf)');
assert.equal(found.rows[0].detail, 'in block', 'the row says which module writes it');
assert.equal(searchHierarchy(model, 'tb.sv').total, 0, 'filenames are not searched');
assert.equal(searchHierarchy(model, 'TB.dut').total, 0, 'full paths are not searched');
assert.equal(searchHierarchy(model, '').total, 0, 'an empty query is not match-everything');
const target = searchTarget(model, found.rows[0].id);
assert.equal(target.kind, 'instance');
assert.equal(target.site.uri, 'file:///block.sv');
assert.equal(target.definition.uri, 'file:///leaf.sv');
assert.equal(target.fullPath, undefined, 'a flat hit has no one path');
assert.equal(searchTarget(model, 'find:nope'), undefined);
assert.equal(searchTarget(model, 'root:whatever'), undefined);
}
function recursionAndAmbiguityStayFinite() {
// `A` and `B` instantiate each other — the cycle — and `B` instantiates `C`,
// which two files declare, so every `C` row is ambiguous. Ambiguity is the
// model's own conclusion from the module table: the wire says only that the
// instance's type is spelled `C`.
const model = buildHierarchy({
schemaVersion: 2,
revision: 1,
complete: true,
files: ['file:///a.sv', 'file:///b.sv', 'file:///c.sv', 'file:///other-c.sv'],
modules: [
{ moduleName: 'A', definition: site(0, 0, 7, 8), instances: [
{ instanceName: 'u_b', moduleName: 'B', site: site(0, 1, 4, 7) },
] },
{ moduleName: 'B', definition: site(1, 0, 7, 8), instances: [
{ instanceName: 'u_a', moduleName: 'A', site: site(1, 1, 4, 7) },
{ instanceName: 'u_amb', moduleName: 'C', site: site(1, 2, 4, 9) },
] },
{ moduleName: 'C', definition: site(2, 0, 7, 8), instances: [] },
{ moduleName: 'C', definition: site(3, 0, 7, 8), instances: [] },
],
});
assert.deepEqual(
model.roots.map(({ module, fallback }) => [module.moduleName, fallback]),
[['C', false], ['C', false], ['A', true]],
'the two unparented `C` declarations, then one fallback root for the cycle',
);
// Open A, then u_b: the `u_a` under it is the cycle closing, and it is a leaf.
const open = [];
for (const label of ['A', 'u_b (B)']) {
open.push(treeRows(model, new Set(open), '').rows
.find((candidate) => candidate.label === label).id);
}
const { rows } = treeRows(model, new Set(open), '');
const recursive = rows.find((row) => row.kind === 'instance' && row.detail === 'recursive');
assert(recursive, 'the repeated edge is present and marked');
assert.equal(recursive.label, 'u_a (A)');
assert.equal(recursive.hasChildren, false, 'and does not open again');
const ambiguous = rows.find((row) => row.detail === 'ambiguous');
assert(ambiguous, 'a type two files declare is ambiguous');
assert.equal(ambiguous.hasChildren, false);
}
function scoringIsDeterministic() {
assert(fuzzyScore('inst2', 'inst2') > fuzzyScore('inst20', 'inst2'));
assert(fuzzyScore('u_fifo', 'ufi') > fuzzyScore('unrelated_f_i', 'ufi'));
assert.equal(fuzzyScore('module', 'xyz'), -1);
}
function malformedSnapshotsAreRejected() {
assert.throws(() => buildHierarchy({ schemaVersion: 1, files: [], modules: [] }), /unsupported/);
assert.throws(() => buildHierarchy({ ...fixture(), files: undefined }), /unsupported/);
const noRange = fixture();
noRange.modules[0].definition.selectionRange = null;
assert.throws(() => buildHierarchy(noRange), /malformed/);
const shortRange = fixture();
shortRange.modules[0].instances[0].site.range = [1, 2, 3];
assert.throws(() => buildHierarchy(shortRange), /malformed/);
const offTable = fixture();
offTable.modules[0].definition.file = FILES.length;
assert.throws(() => buildHierarchy(offTable), /malformed/);
}
/** The wire is narrow; the model is not. Everything the rest of the extension
* reads — a URI, `{ line, character }` positions, an id, the declarations an
* instance's module name resolves to — is rebuilt here. */
function theNarrowWireIsRebuiltIntoTheWideModel() {
const model = buildHierarchy(fixture());
const block = model.modules.find((module) => module.moduleName === 'block');
const [inst2] = block.instances;
assert.equal(inst2.site.uri, 'file:///block.sv');
assert.deepEqual(inst2.site.selectionRange, {
start: { line: 1, character: 7 },
end: { line: 1, character: 12 },
});
assert.equal(inst2.id, 'file:///block.sv#1:7');
assert.equal(inst2.definitions.length, 1, 'rebuilt from the module table');
assert.equal(inst2.definitions[0].uri, 'file:///leaf.sv');
assert.equal(inst2.unresolved, false);
assert.equal(inst2.ambiguous, false);
}
/** The owner's freeze, turned into a budget. 20 000 modules and 100 000
* instances — six times opentitan — built once, then queried. What is asserted
* is the shape of the cost with room to spare on a slow machine: an array scan
* is microseconds per entry, so 120 000 entries is single-digit milliseconds
* per query. */
function searchOverAHugeHierarchyStaysInsideItsBudget() {
const MODULES = 20000;
const PER_MODULE = 5;
const files = [];
const modules = [];
for (let m = 0; m < MODULES; m += 1) {
files.push(`file:///gen/mod_${m}.sv`);
const instances = [];
for (let i = 0; i < PER_MODULE; i += 1) {
instances.push({
instanceName: `u_inst_${m}_${i}`,
moduleName: `mod_${(m + i + 1) % MODULES}`,
site: { file: m, range: [i + 1, 2, i + 1, 40], selectionRange: [i + 1, 6, i + 1, 20] },
});
}
modules.push({
moduleName: `mod_${m}`,
definition: { file: m, range: [0, 0, 9, 9], selectionRange: [0, 7, 0, 14] },
instances,
});
}
const snapshot = { schemaVersion: 2, revision: 1, complete: true, files, modules };
const builtAt = process.hrtime.bigint();
const model = buildHierarchy(snapshot);
const buildMs = Number(process.hrtime.bigint() - builtAt) / 1e6;
assert.equal(model.entries.length, MODULES * (PER_MODULE + 1));
assert(buildMs < 8000, `building the model took ${buildMs.toFixed(1)} ms`);
// Rows are only built for what is open, so a collapsed tree over 100 000
// instances is one row per root and nothing else.
const rowsAt = process.hrtime.bigint();
const { rows } = treeRows(model, new Set(), '');
const rowsMs = Number(process.hrtime.bigint() - rowsAt) / 1e6;
assert(rows.length <= MODULES, 'a collapsed tree is at most one row per root');
assert(rowsMs < 500, `the collapsed tree took ${rowsMs.toFixed(1)} ms`);
// Every prefix of a word typed one character at a time — the keystroke
// sequence that froze the view.
let worst = 0;
for (const query of ['u', 'u_', 'u_i', 'u_in', 'u_ins', 'u_inst', 'u_inst_1', 'mod_999', 'zzz']) {
const at = process.hrtime.bigint();
const found = searchHierarchy(model, query);
const ms = Number(process.hrtime.bigint() - at) / 1e6;
worst = Math.max(worst, ms);
assert(found.rows.length <= SEARCH_LIMIT, `${query} rendered ${found.rows.length} rows`);
if (found.total > SEARCH_LIMIT) {
assert.equal(found.truncated, found.total - SEARCH_LIMIT, 'the "N more" count');
}
}
// Single-digit milliseconds is the target; 60 ms is the assertion, so a busy
// machine does not fail a test that is about orders of magnitude.
assert(
worst < 60,
`the slowest query took ${worst.toFixed(1)} ms over ${model.entries.length} entries`,
);
if (process.env.LUCISV_SEARCH_TIMINGS) {
console.log(` build ${buildMs.toFixed(1)} ms, collapsed tree ${rowsMs.toFixed(2)} ms, worst query ${worst.toFixed(2)} ms`);
}
}
/** QA (2026-08-29): the counting cutoff must choose the same top rows a full
* sort of every score would — checked here by hand, not by re-deriving
* `truncated` from the same numbers the search already produced. Five
* instances of one module, `leaf`, are scored against `fifo` by the
* documented rule (exact/prefix/substring tiers, then the subsequence loop's
* bonuses), and the ranking below is arithmetic anyone can redo:
* "fifo" exact 10000 + 1 (instance tie) = 10001
* "fifo_ctrl" prefix, 8000 - (9-4) = 7996
* "ffifo" substring at 1, 6000-10-(5-4) +1 = 5990
* "u_fifo" substring at 2, 6000-20-(6-4) +1 = 5979
* "f_i_f_o" subsequence only +1 = 65
* "unrelated" no match at all -1
* so the top 3 are "fifo", "fifo_ctrl", "ffifo" in that order, and 2 more
* (of the 5 real matches) are owed. */
function topKSearchMatchesWhatAFullSortWouldChoose() {
const files = ['file:///top.sv', 'file:///leaf.sv'];
const names = ['fifo', 'fifo_ctrl', 'ffifo', 'u_fifo', 'f_i_f_o', 'unrelated'];
const instances = names.map((name, i) => ({
instanceName: name,
moduleName: 'leaf',
site: site(0, i + 1, 2, 6 + name.length),
}));
const snapshot = {
schemaVersion: 2,
revision: 1,
complete: true,
files,
modules: [
{ moduleName: 'top', definition: site(0, 0, 7, 10), instances },
{ moduleName: 'leaf', definition: site(1, 0, 7, 11), instances: [] },
],
};
const model = buildHierarchy(snapshot);
const found = searchHierarchy(model, 'fifo', 3);
assert.deepEqual(
found.rows.map((row) => row.label.split(' ')[0]),
['fifo', 'fifo_ctrl', 'ffifo'],
'the counting cutoff must agree with a full sort by hand',
);
assert.equal(found.total, 5, 'exactly the five names that contain f, i, f, o in order');
assert.equal(found.truncated, 2, 'five real matches minus the three shown');
// The same query with no cap at all must return every match, in the same
// relative order, as a cross-check that capping never reorders anything.
const uncapped = searchHierarchy(model, 'fifo', 100);
assert.deepEqual(
uncapped.rows.map((row) => row.label.split(' ')[0]),
['fifo', 'fifo_ctrl', 'ffifo', 'u_fifo', 'f_i_f_o'],
);
}
/** QA (2026-08-29): the letter/digit bitmask is a coarse presence test — every
* non-alphanumeric, non-`_` character shares one bit — so it must only ever
* be more permissive than the real scorer, never less. Checked against an
* independent, un-bitmasked subsequence check (`isSubsequence` below, which
* does not use `maskOf` at all) over escaped-identifier-shaped names: an
* instance name a real design can actually carry, with `$`, `.` and `[]` in
* it, none of which are letters or digits and so all fold onto one bit. */
function theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch() {
function isSubsequence(haystack, needle) {
let cursor = 0;
for (const ch of needle) {
cursor = haystack.indexOf(ch, cursor);
if (cursor < 0) return false;
cursor += 1;
}
return true;
}
const cases = [
['\\pll.ref_clk[0]', 'pll.ref'],
['\\pll.ref_clk[0]', 'p.r[0'],
['a$b.c]d', 'a$c]d'],
['a$b.c]d', 'a.d'],
['zz9', 'z9'],
['a0z', 'a0z'],
];
for (const [haystack, needle] of cases) {
assert(
isSubsequence(haystack, needle),
`premise: "${needle}" is really a subsequence of "${haystack}"`,
);
assert(
fuzzyScore(haystack, needle) >= 0,
`the bitmask prefilter excluded a true match: "${needle}" in "${haystack}"`,
);
}
// End to end: the same names, reachable through `searchHierarchy`, not just
// through the scorer it calls.
const files = ['file:///top.sv', 'file:///leaf.sv'];
const model = buildHierarchy({
schemaVersion: 2,
revision: 1,
complete: true,
files,
modules: [
{ moduleName: 'top', definition: site(0, 0, 7, 10), instances: [
{ instanceName: '\\pll.ref_clk[0]', moduleName: 'leaf', site: site(0, 1, 2, 20) },
] },
{ moduleName: 'leaf', definition: site(1, 0, 7, 11), instances: [] },
],
});
assert.equal(searchHierarchy(model, 'pll.ref').rows.length, 1);
assert.equal(searchHierarchy(model, 'p.r[0').rows.length, 1);
}
for (const test of [
rootsAreAlphabeticalAndEverythingStartsCollapsed,
openingOneLevelAtATimeWalksTheDesign,
rowIdsSurviveARefresh,
bookmarksResolveByPathWithoutATableOfEveryPath,
searchScansTheFlatIndexAndKeepsAncestorContext,
recursionAndAmbiguityStayFinite,
scoringIsDeterministic,
malformedSnapshotsAreRejected,
theNarrowWireIsRebuiltIntoTheWideModel,
searchOverAHugeHierarchyStaysInsideItsBudget,
topKSearchMatchesWhatAFullSortWouldChoose,
theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch,
]) test();
console.log('hierarchy model: OK — collapsed roots, lazy levels, stable ids, bookmarks, search, cycles, validation, wire rebuilding, and the 120k-entry search budget');
+276
View File
@@ -0,0 +1,276 @@
const crypto = require('crypto');
const vscode = require('vscode');
const {
bookmarkChain,
buildHierarchy,
idForPath,
searchHierarchy,
searchTarget,
treeRows,
} = require('./hierarchyModel');
const VIEW_ID = 'lucisv.hierarchy';
const SNAPSHOT_METHOD = 'lucisv/moduleHierarchy';
const CHANGED_METHOD = 'lucisv/moduleHierarchyChanged';
const BOOKMARK_KEY = 'lucisv.hierarchy.bookmark';
const REFRESH_DEBOUNCE_MS = 100;
class HierarchyView {
constructor(context, client) {
this.context = context;
this.client = client;
this.view = undefined;
this.model = undefined;
this.query = '';
// Which rows the user has opened. Row ids are composed from URIs and
// declaration positions, so they survive a refresh and what was open stays
// open — nothing is expanded on the user's behalf (owner, 2026-08-29).
this.expanded = new Set();
this.nodes = new Map();
this.request = 0;
this.refreshTimer = undefined;
this.bookmarkPath = context.workspaceState.get(BOOKMARK_KEY, '');
this.lostBookmarkReported = false;
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(VIEW_ID, this, {
webviewOptions: { retainContextWhenHidden: true },
}),
vscode.commands.registerCommand('lucisv.hierarchy.refresh', () => this.refresh()),
vscode.commands.registerCommand('lucisv.hierarchy.clearBookmark', () => this.setBookmark('')),
client.onNotification(CHANGED_METHOD, () => this.scheduleRefresh()),
{ dispose: () => clearTimeout(this.refreshTimer) },
);
}
resolveWebviewView(view) {
this.view = view;
const media = vscode.Uri.joinPath(this.context.extensionUri, 'media');
view.webview.options = {
enableScripts: true,
localResourceRoots: [media],
};
this.context.subscriptions.push(
view.webview.onDidReceiveMessage((message) => this.message(message)),
view.onDidDispose(() => {
if (this.view === view) this.view = undefined;
}),
);
// Install the receiver before loading the document: its script posts
// `ready` immediately, and even a fast webview must not outrun the host.
view.webview.html = html(view.webview, media);
}
onStarted() {
this.refresh();
}
scheduleRefresh() {
clearTimeout(this.refreshTimer);
this.refreshTimer = setTimeout(() => this.refresh(), REFRESH_DEBOUNCE_MS);
}
async refresh() {
if (!this.view) return;
const asked = ++this.request;
this.post({ type: 'status', text: 'Loading hierarchy…' });
try {
const snapshot = await this.client.sendRequest(SNAPSHOT_METHOD, {});
if (asked !== this.request) return;
this.model = buildHierarchy(snapshot);
if (this.bookmarkPath && !idForPath(this.model, this.bookmarkPath)) {
await this.context.workspaceState.update(BOOKMARK_KEY, undefined);
this.bookmarkPath = '';
if (!this.lostBookmarkReported) {
this.lostBookmarkReported = true;
vscode.window.showWarningMessage('The bookmarked lucisv instance no longer exists uniquely.');
}
} else {
this.lostBookmarkReported = false;
}
this.render();
} catch (error) {
if (asked !== this.request) return;
const code = error && (error.code || (error.data && error.data.code));
const oldServer = code === -32601 || /method.*not found/i.test(String(error && error.message));
this.post({
type: 'status',
error: true,
text: oldServer
? 'This lucisv server is too old for the hierarchy sidebar.'
: 'The hierarchy is unavailable while the language server is restarting.',
});
}
}
/// Post exactly the rows the view shows — the open part of the tree, or one
/// page of search results. Never the whole design: shipping every path of it
/// on every keystroke is what froze the UI.
render() {
if (!this.model) return;
const common = {
type: 'render',
revision: this.model.revision,
complete: this.model.complete,
query: this.query,
empty: this.model.roots.length === 0,
};
if (this.query.trim() !== '') {
const found = searchHierarchy(this.model, this.query);
this.post({ ...common, mode: 'search', rows: found.rows, truncated: found.truncated, total: found.total });
return;
}
const tree = treeRows(this.model, this.expanded, this.bookmarkPath);
this.nodes = tree.nodes;
this.post({ ...common, mode: 'tree', rows: tree.rows, truncated: 0, total: tree.rows.length });
}
async message(message) {
if (!message || typeof message.type !== 'string') return;
if (message.type === 'ready') {
await this.refresh();
return;
}
if (message.type === 'search' && typeof message.query === 'string') {
this.query = message.query.slice(0, 256);
this.render();
return;
}
if (!this.model || typeof message.id !== 'string') return;
if (message.type === 'toggle') {
if (this.expanded.has(message.id)) this.expanded.delete(message.id);
else this.expanded.add(message.id);
this.render();
return;
}
// A tree row is a path the view is currently showing; a search row names a
// module and, for an instance, which module writes it. Both resolve to the
// same three things an action needs: a site, a definition, and candidates.
const node = this.nodes.get(message.id) || searchTarget(this.model, message.id);
if (!node) return;
if (message.type === 'activate') {
await this.show(node.kind === 'instance' ? node.site : node.definition, false);
return;
}
if (message.type !== 'context' || typeof message.action !== 'string') return;
const actions = new Set(['copyPath', 'definition', 'instance', 'bookmark', 'openRight']);
if (!actions.has(message.action) || node.kind !== 'instance') return;
// A search hit is one row for an instance however many paths reach it, so
// it has no one full path to copy or bookmark.
if (!node.fullPath && (message.action === 'copyPath' || message.action === 'bookmark')) {
vscode.window.showWarningMessage('Clear the search to copy or bookmark an instance path.');
return;
}
switch (message.action) {
case 'copyPath':
await vscode.env.clipboard.writeText(node.fullPath);
break;
case 'definition':
await this.showDefinition(node, false);
break;
case 'instance':
await this.show(node.site, false);
break;
case 'bookmark':
await this.setBookmark(this.bookmarkPath === node.fullPath ? '' : node.fullPath);
break;
case 'openRight':
await this.showDefinition(node, true);
break;
default:
break;
}
}
async setBookmark(path) {
this.bookmarkPath = path;
await this.context.workspaceState.update(BOOKMARK_KEY, path || undefined);
// The one expansion the view performs for the user, and only because the
// user asked for it by bookmarking: the direct ancestors of the marked row.
const chain = path && bookmarkChain(this.model, path);
if (chain) for (const id of chain.slice(0, -1)) this.expanded.add(id);
this.render();
}
async showDefinition(node, beside) {
let location;
if (node.definitions.length === 0) {
vscode.window.showWarningMessage(`No indexed definition was found for module ${node.moduleName}.`);
return;
}
if (node.definitions.length === 1) {
[location] = node.definitions;
} else {
const choices = node.definitions.map((candidate) => ({
label: vscode.workspace.asRelativePath(vscode.Uri.parse(candidate.uri), false),
description: `${candidate.selectionRange.start.line + 1}:${candidate.selectionRange.start.character + 1}`,
location: candidate,
}));
const picked = await vscode.window.showQuickPick(choices, {
placeHolder: `Choose a definition for ${node.moduleName}`,
});
if (!picked) return;
location = picked.location;
}
await this.show(location, beside);
}
async show(location, beside) {
if (!location) return;
const document = await vscode.workspace.openTextDocument(vscode.Uri.parse(location.uri));
await vscode.window.showTextDocument(document, {
viewColumn: beside ? vscode.ViewColumn.Beside : vscode.ViewColumn.Active,
preserveFocus: false,
preview: !beside,
selection: asRange(location.selectionRange),
});
}
post(message) {
if (this.view) this.view.webview.postMessage(message);
}
}
function asRange(range) {
return new vscode.Range(
range.start.line,
range.start.character,
range.end.line,
range.end.character,
);
}
function html(webview, media) {
const nonce = crypto.randomBytes(16).toString('base64');
const script = webview.asWebviewUri(vscode.Uri.joinPath(media, 'hierarchy.js'));
const style = webview.asWebviewUri(vscode.Uri.joinPath(media, 'hierarchy.css'));
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<link rel="stylesheet" href="${style}">
<title>lucisv Hierarchy</title>
</head>
<body>
<div class="search-wrap">
<input id="search" type="search" placeholder="Search module or instance" aria-label="Search module or instance names" autocomplete="off" spellcheck="false">
</div>
<div id="status" role="status" aria-live="polite">Loading hierarchy…</div>
<div id="tree" role="tree" aria-label="Module instance hierarchy"></div>
<div id="results" role="listbox" aria-label="Hierarchy search results" hidden></div>
<div id="more" hidden></div>
<div id="menu" role="menu" aria-label="Instance actions" hidden>
<button role="menuitem" data-action="copyPath">Copy Full Path</button>
<button role="menuitem" data-action="definition">Show Definition</button>
<button role="menuitem" data-action="instance">Show Instance</button>
<button role="menuitem" data-action="bookmark">Highlight / Bookmark</button>
<button role="menuitem" data-action="openRight">Open on the Right</button>
</div>
<script nonce="${nonce}" src="${script}"></script>
</body>
</html>`;
}
module.exports = { HierarchyView, VIEW_ID };
+190
View File
@@ -0,0 +1,190 @@
const assert = require('assert/strict');
const Module = require('module');
const disposables = () => ({ dispose() {} });
const posted = [];
const copied = [];
const opened = [];
const shown = [];
const warned = [];
let requests = 0;
let provider;
let receive;
let changed;
class Range {
constructor(startLine, startCharacter, endLine, endCharacter) {
this.start = { line: startLine, character: startCharacter };
this.end = { line: endLine, character: endCharacter };
}
}
const vscode = {
Uri: {
parse(value) { return { value, fsPath: value.replace('file://', ''), toString: () => value }; },
joinPath(base, ...parts) {
const value = [base.value || base.toString(), ...parts].join('/');
return { value, toString: () => value };
},
},
Range,
ViewColumn: { Active: 1, Beside: 2 },
env: { clipboard: { async writeText(value) { copied.push(value); } } },
commands: { registerCommand() { return disposables(); } },
workspace: {
asRelativePath(uri) { return uri.fsPath; },
async openTextDocument(uri) {
opened.push(uri.value);
return {
uri,
lineCount: 6,
lineAt(line) { return { text: `line ${line + 1}` }; },
};
},
},
window: {
registerWebviewViewProvider(_id, value) { provider = value; return disposables(); },
async showTextDocument(document, options) { shown.push({ document, options }); },
async showQuickPick(items) { return items[0]; },
showWarningMessage(text) { warned.push(text); },
},
};
const originalLoad = Module._load;
Module._load = function load(request, parent, main) {
if (request === 'vscode') return vscode;
return originalLoad(request, parent, main);
};
const { HierarchyView } = require('./hierarchyView');
Module._load = originalLoad;
// The schema-2 wire: a file table and four-number ranges, no ids and no
// per-instance `definitions` — `hierarchyModel.js` rebuilds all three.
function place(file, line, start, end) {
return { file, range: [line, 0, line, end + 2], selectionRange: [line, start, line, end] };
}
const snapshot = {
schemaVersion: 2,
revision: 1,
complete: true,
files: ['file:///top.sv', 'file:///sub.sv'],
modules: [
{ moduleName: 'top', definition: place(0, 0, 7, 10), instances: [
{ instanceName: 'u', moduleName: 'sub', site: place(0, 1, 6, 9) },
] },
{ moduleName: 'sub', definition: place(1, 0, 7, 10), instances: [] },
],
};
const state = new Map();
const context = {
extensionUri: { value: 'file:///extension', toString: () => 'file:///extension' },
subscriptions: [],
workspaceState: {
get(key, fallback) { return state.has(key) ? state.get(key) : fallback; },
async update(key, value) { if (value === undefined) state.delete(key); else state.set(key, value); },
},
};
const client = {
async sendRequest(method) {
assert.equal(method, 'lucisv/moduleHierarchy');
requests += 1;
return snapshot;
},
onNotification(method, handler) {
assert.equal(method, 'lucisv/moduleHierarchyChanged');
changed = handler;
return disposables();
},
};
new HierarchyView(context, client);
assert(provider, 'the webview provider is registered');
const webview = {
cspSource: 'vscode-webview:',
options: undefined,
html: '',
asWebviewUri(uri) { return uri.toString(); },
postMessage(message) { posted.push(message); },
onDidReceiveMessage(handler) { receive = handler; return disposables(); },
};
provider.resolveWebviewView({
webview,
onDidDispose() { return disposables(); },
});
assert(webview.html.includes('Search module or instance'));
assert(webview.html.includes('Content-Security-Policy'));
async function run() {
await receive({ type: 'ready' });
const rendered = () => posted.findLast((message) => message.type === 'render');
assert(rendered(), 'ready requests and renders a snapshot');
// Owner, 2026-08-29: everything starts collapsed — one row, the root.
assert.equal(rendered().mode, 'tree');
assert.deepEqual(rendered().rows.map((row) => row.label), ['top']);
const root = rendered().rows[0];
assert.equal(root.hasChildren, true);
assert.equal(root.expanded, false);
// Opening is the user's own act, and it is the only thing that builds the
// level below.
await receive({ type: 'toggle', id: root.id });
assert.deepEqual(rendered().rows.map((row) => row.label), ['top', 'u (sub)']);
const instance = rendered().rows[1];
// A query swaps in a flat, capped result list; clearing it puts the tree
// back with the same row open and no new snapshot request.
const requestsBefore = requests;
await receive({ type: 'search', query: 'u' });
assert.equal(rendered().mode, 'search');
assert(rendered().rows.some((row) => row.label === 'u (sub)'));
assert.equal(rendered().truncated, 0);
await receive({ type: 'search', query: '' });
assert.equal(rendered().mode, 'tree');
assert.deepEqual(rendered().rows.map((row) => row.label), ['top', 'u (sub)']);
assert.equal(requests, requestsBefore, 'searching never asks the server again');
await receive({ type: 'context', action: 'copyPath', id: instance.id });
assert.deepEqual(copied, ['top.u']);
await receive({ type: 'context', action: 'instance', id: instance.id });
assert.equal(opened.at(-1), 'file:///top.sv');
assert.equal(shown.at(-1).options.viewColumn, 1);
await receive({ type: 'context', action: 'openRight', id: instance.id });
assert.equal(opened.at(-1), 'file:///sub.sv');
assert.equal(shown.at(-1).options.viewColumn, 2);
assert.equal(shown.at(-1).options.preview, false);
await receive({ type: 'context', action: 'bookmark', id: instance.id });
assert.equal(state.get('lucisv.hierarchy.bookmark'), 'top.u');
assert.equal(rendered().rows.find((row) => row.bookmarked).label, 'u (sub)');
// A search row navigates, but has no one path to copy or bookmark.
await receive({ type: 'search', query: 'u' });
const hit = rendered().rows.find((row) => row.kind === 'instance');
await receive({ type: 'context', action: 'definition', id: hit.id });
assert.equal(opened.at(-1), 'file:///sub.sv');
const copiedBefore = copied.length;
await receive({ type: 'context', action: 'copyPath', id: hit.id });
assert.equal(copied.length, copiedBefore, 'a flat hit has no full path to copy');
assert.equal(warned.at(-1), 'Clear the search to copy or bookmark an instance path.');
await receive({ type: 'search', query: '' });
// The source-line hover preview was removed at the owner's request
// (2026-08-29): a `hover` message is now one the view does not answer, and
// it must not resurrect the code that read a document behind the tree.
const before = posted.length;
await receive({ type: 'hover', id: instance.id });
assert.equal(posted.length, before, 'a hover posts nothing back');
assert(!posted.some((message) => message.type === 'preview'), 'no preview is ever posted');
assert(!webview.html.includes('id="preview"'), 'and the popover is gone from the markup');
assert.equal(typeof changed, 'function');
console.log('hierarchy view: OK — collapsed rows, lazy opening, search list, navigation, menu, bookmark, and no preview');
}
run().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="5" rx="1"/>
<rect x="14" y="10" width="7" height="5" rx="1"/>
<rect x="14" y="17" width="7" height="4" rx="1"/>
<path d="M6.5 8v5h7.5M10 5.5h2a3 3 0 0 1 3 3V10M10 5.5h2a3 3 0 0 1 3 3V17"/>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+85
View File
@@ -0,0 +1,85 @@
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
body {
margin: 0;
padding: 0;
color: var(--vscode-foreground);
background: var(--vscode-sideBar-background);
font: var(--vscode-font-weight) var(--vscode-font-size)/1.4 var(--vscode-font-family);
overflow: hidden auto;
}
.search-wrap {
position: sticky;
top: 0;
z-index: 3;
padding: 6px 8px;
background: var(--vscode-sideBar-background);
}
#search {
width: 100%;
height: 26px;
padding: 2px 7px;
color: var(--vscode-input-foreground);
background: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border, transparent);
outline: none;
}
#search:focus { border-color: var(--vscode-focusBorder); }
#status { padding: 8px 10px; color: var(--vscode-descriptionForeground); }
#status.error { color: var(--vscode-errorForeground); }
#tree, #results { padding-bottom: 8px; }
#more { padding: 4px 10px 10px; color: var(--vscode-descriptionForeground); }
.row {
--indent: calc(var(--depth) * 12px);
width: 100%;
min-height: 22px;
display: flex;
align-items: center;
gap: 4px;
padding: 1px 8px 1px calc(4px + var(--indent));
border: 1px solid transparent;
color: inherit;
background: transparent;
font: inherit;
text-align: left;
cursor: default;
}
.row:hover { background: var(--vscode-list-hoverBackground); }
.row:focus { outline: 1px solid var(--vscode-list-focusOutline, var(--vscode-focusBorder)); outline-offset: -1px; }
.row.match .label { font-weight: 600; }
.row.bookmarked {
background: color-mix(in srgb, var(--vscode-charts-yellow, #cca700) 35%, transparent);
border-color: var(--vscode-charts-yellow, #cca700);
}
.row.warning .detail { color: var(--vscode-list-warningForeground, var(--vscode-editorWarning-foreground)); }
.twisty { width: 12px; flex: 0 0 12px; text-align: center; }
.icon { width: 14px; flex: 0 0 14px; color: var(--vscode-symbolIcon-moduleForeground, var(--vscode-foreground)); }
.label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.detail { margin-left: auto; font-size: .9em; color: var(--vscode-descriptionForeground); }
#menu {
position: fixed;
z-index: 10;
width: 185px;
padding: 4px;
background: var(--vscode-menu-background);
color: var(--vscode-menu-foreground);
border: 1px solid var(--vscode-menu-border, var(--vscode-widget-border));
box-shadow: 0 4px 12px var(--vscode-widget-shadow);
}
#menu button {
display: block;
width: 100%;
padding: 4px 8px;
border: 0;
color: inherit;
background: transparent;
text-align: left;
font: inherit;
}
#menu button:hover, #menu button:focus {
color: var(--vscode-menu-selectionForeground);
background: var(--vscode-menu-selectionBackground);
outline: none;
}
[hidden] { display: none !important; }
@media (forced-colors: active) { .row.bookmarked { outline: 2px solid Highlight; } }
+192
View File
@@ -0,0 +1,192 @@
// The hierarchy view's renderer. It draws exactly the rows the extension host
// sends and owns no model of its own: the host holds the flat snapshot, opens
// one level at a time, and answers a query from a prebuilt index. What used to
// arrive here was every path of the whole design, rebuilt and re-sent on every
// keystroke — the freeze the owner reported on 2026-08-29.
const vscode = acquireVsCodeApi();
const search = document.getElementById('search');
const tree = document.getElementById('tree');
const results = document.getElementById('results');
const more = document.getElementById('more');
const status = document.getElementById('status');
const menu = document.getElementById('menu');
/** Long enough that a fast typist sends one query, short enough to feel live. */
const SEARCH_DEBOUNCE_MS = 60;
let payload = { mode: 'tree', rows: [], truncated: 0, query: '' };
let menuNode;
let searchTimer;
search.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(
() => vscode.postMessage({ type: 'search', query: search.value }),
SEARCH_DEBOUNCE_MS,
);
});
search.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && search.value) {
search.value = '';
clearTimeout(searchTimer);
vscode.postMessage({ type: 'search', query: '' });
}
if (event.key === 'ArrowDown') firstVisibleRow()?.focus();
});
window.addEventListener('message', ({ data }) => {
if (!data || typeof data.type !== 'string') return;
if (data.type === 'status') {
status.textContent = data.text;
status.classList.toggle('error', Boolean(data.error));
status.hidden = false;
if (data.error) {
tree.replaceChildren();
results.replaceChildren();
}
return;
}
if (data.type !== 'render') return;
payload = data;
if (search.value !== data.query) search.value = data.query;
render();
});
// The tree and the result list are two containers, and a query swaps which one
// is shown. Searching therefore never tears the tree down, and clearing the
// search puts back exactly the rows that were open — no re-request, no rebuild.
function render() {
const searching = payload.mode === 'search';
const container = searching ? results : tree;
const fragment = document.createDocumentFragment();
for (const row of payload.rows) fragment.appendChild(renderRow(row, searching));
container.replaceChildren(fragment);
tree.hidden = searching;
results.hidden = !searching;
more.textContent = payload.truncated > 0
? `${payload.truncated} more match${payload.truncated === 1 ? '' : 'es'} — narrow the search.`
: '';
more.hidden = payload.truncated === 0;
const message = payload.empty
? 'No indexed modules.'
: (searching && payload.rows.length === 0
? 'No module or instance name matches.'
: (!payload.complete ? 'Indexing… showing a partial hierarchy.' : ''));
status.textContent = message;
status.hidden = message === '';
status.classList.remove('error');
}
function renderRow(row, searching) {
const wrapper = document.createElement('div');
wrapper.className = 'node';
wrapper.dataset.id = row.id;
const button = document.createElement('button');
button.className = 'row';
button.type = 'button';
button.setAttribute('role', searching ? 'option' : 'treeitem');
button.setAttribute('aria-level', String(row.depth + 1));
button.style.setProperty('--depth', row.depth);
if (row.bookmarked) button.classList.add('bookmarked');
if (row.warning) button.classList.add('warning');
if (searching) button.classList.add('match');
if (row.hasChildren) button.setAttribute('aria-expanded', String(row.expanded));
const twisty = document.createElement('span');
twisty.className = 'twisty';
twisty.textContent = row.hasChildren ? (row.expanded ? '⌄' : '›') : '';
twisty.setAttribute('aria-hidden', 'true');
const icon = document.createElement('span');
icon.className = 'icon';
icon.textContent = row.kind === 'module' ? '▣' : (row.detail === 'recursive' ? '↻' : '◇');
icon.setAttribute('aria-hidden', 'true');
const label = document.createElement('span');
label.className = 'label';
label.textContent = row.label;
const detail = document.createElement('span');
detail.className = 'detail';
detail.textContent = row.detail || '';
button.append(twisty, icon, label, detail);
button.addEventListener('click', (event) => {
if (row.hasChildren && event.detail === 1 && event.offsetX < 28 + row.depth * 12) {
vscode.postMessage({ type: 'toggle', id: row.id });
} else {
vscode.postMessage({ type: 'activate', id: row.id });
}
});
button.addEventListener('dblclick', () => {
if (row.hasChildren) vscode.postMessage({ type: 'toggle', id: row.id });
});
button.addEventListener('contextmenu', (event) => openMenu(event, row));
button.addEventListener('keydown', (event) => key(event, row));
wrapper.appendChild(button);
return wrapper;
}
function key(event, row) {
if ((event.key === 'ContextMenu') || (event.shiftKey && event.key === 'F10')) {
event.preventDefault();
const rect = event.currentTarget.getBoundingClientRect();
openMenu({ preventDefault() {}, clientX: rect.left + 16, clientY: rect.bottom }, row);
return;
}
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
vscode.postMessage({ type: 'activate', id: row.id });
} else if (event.key === 'ArrowRight' && row.hasChildren) {
event.preventDefault();
if (!row.expanded) vscode.postMessage({ type: 'toggle', id: row.id });
else nextRow(event.currentTarget)?.focus();
} else if (event.key === 'ArrowLeft') {
event.preventDefault();
if (row.hasChildren && row.expanded) vscode.postMessage({ type: 'toggle', id: row.id });
else previousRow(event.currentTarget)?.focus();
} else if (event.key === 'ArrowDown') {
event.preventDefault();
nextRow(event.currentTarget)?.focus();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
previousRow(event.currentTarget)?.focus();
}
}
function shown() { return payload.mode === 'search' ? results : tree; }
function rows() { return [...shown().querySelectorAll('.row')]; }
function firstVisibleRow() { return rows()[0]; }
function nextRow(row) { const all = rows(); return all[all.indexOf(row) + 1]; }
function previousRow(row) { const all = rows(); return all[all.indexOf(row) - 1]; }
function openMenu(event, row) {
event.preventDefault();
if (row.kind !== 'instance') return;
menuNode = row;
menu.hidden = false;
menu.style.left = `${Math.min(event.clientX, innerWidth - 190)}px`;
menu.style.top = `${Math.min(event.clientY, innerHeight - 180)}px`;
menu.querySelector('[data-action="bookmark"]').textContent = row.bookmarked
? 'Remove Highlight / Bookmark' : 'Highlight / Bookmark';
menu.querySelector('button').focus();
}
menu.addEventListener('click', (event) => {
const action = event.target && event.target.dataset.action;
if (action && menuNode) vscode.postMessage({ type: 'context', action, id: menuNode.id });
closeMenu();
});
menu.addEventListener('keydown', (event) => {
const items = [...menu.querySelectorAll('button')];
const at = items.indexOf(document.activeElement);
if (event.key === 'Escape') closeMenu();
if (event.key === 'ArrowDown') items[(at + 1) % items.length].focus();
if (event.key === 'ArrowUp') items[(at - 1 + items.length) % items.length].focus();
});
document.addEventListener('mousedown', (event) => {
if (!menu.contains(event.target)) closeMenu();
});
function closeMenu() { menu.hidden = true; menuNode = undefined; }
vscode.postMessage({ type: 'ready' });
+54 -4
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.14.0",
"version": "0.15.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -50,9 +50,54 @@
"main": "./extension.js",
"activationEvents": [
"onLanguage:verilog",
"onLanguage:systemverilog"
"onLanguage:systemverilog",
"onView:lucisv.hierarchy"
],
"contributes": {
"viewsContainers": {
"activitybar": [
{
"id": "lucisv",
"title": "lucisv",
"icon": "images/hierarchy.svg"
}
]
},
"views": {
"lucisv": [
{
"type": "webview",
"id": "lucisv.hierarchy",
"name": "Hierarchy"
}
]
},
"commands": [
{
"command": "lucisv.hierarchy.refresh",
"title": "Refresh Hierarchy",
"icon": "$(refresh)"
},
{
"command": "lucisv.hierarchy.clearBookmark",
"title": "Clear Hierarchy Bookmark",
"icon": "$(clear-all)"
}
],
"menus": {
"view/title": [
{
"command": "lucisv.hierarchy.refresh",
"when": "view == lucisv.hierarchy",
"group": "navigation@1"
},
{
"command": "lucisv.hierarchy.clearBookmark",
"when": "view == lucisv.hierarchy",
"group": "navigation@2"
}
]
},
"configurationDefaults": {
"[verilog]": {
"editor.defaultColorDecorators": "never"
@@ -187,6 +232,11 @@
"default": "lucisv-server",
"description": "Path to the lucisv-server executable. Overrides the server bundled with the extension. A bare name is looked up on PATH."
},
"lucisv.verbose": {
"type": "boolean",
"default": false,
"markdownDescription": "Print how long every operation took in the lucisv output channel: one `timing:` line per request answered and per notification handled, plus the workspace scans, the index widens, the buffer flushes and any request that had to wait behind a rescan. Off by default and worth turning on only to answer \"why did that feel slow?\" — a busy session logs a line per keystroke. **Changing this restarts the language server**, because it is an argument the server is started with (`lucisv-server --verbose`), not something it can be told mid-session."
},
"lucisv.rainbowBeginEnd": {
"type": "boolean",
"default": true,
@@ -247,9 +297,9 @@
},
"lucisv.index.scopeDepth": {
"type": "number",
"default": 0,
"default": 2,
"minimum": 0,
"markdownDescription": "How many folders **above** an open file the `folder` scope starts from — the reach for relative files. `0` (the default) is the file's own folder and everything under it. `1` starts one folder up, so a file in `rtl/` also indexes `include/` beside it. The climb never leaves the workspace folder that contains the file, so a large number simply means the whole workspace folder. Raising this widens every answer listed under `#lucisv.index.scope#` and costs a larger scan. Ignored when `#lucisv.index.scope#` is `workspace` or a `#lucisv.filelist#` is set. With **no** workspace folder open there is nothing to clamp the climb against, so leave it at `0` for single files."
"markdownDescription": "How many folders **above** an open file the `folder` scope starts from — the reach for relative files. `2` (the default) starts two folders up, which in a typical layout is the whole block an open file belongs to: a file in `hw/ip/aes/rtl/` indexes all of `hw/ip/aes/`, `dv/` and `rtl/` together. `0` is the file's own folder and nothing above it — the old default, and the narrowest, fastest scope there is. The climb never leaves the workspace folder that contains the file, so a large number simply means the whole workspace folder. Raising this widens every answer listed under `#lucisv.index.scope#` and costs a larger scan. Ignored when `#lucisv.index.scope#` is `workspace` or a `#lucisv.filelist#` is set. With **no** workspace folder open there is nothing to clamp the climb against, so set it to `0` when you open single files on their own."
},
"lucisv.index.maxFileSize": {
"type": "number",
+170
View File
@@ -0,0 +1,170 @@
// One serialized restart chain for the language server, and nothing else.
//
// The server's arguments are decided at spawn time (`--verbose`, from
// `lucisv.verbose`), so the only way to change them is to start a new process.
// Doing that naively loses toggles: `vscode-languageclient` 9's `start()`
// returns the *in-flight* start whenever one exists, and its `stop()` rejects
// while the client is still `Starting` — so a toggle that lands during a slow
// first scan can stop nothing, rejoin the start that is already running with
// the old arguments, and report success. The user then believes the setting
// took effect while the server has no idea about it (QA finding 1, 2026-08-29).
//
// The fix is one rule: **there is exactly one chain of transitions, and it
// always reconciles to the last arguments anybody asked for.** Every toggle
// records what it wants and queues onto the same promise, so two transitions
// can never overlap, and a burst of toggles collapses into at most one restart
// that lands on the final answer.
//
// The rule has a second half, and it is the same rule: **no transition exists
// outside the chain either** — teardown included. `deactivate()` used to stop
// the client itself, attached to a *snapshot* of the chain, so a toggle landing
// in the same tick queued a whole reconcile — stop and then **spawn** — beside
// it, with nothing left to await the new process. On an extension disable or an
// extension-host restart, where the host outlives the module, that server is an
// orphan (QA finding 3, 2026-08-29). `dispose()` is the answer: it closes the
// door (`want()` and any already-queued reconcile become no-ops) and puts the
// final stop on the same chain as everything else.
//
// This file knows nothing about VS Code — it takes a client-like object with
// `start()`/`stop()` — which is what lets `restart_test.js` drive it headlessly
// without re-implementing the language client's own state machine.
// See docs/features/verbose-timing/README.md.
/**
* Whether two argument lists are the same list.
*
* `null` is "nothing is running", and it is equal to nothing — not even to
* another `null` — so a reconcile after a failed start always tries again.
*/
function sameArgs(a, b) {
if (a === null || b === null) return false;
return a.length === b.length && a.every((arg, index) => arg === b[index]);
}
/**
* A restarter for one language client.
*
* - `client` — anything with `start()` and `stop()` returning promises.
* - `serverOptions` — the object the client reads its spawn arguments from at
* every `start()`; the desired arguments are written into `.args` here.
* - `onStarted` — called after each successful start (the decorations went
* with the old connection and have to be repainted).
* - `onStartFailed` — called with the error when a start rejects. Not
* optional, and not a place to swallow: the chain survives, so the next
* toggle retries.
*
* `start()` is the first link of the chain — the activation spawn — so a
* toggle arriving while it is still running queues behind it instead of
* racing it. `dispose()` is the last one. That ordering *is* the fix: calling
* `client.start()` or `client.stop()` anywhere else puts a transition outside
* the chain again, which is how both of this feature's restart bugs happened.
*/
function createRestarter({ client, serverOptions, onStarted, onStartFailed }) {
/** What the process that is running (or starting) was given. */
let runningArgs = null;
/** What the settings ask for now. Written synchronously by every toggle, so
* a change that lands mid-restart is recorded even though it cannot act
* yet. */
let desiredArgs = serverOptions.args.slice();
/** The tail of the chain. Everything queues onto this and nothing else. */
let chain = Promise.resolve();
/** How many spawns have actually been attempted — for the tests, and for
* anyone wondering whether a burst of toggles cost one restart or four. */
let spawns = 0;
/** Whether the door is shut. Set synchronously by `dispose`, and checked
* both by `want` (nothing new is accepted) and by `reconcile` (whatever was
* already queued does nothing) — the second check is the one that matters,
* because a toggle can beat `dispose` into the queue by a tick. */
let disposed = false;
/** Make what is running match what is wanted, or do nothing if it already
* does. Never called concurrently with itself: it only runs on the chain. */
async function reconcile() {
// Queued before the door shut. Whatever it wanted, the answer is now
// "nothing" — this is what stops a teardown from spawning a server.
if (disposed) return;
if (sameArgs(runningArgs, desiredArgs)) return;
const wanted = desiredArgs.slice();
if (runningArgs !== null) {
try {
await client.stop();
} catch {
// A client that is not running cannot be stopped, and one already
// stopping is being stopped by somebody else. Neither is a reason not
// to start the process we actually want — and because this runs on the
// chain, "somebody else" is never another reconcile.
}
}
// Written before the start, because that is when the client reads them.
serverOptions.args = wanted;
runningArgs = wanted;
spawns += 1;
try {
await client.start();
} catch (error) {
// Nothing is running, so the next toggle must try again whatever it
// asks for — including the arguments that just failed.
runningArgs = null;
throw error;
}
onStarted();
}
/** The last transition there will ever be: stop whatever is running, and
* leave nothing to start. Never rejects — a client that will not stop while
* the host is going away is not something anyone can act on, and the client
* says so itself if it has anything to say. */
async function stopForGood() {
if (runningArgs === null) return;
runningArgs = null;
try {
await client.stop();
} catch {
// See above: teardown, and nothing to be done about it.
}
}
/** Queue one reconcile, and report a failed start rather than swallowing it.
* The `catch` is what keeps the chain usable for every later toggle — and
* what makes `chain` a promise that always resolves. */
function queue() {
chain = chain.then(reconcile).catch(onStartFailed);
return chain;
}
return {
/** Spawn the server for the first time. The first link of the chain. */
start: queue,
/** Ask for these arguments. Returns when the chain has reconciled.
* A no-op, silently, once `dispose` has been called: nothing may spawn a
* server after teardown has begun. */
want(args) {
if (disposed) return chain;
desiredArgs = args.slice();
return queue();
},
/**
* Shut the door and stop the server, as the last link of the same chain.
*
* Two halves, and both are needed: the flag makes `want` and any reconcile
* already queued do nothing, and the final stop goes *through the chain*
* rather than beside it, so nothing can interleave with it. Await what it
* returns — that is teardown finished. Idempotent.
*/
dispose() {
if (disposed) return chain;
disposed = true;
chain = chain.then(stopForGood);
return chain;
},
/** Everything queued so far, for a test or a `deactivate`. */
settled: () => chain,
/** The arguments the running process was spawned with, or `null` if none
* is running. */
spawnedWith: () => (runningArgs === null ? null : runningArgs.slice()),
/** How many spawns have been attempted. */
spawns: () => spawns,
};
}
module.exports = { createRestarter, sameArgs };
+322
View File
@@ -0,0 +1,322 @@
// Checks for `restart.js`: the serialized restart chain that makes a
// `lucisv.verbose` toggle land on the server, whenever it arrives.
//
// node restart_test.js
//
// Exits 0 on success, 1 on any failure. Plain node, no dependencies and no
// test runner — the same style as `smoke.js` next to it, and run the same way
// (`tools/release.sh` runs `smoke.js`; this one is a developer check).
//
// The fake client below scripts only what `restart.js` is allowed to depend
// on: `start()` and `stop()` return promises, and this file decides when they
// settle. It deliberately does **not** re-implement `vscode-languageclient`'s
// state machine — QA's throwaway harness did, and a copy of somebody else's
// state machine is a test of the copy. What is pinned here is *our* rule: one
// chain, no overlapping transitions, and the last toggle always wins.
// See docs/features/verbose-timing/README.md.
const { createRestarter, sameArgs } = require('./restart');
let checks = 0;
function ok(condition, what) {
checks += 1;
if (!condition) fail(what);
}
function equal(got, want, what) {
checks += 1;
const a = JSON.stringify(got);
const b = JSON.stringify(want);
if (a !== b) fail(`${what}: got ${a}, want ${b}`);
}
function fail(message) {
console.error(`restart: FAIL — ${message}`);
process.exit(1);
}
/** Let every already-resolved promise run. */
const settle = () => new Promise((resolve) => setImmediate(resolve));
/**
* A client whose `start()`/`stop()` this test settles by hand, and a
* `serverOptions` for it to read arguments from.
*
* `spawns` records the arguments of every start *as the client would have read
* them* — which is the whole question a lost toggle turns on.
*/
function fake({ pendingStarts = 0 } = {}) {
const serverOptions = { command: 'lucisv-server', args: [], transport: 'stdio' };
const state = {
serverOptions,
spawns: [],
stops: 0,
started: 0,
failures: [],
/** Resolves the start that is waiting, while there are pending ones left. */
release: null,
pendingStarts,
failNextStart: false,
};
const client = {
start() {
state.spawns.push(serverOptions.args.slice());
if (state.failNextStart) {
state.failNextStart = false;
return Promise.reject(new Error('spawn ENOENT'));
}
// Only the first `pendingStarts` spawns hang — the ones a test is about.
// A restart that follows resolves at once, like a spawn that works.
if (state.pendingStarts <= 0) return Promise.resolve();
state.pendingStarts -= 1;
return new Promise((resolve, reject) => {
state.release = { resolve, reject };
});
},
stop() {
state.stops += 1;
return Promise.resolve();
},
};
state.restarter = createRestarter({
client,
serverOptions,
onStarted: () => {
state.started += 1;
},
onStartFailed: (error) => state.failures.push(error.message),
});
state.client = client;
return state;
}
async function activationSpawnsOnceWithTheSettingsArguments() {
const it = fake();
it.serverOptions.args = ['--verbose'];
const restarter = createRestarter({
client: it.client,
serverOptions: it.serverOptions,
onStarted: () => {},
onStartFailed: fail,
});
await restarter.start();
equal(it.spawns, [['--verbose']], 'activation spawns once, with what the settings said');
equal(restarter.spawnedWith(), ['--verbose'], 'and remembers what it spawned with');
}
async function aToggleDuringTheActivationStartIsNotLost() {
// QA finding 1, 2026-08-29, and the reason this file exists. The activation
// start is still in flight — a large workspace's first scan holds it open —
// when the user turns `lucisv.verbose` on. Before the chain, `stop()` failed,
// `start()` rejoined the in-flight start with the OLD arguments, and the
// extension repainted as if the toggle had worked.
const it = fake({ pendingStarts: 1 });
it.restarter.start();
await settle();
equal(it.spawns, [[]], 'the activation spawn is in flight, with no arguments');
const toggled = it.restarter.want(['--verbose']);
await settle();
equal(it.spawns, [[]], 'and nothing else may spawn while it is: no overlapping transitions');
equal(it.stops, 0, 'and nothing is stopped mid-start');
it.release.resolve();
await toggled;
equal(it.spawns, [[], ['--verbose']], 'the toggle is honoured once the start it queued behind is done');
equal(it.stops, 1, 'by stopping the server that had the old arguments');
equal(it.serverOptions.args, ['--verbose'], 'the client reads the new arguments at that start');
equal(it.restarter.spawnedWith(), ['--verbose'], 'and the running server is the one the user asked for');
equal(it.started, 2, 'both starts repaint');
}
async function aBurstOfTogglesCollapsesToOneRestartOnTheLastOne() {
// on -> off -> on while a start is in flight: three toggles, one restart,
// and it lands on the last thing anybody asked for.
const it = fake({ pendingStarts: 1 });
it.restarter.start();
await settle();
it.restarter.want(['--verbose']);
it.restarter.want([]);
const last = it.restarter.want(['--verbose']);
await settle();
equal(it.spawns, [[]], 'still nothing extra while the first start is in flight');
it.release.resolve();
await last;
equal(it.spawns, [[], ['--verbose']], 'three toggles cost one restart');
equal(it.restarter.spawns(), 2, 'and the restarter says so');
equal(it.restarter.spawnedWith(), ['--verbose'], 'landing on the last toggle');
}
async function aToggleBackToWhatIsRunningRestartsNothing() {
const it = fake();
await it.restarter.start();
await it.restarter.want(['--verbose']);
equal(it.spawns.length, 2, 'the real change restarts');
await it.restarter.want(['--verbose']);
equal(it.spawns.length, 2, 'asking for what is already running does nothing');
equal(it.stops, 1, 'and stops nothing');
}
async function aFailedStartIsReportedAndTheChainStaysUsable() {
const it = fake();
await it.restarter.start();
it.failNextStart = true;
await it.restarter.want(['--verbose']);
equal(it.failures, ['spawn ENOENT'], 'the failure is reported, not swallowed');
equal(it.restarter.spawnedWith(), null, 'and nothing is recorded as running');
// The next toggle must *ask* again, including for the arguments that just
// failed. Whether the ask can succeed is not this module's call: the real
// `vscode-languageclient` never clears `_onStart` after a failed start, so it
// hands back the same rejection without spawning anything (the known
// limitation in the feature README). What is pinned here is that `restart.js`
// keeps asking rather than going quiet — the fake below is free to succeed.
await it.restarter.want(['--verbose']);
equal(it.spawns, [[], ['--verbose'], ['--verbose']], 'the chain is still usable and retries');
equal(it.failures.length, 1, 'and the retry that worked reports nothing');
}
async function aStopThatRejectsDoesNotStopTheRestart() {
// A client that will not stop — not running, or already stopping — must not
// cost the user the start they actually asked for.
const it = fake();
await it.restarter.start();
it.client.stop = () => Promise.reject(new Error('Client is not running'));
await it.restarter.want(['--verbose']);
equal(it.spawns, [[], ['--verbose']], 'the start happens anyway');
equal(it.failures, [], 'and a refused stop is not a start failure');
}
async function aToggleInTheSameTickAsDisposeSpawnsNothing() {
// QA finding 3, 2026-08-29, as they reproduced it: with `deactivate()`
// stopping the client itself — attached to a *snapshot* of the chain — a
// `lucisv.verbose` event arriving in the same tick queued a full reconcile
// beside it and the trace read `stop, stop, start(--verbose)`. That last
// spawn had nothing left to await or stop it: an orphan, whenever the
// extension host outlives the module (a disable, or a host-only restart).
const it = fake();
await it.restarter.start();
equal(it.spawns, [[]], 'the server is up');
const gone = it.restarter.dispose();
it.restarter.want(['--verbose']); // the racing toggle, same tick
await gone;
await settle();
equal(it.spawns, [[]], 'nothing is ever spawned after teardown begins');
equal(it.stops, 1, 'and the one stop is the teardown one');
equal(it.restarter.spawnedWith(), null, 'nothing is left running');
// And the door stays shut: a later toggle is a silent no-op, not a spawn.
const after = it.restarter.want([]);
await after;
equal(it.spawns, [[]], 'a toggle after teardown does nothing at all');
// Nothing is even *queued* after teardown — `want` hands back the teardown
// promise itself rather than adding a reconcile for the flag inside
// `reconcile` to no-op. Both guards are wanted: this one keeps the chain
// from growing, and the one in `reconcile` catches what got in first.
ok(after === gone, 'a toggle after teardown adds no link to the chain');
}
async function aReconcileQueuedBeforeDisposeBecomesANoOp() {
// The other order, and the reason the flag is checked inside `reconcile` and
// not only in `want`: the toggle got into the queue first, and `dispose`
// shut the door behind it. What was queued must do nothing rather than
// spawn — the chain guarantees it runs *after* dispose was called, not that
// it was never queued.
const it = fake({ pendingStarts: 1 });
it.restarter.start();
await settle();
equal(it.spawns, [[]], 'the activation start is in flight');
it.restarter.want(['--verbose']); // queued behind the in-flight start
const gone = it.restarter.dispose(); // ...and then the window closes
it.release.resolve();
await gone;
equal(it.spawns, [[]], 'the queued toggle spawns nothing once the door is shut');
equal(it.stops, 1, 'only the teardown stop happens');
equal(it.restarter.spawnedWith(), null, 'and nothing is left running');
}
async function disposeResolvesAfterTheFinalStop() {
// What `deactivate()` returns is what VS Code waits on, so it has to mean
// "the server is stopped", not "the stop was queued".
const it = fake();
await it.restarter.start();
let stopped = false;
it.client.stop = () =>
new Promise((resolve) =>
setTimeout(() => {
stopped = true;
it.stops += 1;
resolve();
}, 10),
);
await it.restarter.dispose();
ok(stopped, 'dispose() resolves only once the final stop has finished');
equal(it.stops, 1, 'and it really stopped the client');
// Idempotent: disposing twice is one stop, and still resolves.
await it.restarter.dispose();
equal(it.stops, 1, 'a second dispose stops nothing again');
// And two disposes in the *same tick* both mean "teardown is finished" —
// which is only true if the final stop went onto the chain rather than
// beside it, since the second caller gets the chain as it stands.
const again = fake();
await again.restarter.start();
let down = false;
again.client.stop = () =>
new Promise((resolve) =>
setTimeout(() => {
down = true;
resolve();
}, 10),
);
await Promise.all([again.restarter.dispose(), again.restarter.dispose()]);
ok(down, 'both callers wait for the one stop that actually happens');
}
async function disposingBeforeAnythingSpawnedStopsNothing() {
// An activation that failed before a server existed must not stop a client
// that was never started — the real one rejects that, loudly.
const it = fake();
await it.restarter.dispose();
equal(it.stops, 0, 'nothing was running, so nothing is stopped');
equal(it.spawns, [], 'and nothing was ever spawned');
}
function argumentListsCompareByValueAndNullIsNothing() {
ok(sameArgs([], []), 'no arguments is no arguments');
ok(sameArgs(['--verbose'], ['--verbose']), 'the same flag is the same flag');
ok(!sameArgs([], ['--verbose']), 'and a different one is not');
ok(!sameArgs(null, []), 'nothing running is never what is wanted');
ok(!sameArgs(null, null), 'not even against another nothing — a failed start must retry');
}
async function main() {
// A test that awaits a promise nothing will settle would otherwise let node
// run out of work and exit 0 in silence — a hang that reads as a pass. This
// timer both fails it and keeps the event loop alive to say so.
const watchdog = setTimeout(
() => fail('timed out after 5s — a promise this test waits on never settled'),
5000,
);
argumentListsCompareByValueAndNullIsNothing();
await activationSpawnsOnceWithTheSettingsArguments();
await aToggleDuringTheActivationStartIsNotLost();
await aBurstOfTogglesCollapsesToOneRestartOnTheLastOne();
await aToggleBackToWhatIsRunningRestartsNothing();
await aFailedStartIsReportedAndTheChainStaysUsable();
await aStopThatRejectsDoesNotStopTheRestart();
await aToggleInTheSameTickAsDisposeSpawnsNothing();
await aReconcileQueuedBeforeDisposeBecomesANoOp();
await disposeResolvesAfterTheFinalStop();
await disposingBeforeAnythingSpawnedStopsNothing();
clearTimeout(watchdog);
console.log(`restart: OK — ${checks} checks over the restart chain`);
}
main().catch((error) => fail(error.stack || String(error)));
+29 -3
View File
@@ -41,9 +41,17 @@ function fail(message) {
process.exit(1);
}
// The same spawn contract extension.js uses: no arguments, inherited env, the
// workspace directory as cwd, LSP on stdin/stdout.
const server = spawn(serverPath, [], { cwd: process.cwd(), env: process.env, stdio: 'pipe' });
// The same spawn contract extension.js uses by default: no arguments,
// inherited env, the workspace directory as cwd, LSP on stdin/stdout. The one
// argument the extension can add — `--verbose`, when the user turns on
// `lucisv.verbose` — only adds log lines, and is driven by
// crates/lucisv_server/tests/e2e.rs; this check stays on the spawn everybody
// gets (docs/features/verbose-timing/README.md).
// `--stdio` is what `vscode-languageclient` really appends for
// TransportKind.stdio, so the smoke spawn matches the extension's actual
// spawn — the shape whose absence from this check let strict argument
// parsing ship a server no real VS Code session could start (2026-08-29).
const server = spawn(serverPath, ['--stdio'], { cwd: process.cwd(), env: process.env, stdio: 'pipe' });
server.on('error', (error) => fail(`could not spawn "${serverPath}": ${error.message}`));
const chunks = [];
@@ -90,6 +98,7 @@ server.stdin.end(
params: {
processId: process.pid,
rootUri: null,
initializationOptions: { hierarchyView: true },
capabilities: { textDocument: { rangeFormatting: { dynamicRegistration: true, rangesSupport: true } } },
},
}),
@@ -106,6 +115,9 @@ server.stdin.end(
params: { textDocument: { uri: brokenUri, languageId: 'systemverilog', version: 1, text: BROKEN } },
}),
frame({ jsonrpc: '2.0', id: 5, method: 'lucisv/scopePairs', params: { textDocument: { uri: brokenUri } } }),
// The custom sidebar snapshot. The opened source contributes one module;
// this catches a server/extension method-name or response-shape mismatch.
frame({ jsonrpc: '2.0', id: 8, method: 'lucisv/moduleHierarchy', params: {} }),
// Ghost text, just after the `begin` on line 2 of the buffer that lost its
// `end`. The extension only ever sends this after opting into
// `ProposedFeatures`, so an "unhandled method" here is the same kind of
@@ -174,6 +186,20 @@ server.on('close', (code) => {
if (!capabilities.documentHighlightProvider) fail('capability missing: documentHighlightProvider');
if (!capabilities.inlineCompletionProvider) fail('capability missing: inlineCompletionProvider');
const hierarchy = messages.find((m) => m.id === 8);
if (!hierarchy || hierarchy.error) fail(`hierarchy snapshot failed: ${JSON.stringify(hierarchy)}`);
if (!hierarchy.result || hierarchy.result.schemaVersion !== 2) fail('hierarchy snapshot has the wrong schema');
if (!Array.isArray(hierarchy.result.files)) fail('hierarchy snapshot has no file table');
const hierarchyNames = (hierarchy.result.modules || []).map((module) => module.moduleName);
if (!hierarchyNames.includes('top')) fail(`hierarchy snapshot missing top: ${JSON.stringify(hierarchyNames)}`);
// A location names its file by index and its ranges as four numbers — the
// narrow wire the sidebar's cost fix introduced.
const definition = (hierarchy.result.modules.find((m) => m.moduleName === 'top') || {}).definition;
if (!definition || typeof definition.file !== 'number'
|| !Array.isArray(definition.range) || definition.range.length !== 4) {
fail(`hierarchy definition is not the narrow shape: ${JSON.stringify(definition)}`);
}
const diagnostics = messages.find((m) => m.method === 'textDocument/publishDiagnostics');
if (!diagnostics) fail('the server pushed no diagnostics for the opened document');
+487
View File
@@ -0,0 +1,487 @@
# lucisv-server LSP performance against opentitan
Measured 2026-08-28 on the real opentitan checkout, driving the real server
binary over stdio with a scripted LSP client. Every number below is a
client-observed round trip on a monotonic clock (`time.perf_counter`), which is
what the editor — and therefore the user — actually experiences.
---
## 0. Read this first: the binary is **not** instrumented
The brief said the binary at
`…/scratchpad/lucisv-server-instrumented` emits
`window/logMessage` lines of the form `timing: <method> answered in X ms`.
**It does not.** Verified three ways:
- `strings -a` on the binary finds no `timing`, `answered`, `handled in`,
`elapsed`, `took`, or ` ms` literal anywhere.
- Over ~20 sessions the client received **zero** `window/logMessage`
notifications, despite `index.logFiles` defaulting to `true`.
- `shasum -a 256` shows the binary is **byte-identical** to
`/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server`
(`ce7e15db473e81f420a247ca463085c22262b28815d6edb8345da04ecadfe7cc`), i.e. it
is the ordinary release build, copied. `crates/lucisv_server/src/perf.rs` is
an `#[ignore]`d in-process test module, not protocol instrumentation.
I could not rebuild (the brief forbids running cargo in the repo, since another
agent is editing it concurrently). So **there is no server-side handling column
below.** In its place I measured a **transport baseline**: an unknown request
method (`$/lucisvNoSuchMethod`), which the server rejects without doing any
work. Its round trip is **0.02–0.33 ms** (median ≈ 0.05 ms across all sessions).
Everything above ~0.5 ms is therefore server work, not framing, and for an
isolated request `client round trip ≈ server handling + 0.05 ms`. The one thing
the missing instrumentation costs us is a breakdown *inside* a slow request; the
queue-blocking numbers in §3 are client-observable by construction and are
unaffected.
---
## 1. Environment and provenance
| | |
|---|---|
| Machine | Apple M1 Max, 10 cores, 64 GB RAM |
| OS | macOS 27.0 (build 26A5421a) |
| Date | 2026-08-28, ~21:50–22:15 local |
| Binary | `lucisv-server` 0.14.0, Mach-O arm64, 4,120,288 bytes, sha256 `ce7e15db…dfe7cc` |
| Repo HEAD | `bf9170a` — *"A scope widen indexes the folders it added, not everything again"* |
| Working tree at build time | **dirty**: `lucisv_server/{ports,state}.rs`, `vlog_refactor/{lib,ports}.rs` modified 21:43:09–21:43:29; binary linked 21:47:27. **The in-progress `code_actions` fan-out fix (`ws.module_sources()` replacing `ws.sources()`) is therefore compiled into this binary.** `ports.rs` was touched again at 21:55 (tests) — after the build. |
| Corpus | `/Users/guoliangchen/repo/opentitan` @ `0098135264` — 3979 `.sv`/`.svh`/`.v` files; the server indexes **3976, skips 3** |
| Scenario file | `hw/ip/aes/dv/tb/tb.sv` (100 lines); module `aes` instantiated at line 45 (0-based 44, col 2); `.clk_i` port connection at line 50; `aes` defined at `hw/ip/aes/rtl/aes.sv:9` |
| Client | `scratchpad/perf/lspclient.py` + `bench.py` / `bench2.py` / `bench3.py` / `typing.py` |
**Cache state is controlled per run** via
`workspace/configuration` → `{"index":{"scope":…,"cachePath":"<temp dir>"}}`.
"Cold" = the cache directory was `rm -rf`'d immediately before. "Warm" = the
directory carries a previous session's store (23 MB for the full workspace).
---
## 2. Summary table — worst first
Workspace scope, warm cache, unless the row says otherwise. "Repeats" is the
range over the 2nd–4th (or 2nd–6th) identical request in the same session.
| Action | First try | Repeats | Verdict |
|---|---:|---:|---|
| `textDocument/rename` on `aes` (edits computed, not applied) | **6 355 ms** | 3 601 – 8 659 ms | **very slow** |
| — anything queued behind that rename (definition / hover / documentSymbol) | **5 079 ms** | — | **very slow** |
| `textDocument/prepareRename` on `aes` (**this is just pressing F2**) | **2 999 ms** | 1 723 – 2 597 ms | **very slow** |
| — anything queued behind that prepareRename | **2 501 ms** | — | **very slow** |
| Workspace scan, **cold** cache (didOpen → 3976 files indexed) | **3 003 ms** | — | acceptable (once) |
| Workspace scan, **warm** cache (3975 of 3976 from cache) | **1 551 ms** | 1 548 – 1 580 ms | acceptable |
| `textDocument/completion` at 1 typed character (512 candidates) | **61 ms** | 34 – 66 ms | **slow** (fires per keystroke) |
| `textDocument/codeAction` **on the `aes` instantiation** | **60 ms** | 46 – 49 ms | **slow** (fires per cursor move) |
| — definition pipelined behind that codeAction | **53 ms** | 47 – 58 ms | **slow** |
| definition immediately after a widening `didOpen` (`spi_device.sv`) | **88 ms** | 88 ms (2nd session) | slow-ish |
| definition immediately after a widening `didOpen` (`aes.sv`) | **48 ms** | 49 ms (2nd session) | acceptable |
| definition immediately after a widening `didOpen` (`kmac`, `hmac`) | 38 / 27 ms | 34 / 24 ms | acceptable |
| Typing 11 characters (`aes_reg_top`), completion each keystroke | **201 ms total** | — | 18 ms/keystroke avg |
| `workspace/symbol "aes"` (256 results) | 6.7 ms | 5.9 – 6.5 ms | fine |
| `textDocument/completion` at ≥5 typed characters | 5.3 ms | 4.0 – 5.0 ms | fine |
| `initialize` → response | 2.0 – 8.0 ms | — | fast |
| `textDocument/hover` on `aes` | 1.35 ms | 0.07 – 0.16 ms | fast |
| `textDocument/codeAction` on a **comment line** (contrast) | 0.93 ms | 0.50 – 0.91 ms | fast |
| `didChange` flush (measured with a `foldingRange` barrier) | 0.75 ms | 0.25 – 0.32 ms | fast |
| `textDocument/references` on `aes` (7 hits, incl. declaration) | 0.61 ms | 0.39 – 0.72 ms | fast |
| `textDocument/signatureHelp` inside the port list | 0.61 ms | 0.48 – 0.53 ms | fast |
| `textDocument/definition` on `aes` | 0.49 ms | 0.11 – 0.18 ms | fast |
| `textDocument/references` on `.clk_i` (10 hits) | 0.48 ms | 0.36 – 0.44 ms | fast |
| `textDocument/inlayHint` (whole 100-line file) | 0.36 ms | 0.21 – 0.25 ms | fast |
| `textDocument/documentSymbol` | 0.13 ms | 0.13 – 0.21 ms | fast |
| `textDocument/semanticTokens/full` | 0.16 ms | 0.12 – 0.13 ms | fast |
| `textDocument/typeDefinition` on `aes` | 0.15 ms | 0.09 – 0.10 ms | fast |
| `textDocument/diagnostic` (pull) | 0.13 ms | 0.04 – 0.07 ms | fast |
| `textDocument/selectionRange` at the instantiation | 0.12 ms | 0.08 – 0.09 ms | fast |
| `textDocument/documentHighlight` (see §7 — returns nothing) | 0.09 ms | 0.03 – 0.12 ms | fast |
| `textDocument/codeLens` | 0.10 ms | 0.03 – 0.07 ms | fast |
| `textDocument/documentLink` | 0.09 ms | 0.05 – 0.08 ms | fast |
| `textDocument/foldingRange` | 0.03 ms | 0.05 – 0.07 ms | fast |
| `textDocument/definition` / `hover` on `.clk_i` | 0.05 ms | 0.03 – 0.07 ms | fast |
| *transport baseline (unknown method — does no work)* | *0.02 – 0.33 ms* | — | *floor* |
`textDocument/implementation` is **not advertised** by this server
(`implementationProvider` absent from the `initialize` result) and was not
measured. Advertised and measured: `typeDefinition`, `typeHierarchy`,
`callHierarchy`, `diagnostic` (pull, with `workspaceDiagnostics: true`),
`inlineCompletion`, `linkedEditingRange`, `documentOnTypeFormatting`,
`willSaveWaitUntil`.
---
## 3. The queue-blocking analysis — this is the owner's pain
The server runs a **single-threaded request loop**: one message is taken off
stdin, answered to completion, and only then is the next one read. Nothing is
cancelled, nothing is answered out of order, nothing runs on a worker. So the
latency a user feels for request *R* is not *R*'s own cost — it is *R*'s cost
**plus the un-finished cost of everything the editor already sent**.
I measured this directly. Each slow request was sent, and then — with no wait,
same TCP-less pipe, back to back — three requests a real editor fires on every
cursor move. All four were timed from the same `t0`:
| Sent first (the blocker) | Its own cost | `definition` behind it | `hover` behind it | `documentSymbol` behind it |
|---|---:|---:|---:|---:|
| `codeAction` on the `aes` token | 60.0 ms | **60.0 ms** | 60.1 ms | 60.3 ms |
| `prepareRename` on `aes` | 2 500.7 ms | **2 500.7 ms** | 2 500.9 ms | 2 501.0 ms |
| `rename` on `aes` | 5 079.1 ms | **5 079.1 ms** | 5 079.2 ms | 5 079.3 ms |
| `workspace/symbol "aes"` | 9.7 ms | **9.7 ms** | 9.7 ms | 9.8 ms |
The same three requests, sent alone into an idle server in the same session,
cost **0.11 ms**, **0.07 ms** and **0.13 ms**.
Read the amplification:
- **definition behind `codeAction`: 52.7 ms first try (47.4–58.2 ms repeats) vs
0.11 ms alone — ~480×.** This is the one the brief asked for by name. The
dedicated pipelined test (`codeAction` then `definition`, neither waited on)
gave 52.65 / 58.13 / 47.36 ms for the codeAction and 52.72 / 58.18 / 47.38 ms
for the definition riding behind it — the definition's answer lands **0.02–0.05
ms** after the codeAction's, i.e. the queue is strictly serial and the
follower pays the leader's bill almost exactly.
- **definition behind `prepareRename`: 2 500.7 ms vs 0.11 ms — ~22 000×.**
- **definition behind `rename`: 5 079.1 ms vs 0.11 ms — ~46 000×.**
Why this matters in an editor rather than in a benchmark: VS Code does not send
one request at a time. Moving the cursor emits `codeAction` +
`documentHighlight` + `inlayHint` + `codeLens`; typing emits `didChange` +
`completion` + `signatureHelp` + `diagnostic`. Every one of those lands behind
whatever is currently executing. So a 3-second `prepareRename` is not a
3-second F2 — it is a **3-second freeze of hover, go-to-definition, highlight,
and the completion popup**, and any keystroke typed during it is not even
*parsed* until it ends.
Two structural consequences worth stating plainly:
1. **The absolute number matters more than the ratio.** `workspace/symbol`
amplifies a follower by ~90× too, but 9.7 ms is invisible. The threshold is
roughly the frame budget: anything under ~16 ms is free, 16–100 ms is
noticeable on a cursor move, and anything over ~200 ms reads as a hang.
2. **`codeAction` and `completion` are the only slow requests on the hot path.**
`rename`/`prepareRename` are user-initiated; `codeAction` fires whether or
not the user wants a lightbulb, and `completion` fires on every character.
---
## 4. Startup and scan, per scope and cache state
`didOpen tb.sv` → the last `$/progress` `end`, followed by 1.5 s of silence.
(Naïvely waiting for the *first* `end` is wrong: the server raises **three**
progress bars in a row — a 0-file one, a 1-file one for the opened buffer, and
only then the real workspace scan under token `lucisv-index-2`. My first pass
made exactly this mistake and reported a 102 ms workspace scan.)
| Scope | Cache | didOpen → settled | Files indexed |
|---|---|---:|---|
| `folder` (**the default**) | cold | **102.2 ms** | **1** |
| `folder` (default) | warm | **101.1 ms** | **1** |
| `workspace` | cold | **3 003.2 ms** | 3976 indexed, 3 skipped |
| `workspace` | warm | **1 551 / 1 560 / 1 568 / 1 573 / 1 580 ms** | 3976, **3975 from cache**, 3 skipped |
- `initialize` itself is 2.0–8.0 ms and does no scanning; the scan is kicked off
by the first `didOpen`.
- The real scan begins ~300 ms after `didOpen` (the two trivial bars occupy the
first ~105 ms), so cold wall-clock from didOpen to a usable workspace index is
~3.0 s and warm is ~1.6 s.
- **Persistence buys ~1.45 s (48%)** on this corpus. The store is 23 MB.
- Once the bar ends the index is genuinely ready: `definition` answers correctly
at 0.16–0.25 ms immediately, and is no better after a further 1 s idle. There
is no post-bar background settling to wait for.
- Three runs (`rename-workspace` 2 741 ms, `blockers` 3 004 ms, `renamegrow`
2 987 ms) showed warm scans at cold-scan cost while still reporting "3975 from
cache". Five clean back-to-back runs afterwards were all 1 551–1 580 ms. I
attribute the outliers to CPU contention (another agent was building this repo
on the same machine during the session), not to a cache miss — but it is not
proven, and if warm scans are intermittently 2× it is worth a look.
**The default scope is the headline startup finding, and it is not a
performance finding.** `IndexScope::Folder` with `scopeDepth: 0`
(`crates/lucisv_server/src/settings.rs`) walks only the open file's own
directory. `hw/ip/aes/dv/tb/` contains exactly one file. So on the shipped
default, opening `tb.sv` gives an index of **1 file**, and:
| Request at the `aes` instantiation | folder scope (default) | workspace scope |
|---|---|---|
| `definition` | **0 results**, 0.05 ms | 1 result, 0.49 ms |
| `typeDefinition` | **0 results** | 1 result |
| `hover` | **0 results** | 1 result (module signature) |
| `references` | **0 results** | 7 results |
| `workspace/symbol "aes"` | **0 results** | 256 results |
| `completion` at a fresh line | **8 items** | 483 items |
| `signatureHelp` in the port list | **0 results** | 1 signature |
Folder scope's uniformly sub-0.1 ms timings are therefore not a speed result —
**they are the cost of answering nothing.** Any comparison of folder vs
workspace latency that ignores this is meaningless.
---
## 5. The `didOpen` widen (item 7) — the fix holds
Folder scope, `tb.sv` open, then RTL files opened one at a time. Each open
widens the scope to a new folder, which the server indexes; the request sent
immediately afterwards waits for that work. Measured on both a cold and a warm
cache directory:
| Widening `didOpen` | definition behind it (cold cache) | (warm cache) |
|---|---:|---:|
| `hw/ip/aes/rtl/aes.sv` | 48.4 ms | 49.3 ms |
| `hw/ip/kmac/rtl/kmac.sv` | 37.7 ms | 34.1 ms |
| `hw/ip/hmac/rtl/hmac.sv` | 27.0 ms | 23.9 ms |
| `hw/ip/spi_device/rtl/spi_device.sv` | **87.7 ms** | **88.3 ms** |
**Verified: this is the post-fix regime.** The brief records 120–169 ms before
`bf9170a` and 12–44 ms after; three of the four jumps land in 24–49 ms.
`spi_device` at ~88 ms is above the quoted band, which is expected rather than
alarming — `hw/ip/spi_device/rtl/` is a much larger directory than the others,
and the widen now indexes *the folders it added*, so its cost scales with the
folder actually opened. Worth recording as the current ceiling for a single
jump.
The cache makes almost no difference here (48.4 vs 49.3 ms), which makes sense:
the widen's cost is walking and parsing a directory the store has entries for
only if a previous session in the *same* cache dir already widened into it.
After the widen, and after the index settles, everything is fast again
(`definition` 0.18/0.04/0.03 ms).
**But the widen changes the cost of the slow requests too**, because `sources()`
now returns more files. Folder scope, after opening only `aes.sv`:
| | before widen | after widen | workspace scope |
|---|---:|---:|---:|
| `codeAction` on the instantiation | 1.8 ms | 4.5 ms | 60 ms |
| `prepareRename` | — (0 results) | **27.0 ms** | **2 999 ms** |
| `rename` | — | **93.8 ms** | **6 355 ms** |
| `workspace/symbol "aes"` | 0.04 ms (0 results) | 3.7 ms (256) | 6.7 ms (256) |
This is the clearest statement of the root cause: **the slow requests cost
`O(files in scope)`.** 2 files → 27 ms. ~200 files → 94 ms. 3976 files →
3 000 ms.
---
## 6. Root causes
### 6a. `codeAction` — already fixed in this binary, still 60 ms
The brief predicted ~3 s on the instantiation and asked me to verify. **It is
46–60 ms, not 3 s**, because the fix described as "in progress this session" is
compiled into the binary I was given (sources modified 21:43, binary linked
21:47). The diff replaces
```rust
let sources = ws.sources(); // every in-scope file
```
with
```rust
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
if modules.is_empty() { return Vec::new(); }
let sources = ws.module_sources(&path, &modules); // that module's fan-out
```
in `crates/lucisv_server/src/ports.rs::code_actions`, plus a `sources_at()`
helper doing the same for the `addPort` / `removePort` / `propagatePorts`
commands.
That the contrast case is 0.5–0.9 ms (comment line, `port_action_modules`
returns empty and the function bails before touching the workspace) while the
instantiation case is 46–60 ms shows the early-out works and the residue is the
fan-out read itself: `aes` is instantiated ~6 times workspace-wide, so
`module_sources` still reads and parses those files on **every cursor move onto
the instantiation**. 60 ms per cursor move is still four frames, and §3 shows it
is charged to whatever the editor sent next.
*Suggested follow-up (not implemented — out of scope for this measurement
task):* memoize `module_sources` per (module, index generation), or answer
`codeAction` from the index rather than from re-read source text.
### 6b. `prepareRename` — 2.5–3.0 s, and it is **not** "user-initiated-rare"
`crates/lucisv_server/src/rename.rs:30`:
```rust
let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?;
```
`ws.sources()` reads and returns **every file in scope** — 3976 files at
workspace scope. `prepareRename` is a **read-only** request whose entire job is
to answer "is this token renameable, and what range/placeholder?". It returns
`{"placeholder": "aes", "range": {line 44, chars 2–5}}` — information available
from the open buffer alone. It does not need the workspace.
**I want to push back on the brief's framing here.** The brief labels the rename
machinery "user-initiated-rare" and expected slowness to be acceptable.
`prepareRename` is not rare and it is not what the user thinks of as "doing a
rename" — it is what fires the instant F2 is pressed, *before* the rename box
even appears. 2.5–3.0 s of a wholly frozen server, on a keypress that has not
yet committed to anything, is the second-worst result in this report and by §3
it takes hover, definition and highlight down with it. I'd rate it **the most
fixable serious problem here**, and more urgent than `codeAction`: the fix is
narrower (answer the range from the buffer; only consult the workspace if the
token turns out to be a cross-file symbol) and the payoff is larger.
### 6c. `rename` — 3.6–8.7 s, genuinely rare, genuinely expensive
`rename.rs:47` has the same `ws.sources()` call and then computes edits across
the workspace (7 files edited for `aes`). 3.6–8.7 s is bad but this one really
is a deliberate, infrequent, "I asked for a big thing" action, and it produces a
correct workspace-wide edit set. Acceptable *if* it reported progress and were
cancellable, which it currently is not (`workDoneProgress` is not raised for it,
and the single-threaded loop cannot service `$/cancelRequest` while busy).
**Correction to an earlier reading:** my first rename run showed 6 355 → 7 486 →
8 659 ms and looked like monotonic growth (a leak). A dedicated 6-repeat re-run
showed 5 357 → 5 347 → 4 829 → 4 458 → 3 992 → 3 601 ms — *decreasing*. There is
no growth; the spread is machine noise (see §8). Range across all runs:
**3 601–8 659 ms**, which is itself a 2.4× spread and a sign of how much this
path is at the mercy of I/O and CPU contention.
### 6d. `completion` — 34–66 ms per keystroke, and it is a NEW finding
**Flagging this loudly: this was not in the brief's list of known-slow items,
and on the hot path it is worse than `codeAction`.**
Completion cost tracks the number of candidates *before* the 512-item
truncation, i.e. it is worst exactly when the user has typed the fewest
characters — the beginning of every identifier:
| Typed prefix | Items returned | Round trip |
|---|---:|---:|
| `` (empty) | 512 | **63–66 ms** |
| `a` | 512 | **58–61 ms** |
| `ae` | 483 | 35–36 ms |
| `aes` | 482 | 34–37 ms |
| `aes_` | 476 | 35 ms |
| `prim_` | 339 | 16–19 ms |
| `clk` | 512 | 5.7–6.0 ms |
| `aes_reg` | 20 | 5.0 ms |
| `zzzz` | 1 | 1.4–2.0 ms |
Typing the identifier `aes_reg_top` one character at a time, with a completion
request per keystroke (what VS Code's 24×7 IntelliSense does) and a `hover`
racing behind each one:
```
keystroke 1 'a' completion 61.44 ms hover-behind-it 61.46 ms (512 items)
keystroke 2 'ae' completion 36.13 ms hover-behind-it 36.15 ms (483 items)
keystroke 3 'aes' completion 35.36 ms hover-behind-it 35.39 ms (482 items)
keystroke 4 'aes_' completion 34.92 ms hover-behind-it 34.94 ms (476 items)
keystroke 5 'aes_r' completion 5.34 ms hover-behind-it 5.35 ms ( 35 items)
…
keystroke 11 'aes_reg_top' completion 4.27 ms hover-behind-it 4.27 ms ( 1 items)
→ 11 characters cost 200.9 ms of server time (18.3 ms/keystroke average)
```
Note `clk` → 512 items in 6 ms versus `` → 512 items in 64 ms: the returned
count is capped at 512 either way, so the cost is **not** in building or
serialising the result. It is in scanning/filtering the candidate set, and the
broader the prefix the more of the 3976-file symbol table is walked. A prefix
index (or an early bail once 512 matches are found, if the ordering permits)
would flatten this.
The `didChange` half of a keystroke is **not** the problem: measured alone with
a `foldingRange` barrier it is **0.25–0.75 ms**, and a burst of 10 `didChange`
notifications followed by one completion cost 2.88 ms total. The flush is
cheap; the completion is not.
### 6e. `file_ops.rs:120` — same pattern, unmeasured
`for (path, text) in ws.sources()` in
`crates/lucisv_server/src/file_ops.rs:120` serves `workspace/willRenameFiles`.
The server advertises `willRename` with a `**` folder filter, so **renaming any
folder in the VS Code explorer** will pay the same full-workspace read. Not
measured (it needs a file-system mutation, and the brief forbids touching the
opentitan checkout), but it is the same `ws.sources()` shape as §6b/§6c and
should be on the same follow-up list.
---
## 7. Non-performance findings worth surfacing
- **`textDocument/documentHighlight` returns 0 results at every position
tested** — on the `aes` instantiation and on the `.clk_i` port connection, at
both folder and workspace scope, before and after the widen, even though
`documentHighlightProvider: true` is advertised and `references` at the same
positions returns 7 and 10 hits respectively. It is fast (0.03–0.12 ms)
because it is doing nothing. This looks like a functional bug, not a perf
issue, but a fast wrong answer will read as "fast" in any benchmark that only
times it.
- **`inlayHint` over the whole file returns 4 hints at workspace scope and 0 at
folder scope**, and `codeLens` reports `"no instantiations"` for `tb` (correct
— nothing instantiates the testbench).
- **A cold workspace scan emits ~994 `$/progress` report notifications** (one
per 4 files). Harmless for a real editor, but it saturated my first
measurement client and made a 3-second scan look like a 70-second one. Worth
knowing before anyone else measures this.
- `index.logFiles` defaults to `true` but **no `window/logMessage` was ever
received** in any session. Either the default is not being honoured or the log
is gated on something the pulled configuration did not supply.
---
## 8. Methodology and caveats — read before quoting any number
- **No server-side timing.** See §0. Every number is a client round trip. The
transport floor is 0.02–0.33 ms, so for isolated requests the two are within
noise of each other, but a slow request's *internal* breakdown is not
available and nothing in this document should be read as one.
- **One machine, one corpus, one afternoon.** M1 Max / 64 GB is a fast laptop.
A 3 s cold scan here could be 10 s on a 4-core machine with a slower disk.
- **Page cache is hot.** opentitan had been walked repeatedly by earlier
sessions before I started; "cold cache" above means *lucisv's* index store was
deleted, **not** that the OS file cache was dropped. A genuinely cold-boot
first scan will be slower than the 3 003 ms reported.
- **The machine was not quiet.** Another agent was editing and building this
repo concurrently, by design of the task. This is the most likely explanation
for the three anomalous 2.7–3.0 s "warm" scans in §4 and for the 2.4× spread
in `rename`. The sub-millisecond results are unaffected (they were stable to
±0.05 ms across ~20 sessions); the multi-hundred-millisecond ones should be
read as ±30%.
- **Repeats share a warm process.** Each "repeats" range is the 2nd–4th
identical request in the same session, so it reflects whatever the server
memoised on the first. Where that matters (`codeAction`, `rename`) I ran the
request as the **first** request of a dedicated session to get a genuinely
cold first try; that is what the "first try" column reports.
- **`rename` was measured but never applied.** `textDocument/rename` returns a
`WorkspaceEdit`; the client discarded it. The opentitan checkout is unmodified
(verified: no writes, only `didOpen` of existing files).
- **Instrumentation overhead is nil** — there is none to have. Client overhead
(JSON encode/decode, framing) is inside the 0.05 ms transport baseline.
- **Positions were resolved from the file text at run time**, not hard-coded, so
the numbers stay attached to the `aes` instantiation and the `.clk_i` port
connection even if the file shifts.
- **`tb.sv` carries one pre-existing local edit** — a trailing space on line 44,
`git diff` against `0098135264`, mtime 20:39, an hour before this session
began and not made by this measurement. It is why `textDocument/diagnostic`
returns a `no-trailing-whitespace` item. Nothing in the checkout was written
by these runs.
---
## 9. Raw logs
All under
`/private/tmp/claude-501/-Users-guoliangchen-repo-verilogrustformatter/7b09ba01-f222-4ace-bf9a-b321331bf159/scratchpad/perf/`:
| File | What |
|---|---|
| `lspclient.py` | the LSP client (framing, config/progress replies, timing helpers) |
| `bench.py` | phases `startup` / `nav` / `codeaction` / `rename` / `widen` |
| `bench2.py` | phases `blockers` (§3) / `renamegrow` (§6c) / `keystroke` (§6d) |
| `bench3.py` | `realfolder` (§5 post-widen table) / `completion` (§6d table) |
| `typing.py` | the per-keystroke typing simulation (§6d) |
| `results.jsonl` | every measurement, machine-readable |
| `logs/startup-{folder,workspace}-{cold,warm*}.log` | §4 |
| `logs/nav-{workspace,folder}.log` | §2 whole-document and cursor batteries |
| `logs/codeaction-{workspace,folder}.log` | §6a and the pipelined test |
| `logs/rename-workspace.log`, `logs/renamegrow.log` | §6b, §6c |
| `logs/blockers-workspace.log` | §3 queue-blocking table |
| `logs/widen-folder-{cold,warm}.log`, `logs/realfolder.log` | §5 |
| `logs/completion.log`, `logs/keystroke.log`, `logs/typing.log` | §6d |
| `logs/progress-ws-cold.log` | the multi-bar progress trace behind §4's note |
| `caps.txt` | full `initialize` result (advertised capabilities) |
+8 -4
View File
@@ -180,10 +180,14 @@ npx @vscode/vsce package --target darwin-arm64 \
a packaging regression — it reproduces with a two-file toy extension. The fix
is to package from a plain path, which is why `release.sh` packages inside the
repo and only writes its *output* to `-o`.
- `.vscodeignore` keeps `smoke.js`, `.vscode/**` and `.gitignore` out of the
package. It must **not** exclude `bin/`, which is where the platform packages'
binaries are staged. Check that after any change to it:
`unzip -l dist/lucisv-<version>.vsix | grep smoke` must print nothing, and
- `.vscodeignore` keeps `smoke.js`, `restart_test.js`, `.vscode/**` and
`.gitignore` out of the package. It must **not** exclude `bin/`, which is
where the platform packages' binaries are staged — nor `restart.js`, which
`extension.js` requires at runtime (an extension that ships without it fails
to activate). Check that after any change to it:
`unzip -l dist/lucisv-<version>.vsix | grep -E 'smoke|restart_test'` must
print nothing, `unzip -l dist/lucisv-<version>.vsix | grep restart.js` must
print `extension/restart.js`, and
`unzip -l dist/lucisv-<version>.vsix | grep syntaxes` must print the grammar —
without it, hover cards ship unhighlighted.
- **`editors/vscode/bin/` is transient.** `release.sh` stages one platform's
+69 -30
View File
@@ -11,7 +11,10 @@ each crate's `Cargo.toml`, each feature's `docs/features/<name>/README.md`
(the **Handshakes** section in particular), `README.md` and `CLAUDE.md`.
Drafted 2026-08-27 from the workspace at v0.10.2 (93 feature READMEs);
updated 2026-08-28 for hover-declarations, change-debounce,
port-detail-spans and interactive-latency (97 feature READMEs).
port-detail-spans and interactive-latency (97 feature READMEs); updated
2026-08-29 from v0.14.0 for hover-line-index, scan-interleave, incremental
scope widening, the request-fan-out performance wave and verbose-timing
(100 feature READMEs).
**Edge notation, used in all three sections:**
@@ -97,17 +100,19 @@ what a change on the pointed-to side must not silently break.
| `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache). (`walk::is_excluded` is `pub` but currently has no consumer outside the crate.) |
| `lucisv ──▶ vlog_formatter` | depends | `format_source` / `format_range` / `LineRanges` / `Config` / `FormatError`, and `fence::{protected_regions, is_protected}` (the `--fix` fence filter — the linter crate deliberately has no fence notion). |
| `lucisv ──▶ vlog_linter` | depends | The public linter API for `lucisv check` — `lint` + `LintContext`/`ParsedSource`, `apply_fixes`, `select_rules` (the CLI does not call `run` itself). Relies on: rule names stable, linting never panics/writes, findings sorted by `(span.start, span.end, rule)`. |
| `lucisv ──▶ vlog_parser` | depends | Thin: `LineIndex` / `TextRange` for lint report coordinates. (The CLI otherwise reaches the parser through the formatter and linter.) |
| `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(8 MiB)` (recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. |
| `lucisv ──▶ vlog_parser` | depends | `LineIndex` / `TextRange` for lint report coordinates, plus `PARSE_STACK_SIZE` for both the named `lucisv` thread and rayon workers. (The CLI otherwise reaches the parser through the formatter and linter.) |
| `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(vlog_parser::PARSE_STACK_SIZE)` (currently 16 MiB; recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. |
| `lucisv_server ──▶ lucisv_core` | depends | Same config discovery and walk as the CLI (that sameness is the point — format-on-save must agree with `lucisv --check`), `filelist::read` (index scope rung 1, `+incdir+` for the include graph), `cache::content_hash` (re-used by the persistent index cache — one FNV-1a, not two). |
| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the VS Code grammar is generated from). |
| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the VS Code grammar is generated from), and `PARSE_STACK_SIZE` for the named `lucisv-main` thread. |
| `lucisv_server ──▶ vlog_semantic` | depends | `analyze`/`Semantics` (every navigation answer), `WorkspaceIndex` (build/incremental update, units/members/defines, `instantiations_of`/`subclasses_of` edge tables, `FileFacts` codec for the persistent cache), `resolve_external` overlay, `index_order`/`IndexBuilder` (watched builds). |
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Two negotiated additions, both 2026-08-28 and both additive: **`Symbol::detail_span` / `Def::detail_span`** (where a non-ANSI port's body declaration completes the header that names it — the server's hover card and `nav::definition` both read it, and they show/jump to it in the same order), and **`Semantics::symbols_named`** (name → declarations, built in `analyze`, in declaration order — the server replaced two scan-every-symbol loops with it and the *first-match tie-break must stay declaration order* or hover's choice between two live declarations of one name changes). `docs/features/port-detail-spans/README.md`. |
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Three later additive performance surfaces: **`DeclLines` / `Def::lines`** record declaration and detail lines at index time (`FACTS_FORMAT` 3 → 4); **`WorkspaceIndex::absorb`** folds a scan batch with one merge rather than one merge per file; and **`WorkspaceIndex::files_spelling`** finds external uses by spelling, resolved or not, for rename's dangling-use refusal. The first feeds hover-line-index, the second scan-interleave, and the third refactor-rename's six-rung fan-out. Changing the facts codec, reference-fact census or merge semantics breaks those consumers. |
| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `instantiation_plan`/`render_with`/`module_definition` (completion skeletons, signature help, inlay hints). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. |
| `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names only to choose an index-derived superset of files; the engine remains the authority. |
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
| `editors/vscode ◀──▶ lucisv_server` | handshake | The **spawn contract**: binary named `lucisv-server`, no args, no env, LSP over stdio, `initialize` works with no roots (single-file mode). Wire shapes pinned on both sides: the custom `lucisv/scopePairs` result, the `lucisv.*` settings section (push and pull), `initializationOptions.storagePath`, the markdown fence tag `systemverilog` (server emits it, extension's grammar registers it), the `bin/` layouts of the platform `.vsix` packages. `smoke.js` drives the contract headlessly; `tests/e2e.rs` and `tests/grammar.rs` pin it server-side. |
| `editors/vscode ◀──▶ lucisv_server` | handshake | The **spawn contract**: binary named `lucisv-server`, no env, LSP over stdio, `initialize` works with no roots (single-file mode). The extension passes exactly `[]` by default or `['--verbose']` when `lucisv.verbose` is true; the server accepts only that spelling (repeats are idempotent) and refuses any other argument with exit 2. Changing that setting restarts the server because it is a process argument, not an LSP setting. Wire shapes pinned on both sides: the custom `lucisv/scopePairs` result, the other `lucisv.*` settings section (push and pull), `initializationOptions.storagePath`, the markdown fence tag `systemverilog` (server emits it, extension's grammar registers it), the `bin/` layouts of the platform `.vsix` packages. `smoke.js` still drives the default no-argument contract headlessly; `tests/e2e.rs` pins both spawns and `tests/grammar.rs` pins the grammar. |
| `editors/vscode ◀──▶ vlog_parser` | handshake | The TextMate grammar's keyword alternation is **hand-maintained and test-locked to `vlog_parser::KEYWORDS`**: `crates/lucisv_server/tests/grammar.rs` fails, naming the missing/extra words, when they diverge (there is no generator script). Adding a keyword to `token.rs`'s `keywords!` macro is therefore also a hand edit to `editors/vscode/syntaxes/systemverilog.tmLanguage.json`. |
| `editors/nvim ──▶ lucisv_server` | depends | Documentation-only module: config snippets consuming the same spawn contract and settings shape. No code. |
| `tools/ ◀──▶ crates + editors/vscode` | handshake | `release.sh` parses `lucisv --version` (field 2), runs `smoke.js` against the built server, stages `dist/lucisv[-server]-<version>-<triple>` names, packages seven `.vsix` files and asserts their `bin/` layouts. `audit_artifacts.sh` and `prune_release_assets.sh` key on those exact names. The version number lives in exactly four files (two `Cargo` files, two `package*.json`) and nowhere in Rust source. |
@@ -147,7 +152,10 @@ grammar, depth/chain budgets from recursion-limit) → `ast.rs`; `span.rs`
(`TextRange`), `line_index.rs` (offset↔line:col), `defines.rs` (the
`` `define`` table, reads the token stream, expands nothing). `tests/spans.rs`
is an exhaustive AST walker: **every new node needs an arm there** and must
keep the span-nesting invariant.
keep the span-nesting invariant. `PARSE_STACK_SIZE` is part of the public
parser contract: every production thread that can reach parse or analysis must
use it; the CLI main thread, rayon pool and server main thread do so, while the
server queue and `lsp-server` I/O threads are proven not to parse.
**`vlog_formatter`** — the pipeline is `format.rs` (per-node rules) →
`doc.rs` (the Wadler IR) → `printer.rs` (width-aware printing);
@@ -164,7 +172,9 @@ an error means emit nothing.
`DataType`; shrinks to zero when open handshake §2.9-2 lands);
`workspace.rs` (`WorkspaceIndex`: units, members, defines, instantiation and
inheritance edge tables, incremental `update_file`/`remove_file`,
`fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache);
reference postings, `files_spelling`, batch `absorb`, declaration `DeclLines`,
`fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache;
`FACTS_FORMAT` is 4);
`instantiations.rs`, `classes.rs` (the shared walks, lifted from the server
so the index census and the request handlers cannot drift).
@@ -185,10 +195,13 @@ table for the three semantic rules), `naming.rs`, `rule_docs.rs`
(`rules_markdown()` — docs generated from the registry).
**`vlog_refactor`** — `rename.rs` (the `Scope` cache + occurrence walk —
also the engine of `references.rs::find_references`), `ports.rs`
(add/remove/propagate), `instantiate.rs` (plans + rendering; the one layout
both plain and snippet spellings go through), `check.rs` (whole-edit
verification: re-tokenize + re-resolve, refuse everything on any drift).
also the engine of `references.rs::find_references`; publishes the cheap
`prepare_rename_here`/`rename_name_at` selectors whose parity with the full
engine is test-pinned), `ports.rs` (add/remove/propagate plus
`port_action_modules`/`enclosing_module`, the names the server uses to bound
the input set), `instantiate.rs` (plans + rendering; the one layout both plain
and snippet spellings go through), `check.rs` (whole-edit verification:
re-tokenize + re-resolve, refuse everything on any drift).
**`lucisv` (CLI)** — `main.rs` (args → walk → per-file worker pool;
`process_file` is the cache-aware unit of work; panic hook installed once at
@@ -203,25 +216,28 @@ spans two layers — the include graph *and* the `documentLink` handler;
| layer | files | role |
|---|---|---|
| entry | `main.rs` | capabilities advertisement, `InitializeParams` reading, wiring |
| loop | `server.rs` | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, reindex orchestration, progress/log senders |
| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay) and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word tables, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync |
| entry | `main.rs` | the no-argument / `--verbose`-only argument contract, capabilities advertisement, `InitializeParams` reading, wiring |
| loop | `server.rs` | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, stepped startup scans with mid-scan request drains, held-request ordering for rescans, reindex/widen orchestration, progress/log senders, optional `timing:` instrumentation |
| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay, bounded closed-file `FileView` cache), `Scan` (whole or additive widen), fan-out source selectors (`module_sources`, `rename_sources`, `include_sources`), and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word/module tables and their scan-batch forms, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync |
| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs`, `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion.rs`, `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) |
**`editors/vscode`** — `extension.js` (spawn + rainbow decorations + storage
path; ~everything else is `vscode-languageclient` driven off advertised
capabilities), `package.json` (languages, grammar, snippets, settings,
colour ids), `syntaxes/` (hand-maintained grammar, test-locked to
`KEYWORDS`), `snippets/` (static, server-independent), `smoke.js` (headless
handshake check), `README.md` (the Marketplace Details page, owned by
editor-marketplace-page).
`KEYWORDS`), `snippets/` (static, server-independent), `restart.js` (the one
serialized start/restart chain, so a `lucisv.verbose` toggle cannot be lost to
an in-flight start — shipped, and the only module `extension.js` requires),
`smoke.js` (headless handshake check) and `restart_test.js` (headless check of
that chain, against a scripted fake client), `README.md` (the Marketplace
Details page, owned by editor-marketplace-page).
---
## 2. Feature dependency graph
96 features. They cluster into eight lanes; edges inside a lane are listed in
100 features. They cluster into eight lanes; edges inside a lane are listed in
that lane's table, cross-lane edges are repeated where they matter. The
mermaid graph shows the lanes and the load-bearing cross-lane edges only.
@@ -292,7 +308,7 @@ graph LR
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
| `recursion-limit ◀──▶ parallel-files` | handshake | recursion-limit requires ≥8 MiB worker stacks; parallel-files built the pool with `stack_size(8 MiB)` and a test that fails if it is removed. |
| `recursion-limit ◀──▶ parallel-files` | handshake | recursion-limit requires every parsing thread to use `vlog_parser::PARSE_STACK_SIZE` (currently 16 MiB); parallel-files points the rayon pool at the constant, and the later stack audit put the CLI/server main work on named threads using the same value. Tests fail if a spawn site drifts. |
| `recursion-limit ◀──▶ error-recovery` | handshake | Recovery must not reset `depth`/`links` while unwinding; error-recovery proves it with white-box + mutation tests. |
| `one-parse ◀──▶ linter-core / server-lint` | handshake | Both filed the "one parse, two tools" request; one-parse delivered `LintContext::from_parse` + `ParsedSource`, `Document` gained its `tree` field, and both front ends lint from one parse. Behavior byte-identical was the gate. |
@@ -397,6 +413,14 @@ promise:
| `index-persistence ──▶ format-cache` (lucisv_core) | depends | Reuses `lucisv_core::cache::content_hash` — one FNV-1a shared with the format cache, not a second copy. Also one additive `vlog_parser` touch: `DefineTable::from_entries` + `PartialEq`/`Eq` derives, so a record restores a table without re-reading a file. |
| `index-persistence ◀──▶ indexing-ux` | handshake | `IndexEvent::Cached` — a new variant, so every consumer is forced to say what it does with an unparsed file; the end message names the cached count. |
| `port-detail-spans ◀──▶ index-persistence` | handshake | A declaration record grew two numbers (the detail span, written unconditionally as `0 0` for the `None` every ordinary declaration has), so **`FACTS_FORMAT` went 2 → 3** and every store written by an earlier build is discarded whole rather than read field-shifted. The bump *is* the contract: `index_cache.rs`'s header line carries the number, and the reader's `done()` check is a backstop, not a version scheme. |
| `vscode-hierarchy-sidebar ◀──▶ index-persistence / hover-line-index / incremental-index` | handshake | **`FACTS_FORMAT` 4 → 5**, one bump for three additions: `Def::decl_span`; `InstantiationEdge::instances` (a `Vec<InstanceOccurrence>` — the statement edge stays one-per-statement, so call hierarchy and code-lens counts are unchanged and the census is still the one `instantiations::sites` walk); and client positions — `DeclLines::positions: Option<DeclPositions>` on **file-scope declarations only**, plus `Utf16Range` on every instance occurrence. Members deliberately carry none: they outnumber units by two orders of magnitude, and the `U`/`M` groups are separate, so a member costs no field at all. `FileFacts::from_analysis` grew a `src: &str` parameter (a position cannot be read off a line table). Measured store cost of the positions: +1.69 % on the 820-file corpus, +1.86 % on opentitan. |
| `vscode-hierarchy-sidebar ──▶ vlog_parser` | depends | `LineIndex::utf16_position` — byte offset to (0-based line, UTF-16 column), moved down beside the line table so the semantic index and `lucisv_server::convert::Positions` cannot answer differently. `Positions::position` is now a wrapper over it; the cross-crate equality is test-pinned. |
| `vscode-hierarchy-sidebar ◀──▶ workspace-index` | handshake | `WorkspaceIndex::units_of(kind)` — file-scope declarations of one kind, in name order, walking the unit table alone. The cheap half of `workspace_symbols("")` for a caller that never wants members; 15 ms per snapshot on opentitan. |
| `hover-line-index ──▶ port-detail-spans / index-persistence` | depends + handshake | `DeclLines { name, detail }` rides each indexed `Decl`, so ordinary and split-port hover headings do not reread a file just to compute a line. The record grew again and **`FACTS_FORMAT` went 3 → 4**; the server's bounded `FileView` cache supplies the text/`LineIndex` only when a snippet or a non-indexed position still needs it. Its four invalidation points are `set_document`, `close_document`, `update_one`, and a whole rebuild. |
| `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and `IncludeGraph::absorb` publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. |
| `scan-interleave ──▶ hover-line-index` | depends | Delivers hover-line-index's measured startup-wait request: a startup scan above 64 files drains queued messages between files. A rescan deliberately still holds requests; what an answer sees never depends on elapsed wall time. |
| `index-scope ──▶ scan-interleave` | depends | A scope widen is the second `Scan` shape (`begin_widen`) and shares `scan_step`/`finish_scan`; it folds only newly reached folders plus open-buffer analyses, never masquerades as a whole scan, and never interleaves. Folder scope now ships at depth 2; rootless sessions do not climb an unnamed tree. |
| `index-scope ──▶ one-parse / completion-core` | depends | Whole scans and widens reuse each open `Document`'s existing `FileFacts` and completion words rather than reparse its text. `IndexEvent::Analyzed` keeps this distinct from a persistent-cache hit. |
| `define-table ◀──▶ macro-expansion` | handshake | What began as free-to-change became contract at M14: params stored **as written**, `NAME()` = `Some(vec![])` — `expand.rs` counts arguments against them and declines on mismatch. |
### 2.6 Refactor lane (the M-plan)
@@ -409,9 +433,12 @@ promise:
| `refactor-rename (M2) ──▶ vlog-semantic / workspace-index` | depends | Every edit from a resolved span; whole-edit verification; refusals from `Resolution` variants. |
| `refactor-rename ◀──▶ vlog_semantic` | handshake | The one authorized cross-module change of M2: `Target::Declaration` + `use_end_label` (end labels must rename or the output doesn't compile). Strictly additive; logged in vlog-semantic's work log. |
| `refactor-ports (M3) ──▶ refactor-rename` | depends | Reuses M2's `check`/`Scope`; the two preprocessor scans were factored to return *sites* so M3 words its own warnings without inheriting M2's text (M2's wording pinned by its 48 tests). |
| `refactor-ports ◀──▶ incremental-index / lucisv_server` | handshake | `port_action_modules` and `enclosing_module` name the engine's possible module targets; `Workspace::module_sources` expands them through module declarations, `instantiations_of`, reference postings and open buffers. Code actions and all three commands use the same builder, and parity tests assert the narrowed result equals the old whole-scope result. The instantiation census in `vlog_semantic::instantiations` and `ports::collect_instantiations` must grow together. |
| `refactor-instantiate (M4) ──▶ workspace-index, editor-scopes` | depends | Plans from the index's real definitions; the item-position gate is built on `pairs::analyze`'s published output only. |
| `apply-edit ──▶ refactor-ports` | depends | The port commands now *push* `workspace/applyEdit` (the protocol's actual mechanism) instead of answering the edit as a result no client applies. `ports::execute`'s signature and behavior unchanged — the only `ports.rs` edit was correcting a now-false doc comment, so this is consumption, not a handshake. |
| `references-nav ──▶ refactor-rename` | depends | `find_references` is `Scope::collect_occurrences` lifted out of `collect_edits` — the references list and a rename's touch-set **cannot disagree**, by construction (deliberately not moved to `vlog_semantic`; the walk needs refactor-crate concerns). |
| `refactor-rename ◀──▶ workspace-index / lucisv_server` | handshake | `prepareRename` answers from the open `Document` plus index through `prepare_rename_here`; `rename` asks `rename_name_at` for the engine's target and feeds only `Workspace::rename_sources`'s six-rung superset. The rungs cover declarations/members, resolved postings, instantiation edges, macro definitions, every open buffer, and `files_spelling` for unresolved new-name uses; if a rung cannot bound a case it falls back to all sources. Refusal sentences and whole-scope parity are pinned. Open residue: macro-invocation-argument warnings need §2.9-18. |
| `file-operations ◀──▶ include-nav / lucisv_server` | handshake | `IncludeGraph::includers` exposes the files that can contain a resolving include; `Workspace::include_sources` overlays open buffers and reads only that set for `willRenameFiles`, instead of the workspace. It is sound only while the graph's held-edge census and `resolve` agree. |
### 2.7 LSP server lane
@@ -422,7 +449,7 @@ engine-lane features are listed above; this table is the server-internal web.
|---|---|---|
| `editor-scopes ─▶ (many)` | depends (consumed by) | `pairs.rs` — one stack matcher, eight consumers today: documentHighlight, missing-closer diagnostics, `lucisv/scopePairs` rainbow, folding (references-nav), the item-position gates (completion-core / refactor-instantiate), on-type-formatting's keyword tables, inline-templates' unmatched-`begin` check, expand-selection (`selection.rs`). The `RULES` table + guard list is the shared truth; a keyword change means re-checking it. |
| `editor-scopes ◀──▶ editors/vscode` | handshake | The `lucisv/scopePairs` wire shape (pinned as literal JSON in a test) and the `lucisv.rainbow*` colour ids that must match between `package.json` and `extension.js`. |
| `completion-core ──▶ define-table, vlog-semantic, workspace-index, refactor-instantiate` | depends | Five tiers over existing facts; the parser widening (`KEYWORDS` export) is its one engine touch. Deliberate duplication recorded: `visible_symbols` vs `ports::visible_in` share an idea, not code. |
| `completion-core ──▶ define-table, vlog-semantic, workspace-index, refactor-instantiate` | depends | Five tiers over existing facts; the parser widening (`KEYWORDS` export) is its one engine touch. Deliberate duplication recorded: `visible_symbols` vs `ports::visible_in` share an idea, not code. Since the performance wave, tier 0 reads module names from `Candidates::modules` (built once with the index) and parses only a definition's guarded header slice; equality with `vlog_refactor::module_names` and full-file planning is test-pinned. |
| `completion-templates ──▶ completion-core, editor-scopes` | depends | Tier 3; `templates.rs` is data + one renderer; tier digits moved (only e2e's word-tier assertion cared). Also consumes `vlog_refactor::Layout` (M4's `{ base, step }`), reused rather than re-declared, so a skeleton and a template indent by one type. |
| `completion-templates ◀──▶ editor-snippets` | handshake | Nine overlapping statement/block snippets were **removed** from `editors/vscode/snippets/*.json` when the server started offering them as tier 3; both READMEs' prefix tables are the shared truth. A template added server-side must check the static set, and vice versa. |
| `inlay-hints ──▶ refactor-instantiate` | depends | Reads exactly the `module_definition` + `instantiation_plan` facts M4 published (the `PlanPort`/`PlanParam` name lists signature help reads); every plan refusal is swallowed silently — a hint has no place for a sentence. |
@@ -437,16 +464,23 @@ engine-lane features are listed above; this table is the server-internal web.
| `change-debounce ◀──▶ incremental-sync, pull-diagnostics` | handshake | The amendment above. A `didChange` composes its ranges against the *pending* text when there is one (`sync::apply_changes` unchanged) and defers only the analysis; the flush happens at the next request, the next non-`didChange` notification, or a 150 ms quiet period on the `cancel-request` queue (`recv_timeout` — no thread, no timer object). Observable: intermediate diagnostics states are no longer published, pinned in `tests/e2e.rs`. |
| `port-detail-spans ──▶ hover-declarations` | depends | The second fenced section, and the comment attached to each, are built on hover-declarations' snippet machinery and its `spells_exactly` guard, both unchanged. `nav::definition` returns the detail location first so a jump and the card cannot disagree. |
| `hover-declarations ◀──▶ vlog_semantic` | handshake | `Semantics::symbols_named` (§1.2) replaced `hover::live_symbol`'s and `nav::indexed_references`' scan-every-symbol loops. Behavior-identical **because the lookup preserves declaration order** — the tie-break between two live declarations of one name is pinned on both sides. |
| `hover-line-index ──▶ hover-declarations / port-detail-spans` | depends | `Def::lines` supplies indexed hover headings (including split-port detail lines); `Workspace::file_view` supplies the guarded snippet and the few non-indexed line lookups. `locate::location` shares that view, so a references list reads a closed file once rather than once per site. |
| `cancel-request ──▶ lsp-server pin` | depends | See §1.2; queue/burst exists because the pinned transport is a rendezvous channel. |
| `scan-interleave ──▶ cancel-request / work-done-progress` | depends | The same queue is polled between startup-scan files. `publish_scan` lands the index, completion and include batches before dispatch; `must_wait` holds requests queued behind any rescan-triggering message and preserves their order/cancels. Progress still counts the whole scan even when requests are answered before the bar comes down. |
| `verbose-timing ◀──▶ editor-packaging / scan-interleave / change-debounce` | handshake | `lucisv.verbose` is an extension-owned spawn setting: false means no arguments and no timing traffic; true means `lucisv-server --verbose`, and changing it restarts the client process. The server writes `MessageType::LOG` lines prefixed `timing:` for request/notification handlers, scan and widen lifecycles, dirty-buffer flushes, one-file reindexes, and requests held behind rescans. The request line precedes its response; notification lines follow their work. Instrumentation is silent by construction when off (one branch, no clock read or formatting), and it observes rather than changes scan/queue ordering. |
| `work-done-progress ──▶ indexing-ux` | depends (then) | w-d-p put up the bar; indexing-ux made it count (`IndexEvent` stream); index-persistence added `Cached`. |
| `large-file-mode ◀──▶ semantic-tokens-delta` | handshake | The windowed lexing serves `semanticTokens/range`; on a large buffer `full`/`full/delta` must answer an ERROR (`ServerCancelled`/`ContentModified`) or the client stops asking the range provider — two sides pinning one wire behavior. `Document::large` is structurally a full `Document` (all fields valid, empty) so no handler changes — the obligation lands on **future** handlers that read `doc.text` (dispatch-table test enforces). |
| `lsp-318-extras ──▶ range-formatting` | depends | `rangesFormatting` is a thin adapter over the same n-range `LineRanges` engine `--lines` uses; hand-rolled params because `lsp-types` 0.97 lacks 3.18. |
| `on-type-formatting ──▶ range-formatting, editor-scopes` | depends | `;` goes through `format::range_formatting` unchanged; `\n` answers indent only, computed from `pairs.rs`'s own keyword tables (three items widened to `pub(crate)`) — one reader's answer for "what opens a scope". |
| `interactive-latency ──▶ change-debounce, editor-scopes, selection-range, on-type-formatting, completion-core, inline-templates` | depends | Round 2 of the perf work (`docs/perf/README.md`). It measures the flush change-debounce coalesces and the round trip it defers, and it replaces one token *sweep* with one token *binary search* in `selection.rs`, `on_type.rs`, `completion.rs` and `inline.rs`. No answer moved — each swap is pinned against the sweep it replaced at every byte — so none of those five features' contracts changed; what they now share is `state.rs`'s two search primitives and the ordering property of `tokenize`'s output they rest on. |
| `interactive-latency ◀──▶ lucisv-server` | handshake | Two free functions, `first_token_reaching` and `first_token_from`, are published from `state.rs` beside `Document::token_at`; that is where the monotonicity argument every caller depends on is written down, and `state::tests::the_token_stream_rises_and_never_overlaps` is the test that fails first if `vlog_parser` ever breaks it. `tests/e2e.rs`'s `Live::finish` now returns its publish count (existing callers ignore it), and `perf::generated_module` has a copy in `tests/e2e.rs` — a binary crate's modules are unreachable from an integration test — which must stay the same shape as the original. |
| `references-nav ──▶ workspace-index / hover-line-index` | depends | Cross-file references resolve an indexed target first and consume declaration postings directly; same-file local references stay on `Semantics`. Locations use the shared `FileView`. `documentHighlight` now also follows the document's external overlay for names declared elsewhere, fixing the old “references works, highlight is empty” split without widening highlights beyond the current file. |
| `selection-range / linked-editing ──▶ spans, name-spans` | depends | Pure arrangements of existing ranges; linked-editing's table documents exactly which constructs carry both spans (and which verbatim ones can't — `program`, property/sequence, covergroup). |
| `type-definition ──▶ nav / overlay-promotion / ansi-first-port` | depends + 2 delivered handshakes | Now literally `nav::definition` at the type name's offset; both of its filed requests landed (§2.2, §2.5). |
| `hierarchy ◀──▶ inlay-hints` | handshake (shared walk) | The instantiation walk was lifted out of `inlay.rs` into a shared module (now `vlog_semantic::instantiations`) rather than copied — the two answers cannot drift; inlay's 34 tests are the regression net. |
| `vscode-hierarchy-sidebar ◀──▶ editors/vscode` | handshake | Two custom wire members, both **gated on `initializationOptions.hierarchyView`** so no other LSP client sees them: the request `lucisv/moduleHierarchy` → a flat `schemaVersion: 2` snapshot (`files` table; locations as `{ file, range, selectionRange }` with each range `[startLine, startCharacter, endLine, endCharacter]`; **no** per-row id and **no** per-instance `definitions` — the client composes both in `hierarchyModel.js::validateSnapshot`), and the notification `lucisv/moduleHierarchyChanged { revision }`. `revision` rises on every completed index install; the notification rides beside the code-lens refresh point so all mutation paths are covered once. An older binary answers `-32601`, which the view renders as a compatibility message. |
| `vscode-hierarchy-sidebar ◀──▶ code-lens / hierarchy` | handshake | Both read the *same* statement-level `InstantiationEdge`; only the sidebar flattens `edge.instances`, so `sub u1 (), u2 ();` is still one call site and one lens count and two sidebar rows. No second census exists. |
| `vscode-hierarchy-sidebar ──▶ scan-interleave / cancel-request` | depends | `complete` is `Server::index_is_complete()` = `!scanning && !must_wait()`. It is false exactly during the startup scan: a request owed a rescan is *held* by `must_wait`, and `rescan_wanted` is only ever set while `scanning` is true, so no snapshot is ever answered `complete` off an index a queued message is about to rebuild. |
| `code-lens ◀──▶ hierarchy` | handshake | code-lens split `incoming` into the batch primitive `callers_of_each` so lens and hierarchy share one census; `incoming` is a one-element call into it and its behavior (empty-name guard included) is pinned unchanged. Lens and hierarchy views can never disagree; refresh rides `reindex()` after the bar comes down. |
| `server-lint / pull-diagnostics / editor-scopes ──▶ diagnostics.rs` | depends | One `diagnostics::all` composition: parse errors + missing-closer warnings + lint warnings, one publish (or one pull) per change; `send_diagnostics` is the single push gate so a pulling client is never served both models. |
@@ -454,7 +488,7 @@ engine-lane features are listed above; this table is the server-internal web.
| edge | kind | contract |
|---|---|---|
| `editor-packaging ◀──▶ lucisv-server` | handshake | The spawn contract (§1.2) plus the fence-tag contract: every markdown code block the server emits opens ```` ```systemverilog ```` — three call sites pin the string; the grammar registers the id. |
| `editor-packaging ◀──▶ lucisv-server` | handshake | The spawn contract (§1.2), including verbose-timing's `[]` / `['--verbose']` argument pair and restart-on-setting-change rule, plus the fence-tag contract: every markdown code block the server emits opens ```` ```systemverilog ```` — three call sites pin the string; the grammar registers the id. |
| `editor-packaging ◀──▶ vlog_parser` | handshake | The grammar↔`KEYWORDS` test lock (§1.2). |
| `editor-snippets ──▶ editor-packaging` | depends | Static `contributes.snippets` keyed to the two language ids the manifest declares; consumes nothing from the server *at runtime* (works with the server missing — deliberate). Its **content** is negotiated against the server's template tier — see the `completion-templates ◀──▶ editor-snippets` handshake in §2.7. |
| `editor-platform-vsix ──▶ editor-packaging, release-prep` | depends | Changes *which path* is spawned, never how; consumes `release.sh`'s artifact naming; promises the three `bin/` layout shapes to `extension.js` (asserted with `unzip -Z1` per package). |
@@ -487,8 +521,11 @@ update the filing README(s) and this file.
| 15 | Bind semantics: whether a `bind`'s target scope and connections should resolve through the workspace index (today only the instantiated module name is recorded) | bind | vlog_semantic |
| 16 | DPI/package re-export halves as real references (`export pkg::item` doesn't resolve; `*::*` has `"*"` as its package name, which nothing expects) | dpi-export | vlog_semantic |
| 17 | Inline aggregate as a parameter-override *argument* (`m #(.T(struct packed { logic a; })) u ();`) is rejected in expression position; M4's `instantiation_plan` drops such a `parameter type` default rather than emit unparseable text | refactor-instantiate (gap 1; its gap 2 was delivered by ansi-first-port) | vlog_parser |
| 18 | A macro-invocation census in `FileFacts`: per-file macro names plus identifier-shaped words in their arguments. Rename's index-bounded fan-out currently preserves every edit/refusal but can lose informational macro-argument warnings in files that have no other relationship to the renamed name; the same table would serve the port refactorings' identical scan. This changes the record shape and therefore requires a `FACTS_FORMAT` bump. | refactor-rename (performance-wave residue, accepted and filed) | vlog_semantic |
---## 3. Combined graph — features mapped onto modules
---
## 3. Combined graph — features mapped onto modules
### 3.1 Feature → primary-home matrix
@@ -504,13 +541,13 @@ untouched, reusing existing arms.
|---|---|
| `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) |
| `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter |
| `vlog_semantic` | vlog-semantic (`bind`/`resolve`/`model`), workspace-index (`workspace.rs`), class-semantics, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` in `bind.rs`/`model.rs`/`workspace.rs`, the `facts.rs` codec + `FACTS_FORMAT` bump, and `Semantics::symbols_named` in `lib.rs`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`), incremental-index (`update_file`, edge tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) |
| `vlog_semantic` | vlog-semantic (`bind`/`resolve`/`model`), workspace-index (`workspace.rs`), class-semantics, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` and `Semantics::symbols_named`), hover-line-index (`DeclLines`, facts codec + `FACTS_FORMAT` 4), scan-interleave (`WorkspaceIndex::absorb`), refactor-rename's performance amendment (`files_spelling`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`, facts-from-analysis), incremental-index (`update_file`, edge/reference tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) |
| `vlog_linter` | linter-core, lint-harness, lint-rules-2, semantic-lints (`signals.rs`), one-parse (`context.rs`) |
| `vlog_refactor` | refactor (plan), refactor-rename, refactor-ports, refactor-instantiate, references-nav (engine half) |
| `vlog_refactor` | refactor (plan), refactor-rename (including `prepare_rename_here` / `rename_name_at` selector half), refactor-ports (including module-target selectors), refactor-instantiate, references-nav (whole-scope equivalence oracle) |
| `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`) |
| `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract) |
| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring→`rename.rs`/`ports.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs`, pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, change-debounce→`server.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` |
| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line) |
| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave→`server.rs`+`state.rs`+`candidates.rs`+`includes.rs`, change-debounce→`server.rs`, verbose-timing→`main.rs`+`server.rs`+`tests/e2e.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` |
| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line), verbose-timing (`lucisv.verbose`, spawn args and restart in `extension.js`) |
| `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`) |
### 3.2 The combined picture
@@ -592,11 +629,13 @@ ownership explicitly.
| `vlog_formatter/src/verify.rs` | safety-net | every formatter feature; the CLI's exit-2 promise | CLAUDE.md invariant #4. Never widen a normalization without masked-corruption attack tests; the standing pattern is "untouched + rejection tests anyway". The single widening in history is macro-items' backtick-`Ident` arm in `normalize` — which produced lucisv's one real corruption; its repair, `trim_lines_outside_strings`, is a *narrowing*, and the pattern to copy: the widening shipped without attack tests, the fix shipped with them. `line_starts_inside_string` is the one definition of "which line breaks are data" — both `format.rs` and `verify.rs` must read it. |
| `vlog_formatter/src/fence.rs` | format-fences | range-formatting, shared-fence-filter, CLI `--fix` (`lucisv/src/lint.rs`), server quick fixes (`lucisv_server/src/lint.rs`) | `protected_regions`/`is_protected` are the **only** supported way to ask "may an automatic edit touch these bytes". One answer, **two** front ends — and `vlog_linter` is deliberately not one of them (it stays fence-blind; the filter lives in each front end). Open gap: no `Class` arm in `scan_nested` (§2.9-3). |
| `lucisv_server/src/pairs.rs` | editor-scopes | documentHighlight, missing-closer diagnostics, scopePairs rainbow, folding, completion gates, on-type indent, inline-templates, expand-selection (`selection.rs`) | The `RULES` table + no-closer guard list is shared truth. Any keyword added to/removed from `token.rs` requires re-checking it (a word that stops being a keyword silently stops being matched). |
| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, indexing-ux, incremental-index, index-persistence, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`) | every handler | `Workspace` is immutable through request handlers (no caches added by handlers — hierarchy/inlay/type-hierarchy all state it). The scope ladder (filelist > `index.scope: "workspace"` > folder-scope, with the rootless flat sibling read as folder-scope's one exception; buffers overlay everything) is the contract; `update_one`'s answer must equal a full rebuild's (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. |
| `lucisv_server/src/server.rs` | lucisv-server; amended by cancel-request, change-debounce, scan-interleave, index-scope, verbose-timing | every request/notification and every rebuild trigger | One ordered loop owns all mutable server state. A startup scan may publish a prefix and answer queued work between files; a request queued behind a rescan trigger is held until that rescan lands, and its cancel travels with it. Never make the distinction time-based: machine load must not change which index a request sees. Verbose timing may observe each wrapper/lifecycle but must be entirely silent when off and must not move protocol ordering. The queue thread only forwards protocol messages and must never parse. |
| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, scan-interleave, indexing-ux, incremental-index, index-persistence, hover-line-index, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`), refactor performance fan-outs | every handler | `Workspace` is immutable through request handlers except the interior-mutable four-entry/8 MiB `FileView` cache. The scope ladder (filelist > `index.scope: "workspace"` > folder-scope at shipped depth 2; a rootless session never climbs and always reads its own directory flat) and open-buffer overlay are contracts. `Scan` has whole/widen shapes but one step/finish path; index/candidate/include prefixes publish together. `module_sources`, `rename_sources`, and `include_sources` must remain supersets of what their engines can edit/refuse over; `rename_sources` falls back to `sources()` when an ambiguous posting prevents a proven bound. `update_one` and a completed scan must equal a fresh build (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. |
| `lucisv_server/src/settings.rs` | editor-settings | folders-and-config, indexing-ux, index-scope, index-persistence, inline-templates, will-save-wait-until, filelist, large-file-mode | One parser for both doors (push and pull, via `from_section` re-wrapping). Every key drops garbage independently; defaults that are not "silence" (1 MiB cap, log on, persist on, 4 MiB large-file threshold) are hand-written in `Default`. `set_client_settings` returns whether a reindex is owed — new keys must decide that question explicitly. |
| `vlog_semantic/src/workspace.rs` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope | server state, hierarchy/lens/type-hierarchy, refactor, completion | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change, edge tables built by the same lifted walks the handlers use. |
| `vlog_semantic/src/workspace.rs` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope, hover-line-index, scan-interleave, refactor-rename performance | server state, hierarchy/lens/type-hierarchy, refactor, completion | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change (currently 4), edge/posting tables built by the same lifted walks the engines use. `DeclLines` must round-trip and participate in `fingerprint`; `absorb` must equal one build over the resulting record set; `files_spelling` must continue to include unresolved non-empty external/inherited paths or rename loses its dangling-use refusal. |
| `vlog_refactor/src/rename.rs` | refactor-rename; shared by references-nav and the performance wave | server rename/prepareRename/references and port refactor verification | `Scope` remains the whole-scope authority and `collect_occurrences` the one rename/references walk. The fast `prepare_rename_here` answer/refusal and `rename_name_at` target are parity contracts, not alternate semantics. Any new refusal must be expressible on the fast path or force a deferral; any new occurrence shape must be reflected in the server fan-out or trigger its all-sources fallback. |
| `vlog_parser/src/token.rs` keyword table | completion-core (`KEYWORDS` export) | lexer, pairs.rs, editor grammar (test-locked), completion | Adding a keyword = lexer change + `pairs.rs` re-check + a hand edit to the grammar (`tests/grammar.rs` names the missing word) + potentially `verify.rs`-adjacent behavior. dv-statements added `randcase`/`let` to `is_keyword` and recorded it as shared with the adjacent lexer-cleanup round — the precedent for treating this file as coordinated even between back-to-back rounds. |
| `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). Version number is one of the four version files. |
| `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, verbose-timing, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). `lucisv.verbose` is special: it changes a spawn argument and therefore restarts the server instead of flowing through the ordinary settings push. Version number is one of the four version files. |
| `tools/release.sh` artifact names | release-prep / editor-platform-vsix | ci-release (`prune_release_assets.sh`), `audit_artifacts.sh`, extension `bin/` layouts | Renaming a `.vsix` is a two-file change (`release.sh` + `prune_release_assets.sh`'s suffix list); renaming a per-triple binary is a two-file change (`release.sh` + `audit_artifacts.sh`, which skips `.vsix` and hard-fails on an unknown binary name). Get the wrong pair and the release fails by name. |
| The frozen CLI contract | cli-polish | corpus scripts, CI users, every new CLI mode | Exit codes 0/1/2 forever; stdout stays machine-readable (JSON mode prints exactly one array; warnings to stderr). |