Compare commits

...
27 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
lucioandClaude Fable 5 b7a934080a Release 0.14.0 — the first-hover release
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 4m54s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:22:30 -07:00
lucioandClaude Fable 5 172a034c67 The startup scan answers requests as it goes
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
A request sent right after initialized waited out the whole startup
scan — 780 ms cold, 287 ms warm over 200 files, against 26-64 us once
the scan was done. The scan is now a value (Scan: begin/step/publish/
finish; rebuild_index_with is the same three-line loop, so one-shot
and interleaved are structurally the same code and fingerprint
identically), fed to the live index with one WorkspaceIndex::absorb
per drain — per-file merging measured quadratic, 11.7 s over 800
files — and the message queue drains between files: the first hover of
a session answers in 15.5 ms cold / 12.8 ms warm against the index so
far, open file first, scan totals inside noise. Order contract kept:
only the startup scan answers mid-way (must_wait holds requests queued
behind any rescan), scans under 64 files stay one-shot (a count, not a
clock), mid-scan rescan requests coalesce into exactly one follow-up,
shutdown stops the scan where it stands. All three tables publish
together. QA pinned the INTERLEAVE_ABOVE boundary, the absorb
duplicate-path edge and the mid-scan didOpen double-publish; the whole
pre-existing suite passes unmodified, stable over repeated runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:20:20 -07:00
lucioandClaude Fable 5 20567e1a7f The index carries every declaration's line, and hover stops re-reading files
ci / checks (push) Successful in 40s
ci / corpus (push) Successful in 18s
The owner's first-level cache, realized on the carrier the index
already had: DeclLines (name line + detail line) on every Decl/Def,
computed at index time from the LineIndex the analysis already holds —
tens of KB for 20k modules, FACTS_FORMAT 3->4, old stores discarded
whole. A closed file's hover heading now costs zero I/O (it survives
the file being deleted), and the snippet's one remaining read is
served from a bounded FileView LRU (4 entries / 8 MiB, newest kept,
dropped on set_document/close/update_one/rebuild): repeat hovers into
a 12 MB file go 5.8 ms -> ~1 us, cross-file hover means 40/157 us ->
4.7/12.9 us. Ports ride the same member entries, so their lines came
free. Stale-disk edits leave heading and snippet stale together, the
spells_exactly guard still omits rather than lies, and QA pinned the
pair. Measured and filed, not fixed here: the first request of a
session waits 287-780 ms behind the startup scan (handshake for the
next round).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 18:04:38 -07:00
lucioandClaude Fable 5 17214ac8db Release 0.13.1 — the F12-latency release
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m37s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:31:47 -07:00
lucioandClaude Fable 5 d4eb8f48ff The stack fits the nesting limit by construction, on every thread
ci / checks (push) Successful in 42s
ci / corpus (push) Successful in 19s
MAX_NESTING_DEPTH turns over-deep input into a parse error only on a
stack big enough to reach level 64, and that was an unenforced README
assumption: debug frames drifted to ~94 KiB/level under rustc 1.97
(worst family nested case, 5.9 MiB at the limit), so a default 2 MiB
spawned thread aborted around level 30 with the limiter never firing.
New vlog_parser::PARSE_STACK_SIZE (16 MiB, 2.7x the re-measured worst
case) is applied at every parse-reaching site: both binaries' work
moved onto named spawned threads (a main stack is the OS's to size —
1 MiB on win32; pre-fix lucisv aborts under ulimit -s 1024, fixed one
diagnoses), rayon pool workers resized, forwarder and lsp-server IO
threads audited parse-free. Deep-nesting suites across four crates on
controlled stacks, sabotage-verified; caller-side stack contract added
to every public parse entry point's rustdoc. analyze measured at
71 KiB on a max-legal tree — no second bound needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:26:06 -07:00
lucioandClaude Fable 5 cf32e92e58 A rescan reuses what open buffers already analyzed
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 21s
A scope-widening didOpen re-parsed every open buffer's text twice —
once for its index facts, once for its completion words — 210 ms of a
223 ms rescan for one 1.4 MB top.sv. FileFacts::of and words_in each
split so their post-parse half is callable on a finished analysis
(facts_from_analysis, words_of_tokens; one implementation per path, so
the routes cannot drift), and collect_sources hands the index and
candidates builds each open buffer's held analysis instead of its
text, on the whole-rebuild path and didSave's. ~228 ms -> ~23 ms.
Equivalence pinned: encoded facts and fingerprints byte-identical
between the two routes over the corpus and 16 crafted non-corpus
shapes; unsaved-edit, didClose-revert, size-cap and large-file
threshold boundaries tested both directions. IndexEvent::Analyzed
keeps "from cache" meaning the persistent store.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 15:28:27 -07:00
lucioandClaude Fable 5 097498da23 References stop sweeping the whole open buffer per request
The open-document overlay loop in indexed_references did two index
lookups and a scope walk for every reference in every open buffer.
A spelled-name prefilter (sound: every Def is filed under exactly its
own declared name, so a mismatched name can never match the target)
plus a hoisted file_id take a 70k-reference open top from 3.2 ms to
110 us per request, both directions. In-file references and
documentHighlight batch-convert spans through the walker (1.76 ms ->
1.18 ms / 917 us on a 10k-use signal). Answers byte-identical; the
refactor-walk equivalence suite extended with a unit-vs-member
same-spelling case. Measurements also acquitted references of the
owner-reported direction asymmetry: the felt cost is the didOpen
scope-widening rescan re-parsing open buffers (210 of 223 ms), filed
as a Handshake for the next round.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 14:02:15 -07:00
lucioandClaude Opus 5 4f7b4a9f91 Release 0.13.0 — the responsiveness release
ci / checks (push) Successful in 49s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m55s
Typing no longer reanalyzes the buffer on every keystroke, cursor
answers binary-search the token stream instead of sweeping it, and
hover finally reads an old-style split port the way a designer wrote
it — header and body declaration, each with its comments.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:17:39 -07:00
lucioandClaude Opus 5 574ab833e3 Feature docs for the responsiveness round, and a perf record
Three new feature READMEs — change-debounce, port-detail-spans,
interactive-latency — each with the mandated sections, dev work logs,
QA findings and their dispositions, and the lead's review. Plus
`docs/perf/README.md`, the record of what was measured, on what, on
which machine, and with which command, so a later round can say
whether it made something faster or only different.

`topo.md` is added to the tree: the dependency topology the round was
planned against, with this round's new edges — the `detail_span` and
`symbols_named` handshake between the server and `vlog_semantic`, and
the facts-format edge to index persistence.

The perf record keeps its losses as well as its wins. A keystroke
followed by nothing now publishes at 164 ms rather than one
reanalysis, because it waits out the quiet period; a perf document
that only records improvements is not a perf document.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:54 -07:00
lucioandClaude Opus 5 12d0bbad51 Measure the paths a keystroke and a hover run through
Twelve `#[ignore]`d measurements, standard library only — `Instant`,
a mean over 10 to 1 000 runs and `black_box`, which is the shape this
repo already uses for perf notes. No benchmark dependency: the
workspace pins six direct ones and `CLAUDE.md` wants a written
justification for a seventh, which statistical rigor on numbers that
assert nothing does not earn.

They answer where a flush's time goes, and the answer is that lexing
and parsing are 79% of it. `analyze` is 5.5 ms of 31 ms, the lint pass
4%, and `resolve_external` — the one the plan expected to matter — is
49 µs, one part in six hundred. The breakdown sums to `Document::new`,
so nothing is unaccounted for.

They also take the numbers this round's changes are argued from: the
cost of one read and one `LineIndex` inside a cross-file hover, the
name lookup against the scan it replaced, and the token search against
the sweep it replaced.

Nothing here is a budget. A test that fails when the machine is busy
is a test that gets deleted.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:45 -07:00
lucioandClaude Opus 5 de8a7e129c Cursor answers binary-search the token stream instead of sweeping it
Expand-selection, on-type formatting, the completion scope gates and
the inline template trigger each walked every token in the file to
find the one at the cursor. The stream is sorted by start and does not
overlap, so the position is a binary search: 77 µs → 20 ns in a
10 000-line buffer, and 130 µs → 36 ns for completion's balanced
window, which had no upper bound and so swept the whole file to reach
a window a few dozen tokens wide.

Two primitives rather than one, and deliberately not `token_at`:
`selection.rs`'s `covers` takes `span.end` inclusively, so at a byte
two tokens share, the sweep returned the *earlier* token where
`token_at` returns the later one. Reaching for the existing helper
would have changed an answer.

No answer changes. Each swap is pinned by a test comparing the new
expression against the predicate it replaced at every byte of a buffer
written to be full of touching tokens, and the precondition they all
rest on — that the stream rises and never overlaps — is pinned
separately, so it is the test that fails first if the parser ever
changes shape.

Left alone, with reasons: signature help's paren depth is a function
of every bracket before the cursor and so is inherently a prefix scan;
`pairs.rs` is not a position query; and completion's comment gate
cannot be answered by any search of the stream, because comments are
trivia attached to whichever token happens to be adjacent. That last
one is the remaining per-keystroke whole-buffer walk.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:34 -07:00
lucioandClaude Opus 5 611dd23069 Hover shows a split port's real declaration, and its comments
A non-ANSI port's card used to show `data_in,` — the header line that
names it and says nothing else. It now shows two fenced sections: the
header, then the body declaration carrying the direction, the type and
the width. Go-to-definition offers both, body declaration first, so
hover and the jump agree. It works into closed files, because the
detail span travels through the workspace index.

Each section also carries the comments that document it: the comment
beside the declaration, the comment-only lines above it, and the
comment-only lines below it — all three where all three are written.
The guards are what make this safe rather than a guess. The walk above
stops at the first line that is not comment-only, so a line carrying
another port never contributes its trailing comment. The block below
attaches only when the line after it is one that positively reads as a
closer — a whitelist, deliberately, so that a line the predicate does
not recognise reads as another declaration and the comment stays with
it. Only a false "another declaration is here" is safe: it merely
declines to attach a comment, while a false "nothing here" would print
one declaration's comment on another's card.

Also: a hover into a closed file now reads that file once. The heading
line and the snippet used to take a read and a `LineIndex` each, since
neither shared the other's; a per-request memo keyed on the path
serves both, and `locate::line_number` answers from an open buffer's
existing index rather than re-reading it. On a 31.7 MB file that is
34 ms → 16.3 ms.

And `live_symbol` asks `symbols_named` for the candidates instead of
walking every symbol in the target buffer and calling
`indexed_def_for_symbol` on each.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:23 -07:00
lucioandClaude Opus 5 a4f23db2c7 Typing costs one reanalysis per burst, not one per keystroke
Every `didChange` used to run a full reparse, reanalysis, lint and
diagnostics publish. In a 10 000-line buffer that is 31 ms of work per
keystroke, nearly all of it thrown away by the next one.

The text stays exactly current after every notification — incremental
sync is applied immediately, and while a change is pending the buffer
the server holds *is* the pending text. Only the analysis is deferred,
and it is flushed by the first thing that needs it: the next request,
the next non-`didChange` notification, or a 150 ms quiet-period timer
in the message loop. Requests therefore see exactly what they saw
before; nothing answers from a stale buffer.

The invariant this replaces was "one didChange = one set_document =
one generation bump". It is now one *flush* = one `set_document` per
dirty buffer. The observable consequence is that intermediate
diagnostics states are no longer published, which the e2e test pins:
what is drawn is always a state the buffer really passed through,
there are simply fewer of them.

Closing a buffer drops its pending text before the flush rather than
after it, so a file closed mid-edit is not analyzed and republished
for nobody a line before its squiggles are cleared.

Also measures it over the wire, against the shipped binary: a burst of
ten keystrokes produces one `publishDiagnostics`, counted at the drain
rather than reasoned about. The burst is measured last, because every
`wait_for` accepts any publish and an earlier position would let a
second one be absorbed by the next row's wait and never counted.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:10 -07:00
lucioandClaude Opus 5 d94f9e3de0 Non-ANSI ports carry where their declaration is completed
A port declared the old way is one symbol named in the module header
and finished in the body by `input signed [31:0] data_in;`. The binder
already merged the two; what was missing was a record of *where* the
declaration is completed, so everything reading the symbol saw only
the header's bare `data_in,`.

`Symbol` and the index's `Def` gain `detail_span`, set by the binder
when a body port declaration resolves to a port already declared in
that scope — first writer wins, so a header naming a port twice stays
deterministic and is the linter's to complain about. Old-style task
and function arguments take the same path: the binder performs the
same merge for them, so they are not special-cased.

The persisted facts record grows two numbers per declaration, written
unconditionally so the stream stays flat. `FACTS_FORMAT` moves 2 → 3
because a store written before this cannot be read after it: only the
last declaration in a record is short enough to fail `done()`, and
every earlier one would be read field-shifted by two — a cache handing
back wrong spans, which is the shape the safety invariants exist to
catch. A store from the old format is now discarded whole.

Also: `Semantics::symbols_named`, a name-sorted side table of symbol
ids searched with two `partition_point`s, so looking a name up is a
binary search instead of a walk of every symbol. Stable-sorted, so
symbols sharing a name keep declaration order and the lookup is an
identity against the scan it replaces. A side table rather than a map
keyed by name, because `Semantics` is cloned per document and need not
hold a second copy of every name it already has.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:15:58 -07:00
90 changed files with 26193 additions and 622 deletions

No files matched your search

+198
View File
@@ -4,6 +4,204 @@ 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
try," traced to three costs and each one removed. Hover's steady state
was already microseconds; now the firsts are too — or as close as
physics allows.
### The index carries every declaration's line
Each indexed declaration — modules, and ports/parameters through the
same member entries — now records its line number(s), computed at index
time for a `u32` per name (+68 KB over the 860-file corpus). A hover
heading into a closed file costs zero I/O: it survives the file being
deleted. The persisted facts format moved to 4; an older cache is
discarded whole and rebuilt once (~175 ms on the corpus).
### Closed files are read once, not per hover
The snippet's one remaining read is served from a small bounded view
cache (4 files / 8 MiB, newest kept, invalidated on every path that can
change a file's text): a repeat hover into a 12 MB closed file goes
5.8 ms → ~1 µs, and mean cross-file hover 40/157 µs → 4.7/12.9 µs.
A stale view can only ever omit a snippet — the wrong-line guard is
unchanged.
### The startup scan answers requests as it goes
A request sent right after `initialized` used to wait out the whole
scan: 780 ms cold / 287 ms warm over 200 files. The scan now feeds the
live index incrementally and drains the message queue between files —
the first hover of a session answers in ~15 ms against the index so
far, with the open file indexed first. One merge per drain (per-file
merging measured quadratic: 11.7 s over 800 files), scans under 64
files stay one-shot, only the startup scan answers mid-way so the
request-order contract holds, and the finished index fingerprints
byte-identical to the old all-at-once scan. Scan totals unchanged
within noise.
## 0.13.1 — 2026-08-28
The F12-latency release: the two costs behind a slow jump out of a big
open file, found by measurement and removed, plus a stack-safety hole
closed.
### References stop sweeping the open buffer
The open-document overlay in find-references did index lookups for
every reference in every open buffer. A spelled-name prefilter and a
hoisted file lookup take a 70 000-reference open `top.sv` from 3.2 ms
to **0.11 ms** per request, both directions; in-file references and
occurrence highlighting on a heavily used signal drop ~40 %. Answers
are byte-identical — the old refactor walk remains the tested oracle.
### A rescan reuses what open buffers already analyzed
Jumping into a folder the index scope had not reached triggered a
rescan that re-parsed every open buffer's text twice — once for index
facts, once for completion words. Both now come from the analysis the
buffer already holds (one implementation per path, byte-identical facts
pinned over the corpus): the folder-widening jump drops from **228 ms
to 23 ms**, and didSave's incremental update rides the same reuse.
### The stack now fits the nesting limit by construction
The parser's 64-level nesting limit only turns over-deep input into an
error on a stack big enough to reach level 64 — an assumption that had
drifted out from under the 2026-08 measurement (~94 KiB per level in
debug under rustc 1.97; a default 2 MiB thread aborted near level 30).
`PARSE_STACK_SIZE` (16 MiB) is now applied at every parse-reaching
thread, both binaries' work included — the CLI previously aborted under
a 1 MiB main stack (`ulimit`, win32 default) on 500 nested `begin`s and
now emits an ordinary diagnostic. Deep-nesting suites across four
crates pin it, sabotage-verified.
## 0.13.0 — 2026-08-28
Editor responsiveness, and hover for old-style ports.
### Typing costs one reanalysis, not one per keystroke
`didChange` no longer reparses and re-lints the buffer on every
keystroke. The text the server holds is still exactly current after
every notification; only the analysis is deferred, and it runs at the
first moment anything needs it — the next request, the next
non-`didChange` notification, or a 150 ms quiet period. A burst of ten
keystrokes in a 10 000-line file therefore costs one 31 ms reanalysis
instead of ten. The visible consequence: intermediate diagnostics
states are no longer published, so squiggles for a half-typed line that
was finished a moment later never appear. Every state that is published
is one the buffer really passed through. Closing a file that was
mid-edit discards its pending change instead of analyzing it, so it
costs one publish — the one that clears its squiggles — and not two.
The one case this makes slower is a single keystroke followed by
nothing at all: it now waits out the quiet period before publishing,
164 ms instead of one reanalysis. Editors ask for something after every
change — semantic tokens, inlay hints, highlights — and any request
flushes the buffer before it is answered, so the latency a user
actually meets is 4.4 ms in a 1 000-line file and 37.6 ms in a
10 000-line one.
### Hover shows a non-ANSI port's real declaration
A port declared the old way — named in the module header, completed in
the body by `input signed [31:0] data_in;` — now hovers as two fenced
sections: the header line, then the body declaration that carries the
direction, the type and the width. Go-to-definition offers both, the
body declaration first. It works cross-file, into files that are not
open, because the span travels through the workspace index. An
old-style task or function argument (`task t(a);` finished by
`input [7:0] a;`) reads the same way. Each section also carries every
comment that documents it: the lines above it, the comment beside it,
and the lines below it when nothing else could claim them — all three
at once where all three are written.
### Faster hover and navigation
A hover into a closed file reads that file once instead of twice (34 ms
→ 16.3 ms on a 31.7 MB file), and resolving a live declaration looks
its name up instead of walking every symbol in the buffer. Measurements
and how to reproduce them: `docs/perf/README.md`.
### Cursor-position answers stop walking the whole buffer
Expand-selection, on-type formatting, the completion scope gates and
the inline template trigger each used to scan every token in the file
to find the one at the cursor. They now binary-search for it: 77 µs →
20 ns in a 10 000-line buffer, and 130 µs → 36 ns for the widest of
them. No answer changed — each swap is pinned by a test that compares
it against the scan it replaced at every byte of the buffer.
The persistent index cache's record format changed to carry the new
span, so the first session after upgrading rebuilds its index rather
than reading the old store.
## 0.12.1 — 2026-08-27
Hover shows the cross-file declaration itself. A name declared in
+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.12.1"
version = "0.15.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.12.1"
version = "0.15.0"
[[package]]
name = "lucisv_server"
version = "0.12.1"
version = "0.15.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.12.1"
version = "0.15.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.12.1"
version = "0.15.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.12.1"
version = "0.15.0"
[[package]]
name = "vlog_refactor"
version = "0.12.1"
version = "0.15.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.12.1"
version = "0.15.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.12.1"
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
+242 -2
View File
@@ -149,8 +149,8 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
- [x] **[R] Parallel file processing.** ruff's speed story is embarrassing
parallelism over files. `main.rs` formats serially; use `rayon`
par_iter over the collected file list (formatting is already pure).
→ `crates/lucisv/src/main.rs`; pool sizing (8 MiB worker stacks, per the
recursion-limit handshake), the reworked panic hook and the
→ `crates/lucisv/src/main.rs`; pool sizing (`vlog_parser::PARSE_STACK_SIZE`
worker stacks, per the recursion-limit handshake), the reworked panic hook and the
ordered-reporting determinism argument in
`docs/features/parallel-files/README.md`. `--threads N` pins the worker
count; output is byte-identical at any count. 3.6× on 10 cores.
@@ -573,6 +573,44 @@ later:
written to a content-keyed store as a scan parses them, so the recompute a
*new session* would otherwise repeat is skipped instead — 1.8x on a whole
corpus rescan, and a scan interrupted halfway resumes where it stopped.
**A third piece answered without salsa, 2026-08-28**
(`docs/features/change-debounce/README.md`): the per-keystroke recompute a
query graph would have made unnecessary is instead *not started* — a burst
of `didChange`s is coalesced into one reanalysis. Still no query graph and
no dependency tracking; the salsa question remains open and deferred.
Measured costs for what a recompute actually is are now recorded in
`docs/perf/README.md`. **Round 2, 2026-08-28**
(`docs/features/interactive-latency/README.md`): that recompute is now
broken down stage by stage, and 79 % of it is lexing and parsing. If the
salsa question is ever reopened, that is the number it has to beat —
incremental *lexing and parsing*, not incremental queries over a whole-file
parse, and it lands squarely on `CLAUDE.md`'s hard invariants 1 and 2.
**A fourth piece answered without salsa, 2026-08-28**
(`docs/features/hover-line-index/README.md`): a derived fact a query used to
recompute — the *line* a declaration is written on, which cost a whole file
read and a whole `LineIndex` per request — is now computed once when the
file is indexed and stored beside the span (`Def::lines`, `FACTS_FORMAT`
3 → 4), and the one thing still needing that file's text is served from a
small bounded cache of closed files. A repeat hover into a 12 MB closed file
goes 5.75 ms → 0.95 µs; a whole scan is unchanged and the store grows 2.9 %.
Still no query graph: what is cached is a value, invalidated at four named
points, not a node in a dependency graph. **The larger number the same round
measured is not an incrementality problem at all**: the first request of a
session waits out the startup scan (780 ms cold, 287 ms warm), because
`Server::new` scans before the message loop starts. Filed there, not fixed.
→ **Fixed 2026-08-28** (`docs/features/scan-interleave/README.md`): the scan
is now per-file steps with the message queue drained between them, so a
startup scan of more than 64 files answers requests while it runs — 780 ms →
**15.5 ms** cold, 287 ms → **12.8 ms** warm, with the scan's own total moving
under a percent (860-file corpus: 351 → 353 ms cold, 187 → 189 ms warm). The
merge cost was measured first and ruled per-file feeding out: a merge is a
pass over the whole index, so one per file would have cost 631 ms of merging
on 200 files against 464 ms of parsing. Records are staged per file and folded
in with one `WorkspaceIndex::absorb` per *drain*, and a drain only happens
when a message is waiting — so a scan nobody is waiting on pays nothing.
Answers given mid-scan read the index as of that moment, and only the startup
scan gives them: a request queued behind a message that asked for a rescan
waits for that rescan, which is the order contract the loop always kept.
- [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version
bumped to 0.2.0 across the workspace and the extension, `tools/release.sh`
(release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and
@@ -610,11 +648,28 @@ section only tracks the milestones.
**the open files' own folders since 2026-08-27 (index-scope), with the
workspace walk behind `lucisv.index.scope: "workspace"`; the filelist
still outranks both. See `docs/features/index-scope/README.md`.**
**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. **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
@@ -721,6 +776,18 @@ and are not gaps.
publish — per notification. Advertised as `TextDocumentSyncOptions`
with the open/close and `save.includeText: false` values a bare `Kind`
already implied, so no client's save behavior moved.
**Amended 2026-08-28** (`docs/features/change-debounce/README.md`): a
`didChange` now only records the composed text; the reparse, the
generation bump and the publish happen at the next *flush* — the next
request, the next non-`didChange` notification, or a 150 ms quiet period —
so a typing burst costs one of each instead of one per keystroke. The
buffer's text is still exactly current after every notification; only its
analysis is deferred, and intermediate diagnostics states are no longer
published. **Measured 2026-08-28**
(`docs/features/interactive-latency/README.md`): a burst of ten keystrokes
over the wire produces exactly one `publishDiagnostics`, and a keystroke a
request follows — the shape a real editor sends — round-trips in 4.8 ms at
1 000 lines and 37 ms at 10 000.
- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native
format-on-save hook (client-side `editor.formatOnSave` already works;
this serves the editors without it).
@@ -780,6 +847,11 @@ and are not gaps.
persistent index cache logs `cached:` rather than `indexing:` and is counted
in the `end` message — `860 files indexed, 860 from cache` — so a rescan that
flew past says why.
→ **Extended once more, 2026-08-28**
(`docs/features/index-scope/README.md`): a file that went into the index from
an open buffer's own finished analysis — no parse, no store — logs
`analyzed:` and adds nothing to the `end` message, so "from cache" still
means the persistent store alone.
→ **The other half of the size story, 2026-08-27**
(`docs/features/large-file-mode/README.md`): the walk cap covers files
nobody opened, and `lucisv.largeFile.threshold` (4 MiB) now covers the file
@@ -1056,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).
+37 -11
View File
@@ -32,12 +32,7 @@ use lucisv_core::config::Discovery;
use lucisv_core::filelist;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
/// input that trips the parser's nesting limit; rayon's own default is
/// 2 MiB, which would put that crash back.
const WORKER_STACK: usize = 8 * 1024 * 1024;
use vlog_parser::PARSE_STACK_SIZE;
fn main() -> ExitCode {
let opts = match args::parse() {
@@ -50,10 +45,40 @@ fn main() -> ExitCode {
// Once, before any worker thread exists, so nothing ever races on it.
install_panic_hook();
// Nothing parses on the main thread, because its stack is not ours to
// state: 8 MiB on a stock macOS or Linux, whatever `ulimit -s` says in a
// container, 1 MiB on Windows. The parser's nesting limit only turns
// over-deep input into an error on a stack of at least
// `PARSE_STACK_SIZE` — below that the overflow, which aborts the
// process, comes first. A thread we spawn is the one stack whose size is
// ours to guarantee. The pool's workers cover the file-at-a-time paths
// (`build_pool`), but not the ones that never reach it: `-` reads and
// formats a buffer right here, and so does `lucisv check -`.
let spawned = std::thread::Builder::new()
.name("lucisv".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || run(&opts));
let handle = match spawned {
Ok(handle) => handle,
Err(e) => {
eprintln!("error: could not start the worker thread: {e}");
return ExitCode::from(2);
}
};
match handle.join() {
Ok(code) => code,
// An uncontained panic, already printed by the hook above. 101 is
// what the same panic on the main thread would have exited with.
Err(_) => ExitCode::from(101),
}
}
/// The run itself, on the stack `main` sized for it.
fn run(opts: &Options) -> ExitCode {
match opts.command {
Command::Format if opts.is_stdin() => run_stdin(&opts),
Command::Format => run_files(&opts),
Command::Check => run_check(&opts),
Command::Format if opts.is_stdin() => run_stdin(opts),
Command::Format => run_files(opts),
Command::Check => run_check(opts),
}
}
@@ -272,11 +297,12 @@ fn entry_for(content: u64, config: &Config) -> Entry {
}
/// Builds rayon's global pool. Worker stacks are sized for the parser's
/// recursion limit (see `WORKER_STACK`); `--threads 0` lets rayon pick.
/// recursion limit (`PARSE_STACK_SIZE` — rayon's own default is 2 MiB, which
/// would put the overflow back); `--threads 0` lets rayon pick the count.
fn build_pool(opts: &Options) -> Result<(), String> {
rayon::ThreadPoolBuilder::new()
.num_threads(opts.thread_count())
.stack_size(WORKER_STACK)
.stack_size(PARSE_STACK_SIZE)
.build_global()
.map_err(|e| format!("could not start the worker pool: {e}"))
}
+30 -1
View File
@@ -407,7 +407,8 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
// costs two levels), so it parses — and needs several MiB of stack to
// do it in a debug build: without the depth limit this family died at
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
// stack. This test crashes the process if the pool's 8 MiB is dropped.
// stack. This test crashes the process if the pool's `PARSE_STACK_SIZE`
// is dropped.
let deep = format!(
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
"if (clk) begin\n".repeat(28),
@@ -425,6 +426,34 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
}
#[test]
fn a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash() {
// The stdin path never touches the worker pool: it formats on the thread
// `main` spawned, which is the only stack whose size lucisv gets to
// state. 500 nested blocks are far past the parser's limit, so the run
// must end with an ordinary parse error — and not with a SIGABRT, which
// is what an unstated stack gives instead.
let deep = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(500),
"end\n".repeat(500)
);
let out = run_with_stdin(&["-"], &deep);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("nesting too deep"), "{}", stderr(&out));
assert!(stdout(&out).is_empty(), "a rejected buffer prints nothing: {}", stdout(&out));
// And the deepest *legal* buffer formats on that same stack.
let legal = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(58),
"end\n".repeat(58)
);
let out = run_with_stdin(&["-"], &legal);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stdout(&out).contains("endmodule"), "{}", stdout(&out));
}
#[test]
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
let dir = TempDir::new("configpar");
+292 -28
View File
@@ -24,7 +24,7 @@ use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_parser::token::TokenKind;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use vlog_semantic::{SymbolKind, WorkspaceIndex};
@@ -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
@@ -71,14 +80,26 @@ impl Candidates {
/// `sources` is the list `Workspace::collect_sources` already produced for
/// the index, so the files are read once and the only extra work is one
/// lex per file — see the measurements in the feature README.
pub fn build(index: &WorkspaceIndex, sources: &[(PathBuf, String)]) -> Candidates {
let mut out = Candidates {
units: units_of(index),
macros: macros_of(index),
..Candidates::default()
};
///
/// `known` holds the words of the files whose token stream the caller
/// already has — an open buffer's, lexed when the buffer was analyzed. A
/// file listed there is not lexed again; a file absent from it is lexed
/// here, exactly as every file used to be. The two produce the same words
/// because they are the same function over the same tokens
/// ([`words_of_tokens`]).
pub fn build(
index: &WorkspaceIndex,
sources: &[(PathBuf, String)],
mut known: HashMap<PathBuf, Vec<String>>,
) -> Candidates {
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 = words_in(text);
let words = match known.remove(path) {
Some(words) => words,
None => words_in(text),
};
for word in &words {
*out.word_files.entry(word.clone()).or_default() += 1;
}
@@ -101,36 +122,82 @@ impl Candidates {
/// so nothing else is re-lexed. The result is what a whole
/// [`Candidates::build`] over the same files would have produced.
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
self.units = units_of(index);
self.update_words(index, path, words_in(text));
}
/// [`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, self.modules) = index_tables(index);
self.macros = macros_of(index);
self.set_words(path, words);
}
/// [`Candidates::update_words`] for a batch of files — the form a scan
/// publishing what it has indexed so far uses.
///
/// One re-derivation of the two index tables for the whole batch rather
/// 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.count_words(&path, words, &mut touched);
}
self.merge_words(touched);
(self.units, self.modules) = index_tables(index);
self.macros = macros_of(index);
self.set_words(path, words_in(text));
}
/// 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() {
@@ -138,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)
@@ -154,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 {
@@ -177,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:
@@ -209,11 +342,26 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
/// orders of magnitude more identifier *tokens* than distinct identifiers
/// (900k against 17k over this repo's corpus), and copying every one of them
/// only to sort the copies away costs more than the lexing does.
fn words_in(text: &str) -> Vec<String> {
///
/// `pub(crate)` because a scan lexes each file as it reaches it rather than in
/// one pass at the end: no part of a scan may be longer than one file, or the
/// message queue goes unanswered for the length of it
/// (`docs/features/scan-interleave/README.md`).
pub(crate) fn words_in(text: &str) -> Vec<String> {
// A file that does not lex contributes nothing rather than being guessed
// at with a regex — the same all-or-nothing rule the lexer gives every
// other consumer.
let Ok(tokens) = tokenize(text) else { return Vec::new() };
words_of_tokens(&tokens)
}
/// [`words_in`] over a token stream the caller already lexed.
///
/// The whole of `words_in` after the lex, so a caller holding an open buffer's
/// tokens gets the same words without lexing the buffer again. A buffer that
/// did not lex holds no tokens and contributes nothing here either, which is
/// the same all-or-nothing rule from the other side.
pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec<String> {
let mut seen: HashSet<String> = HashSet::new();
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
if !seen.contains(token.text.as_str()) {
@@ -272,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()
@@ -289,7 +448,7 @@ mod tests {
fn built(files: &[(&str, &str)]) -> Candidates {
let sources = sources(files);
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
Candidates::build(&index, &sources)
Candidates::build(&index, &sources, HashMap::new())
}
#[test]
@@ -396,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
// ------------------------------------------------------------------
@@ -408,7 +595,7 @@ mod tests {
];
let srcs = sources(&raw);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut candidates = Candidates::build(&index, &srcs);
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
assert_eq!(candidates.words("shared").len(), 1, "premise: two files, one word");
let mut current = index.clone();
@@ -431,7 +618,7 @@ mod tests {
let raw = [("/rtl/a.sv", "module a;\n logic w1;\nendmodule\n")];
let srcs = sources(&raw);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut candidates = Candidates::build(&index, &srcs);
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
let mut current = index.clone();
let text2 = "module a;\n logic w2;\nendmodule\n";
@@ -451,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");
}
}
+498 -9
View File
@@ -33,11 +33,11 @@ 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;
use crate::state::{Document, Workspace};
use crate::state::{first_token_from, Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::{self, Gate, Template};
@@ -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) {
@@ -849,9 +996,12 @@ fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)>
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
/// `generate begin` reaches `generate`. Whichever comes first decides.
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
let Some(begin) = tokens.iter().position(|token| token.span.start == offset) else {
// A token starting exactly at `offset` is the first one that starts at or
// after it: every earlier token starts before, every later token after.
let begin = first_token_from(tokens, offset);
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
return false;
};
}
for token in tokens[..begin].iter().rev() {
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
return true;
@@ -866,7 +1016,11 @@ fn is_procedural(tokens: &[Token], offset: u32) -> bool {
/// Whether every parenthesis opened between `from` and `at` was closed again.
fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
let mut depth = 0i32;
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
// The tokens whose start falls in `[from, at)` are a contiguous run,
// because starts rise across the vector — so the filter this replaced was
// reading the whole buffer to reach a window the two bounds name outright.
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
for token in &tokens[window] {
if token.kind != TokenKind::Symbol {
continue;
}
@@ -898,6 +1052,49 @@ module sub #(
endmodule
";
/// [`is_procedural`] used to sweep the vector for the token starting at
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
/// two offsets name. Both now binary-search; both must answer exactly what
/// the sweeps answered, at every byte and for every window.
#[test]
fn the_scope_gates_answer_what_their_sweeps_answered() {
let text = crate::state::mixed_buffer(20);
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
let tokens = &doc.tokens;
for offset in 0..=text.len() as u32 {
let swept = tokens.iter().position(|token| token.span.start == offset);
let searched = {
let begin = first_token_from(tokens, offset);
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
};
assert_eq!(swept, searched, "the token starting at {offset}");
}
// Every `begin`/`end` opener in the buffer against a spread of cursors
// after it: the two bounds are what pick the window out.
let openers: Vec<u32> = tokens
.iter()
.filter(|t| t.text == "begin" || t.text == "(")
.map(|t| t.span.end)
.collect();
assert!(openers.len() > 20, "premise: plenty of windows to check");
for from in openers {
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
let mut depth = 0i32;
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
if token.kind != TokenKind::Symbol {
continue;
}
match token.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
_ => {}
}
}
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
}
}
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
@@ -990,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");
+580 -76
View File
@@ -15,7 +15,6 @@ use vlog_parser::token::Token;
use vlog_parser::{LineIndex, TextRange};
use vlog_semantic::{Def, Definition, FileId, Symbol};
use crate::convert::Positions;
use crate::expand::{self, Expansion};
use crate::locate::{display_name, line_number};
use crate::nav::indexed_def_for_symbol;
@@ -182,16 +181,45 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
let mut parts = Vec::with_capacity(defs.len());
for def in defs {
let label = kind_label(def.kind);
let where_ = ws
.index()
.path(def.file)
.map(|path| match line_number(ws, path, def.name_span.start) {
Some(line) => format!("{}:{line}", display_name(path)),
None => display_name(path),
})
.unwrap_or_else(|| "the workspace".to_string());
let path = ws.index().path(def.file).map(|p| p.to_path_buf());
let mut where_ = None;
let mut snippet = None;
if let Some(path) = path.as_ref() {
if ws.document_for_path(path).is_some() {
// The live path reads the open buffer — `live_symbol`
// resolves the current span, and its guards stay. The
// line comes from that buffer's own index rather than
// from `def.lines`, because the buffer may hold
// unsaved edits the index has not seen.
where_ = line_number(ws, path, def.name_span.start)
.map(|line| format!("{}:{line}", display_name(path)));
snippet = name.and_then(|name| declaration_snippet(ws, def, name));
} else {
// The heading costs nothing: the line was recorded
// when the file was indexed, from the same text the
// span came from (`vlog_semantic::DeclLines`). Only
// the snippet still wants the file's text, and that
// comes from the workspace's shared view — one read
// per file per generation, so a card naming one file
// twice, and the next hover into it, are both free.
where_ = Some(format!("{}:{}", display_name(path), def.lines.name));
snippet = name.zip(ws.file_view(path)).and_then(|(name, view)| {
spells_exactly(&view.text, def.name_span, name)
.then(|| {
fenced_sections(
&view.text,
&view.lines,
def.name_span,
def.detail_span,
)
})
.flatten()
});
}
}
let where_ = where_.unwrap_or_else(|| "the workspace".to_string());
let mut part = format!("**{label}** — declared in `{where_}`");
if let Some(snippet) = name.and_then(|name| declaration_snippet(ws, def, name)) {
if let Some(snippet) = snippet {
part.push_str(&snippet);
}
parts.push(part);
@@ -201,15 +229,150 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
}
}
/// A local declaration: what it is, and the lines it was written on.
/// A local declaration: what it is, and the lines it was written on — with
/// the comment that documents those lines attached (`attached_lines`). A
/// non-ANSI port is named in the header and *finished* in the body
/// (`input signed [31:0] data_in;`), so its card has two sections: the
/// header's, then the body's, each carrying its own comment.
fn local_text(doc: &Document, symbol: &Symbol) -> String {
let snippet = doc.positions().whole_lines(symbol.decl_span);
format!(
"**{}** `{}`\n\n```systemverilog\n{}\n```",
kind_label(symbol.kind),
symbol.name,
snippet.trim_end()
)
let head = format!("**{}** `{}`\n\n", kind_label(symbol.kind), symbol.name);
let body = fenced_sections(&doc.text, &doc.line_index, symbol.decl_span, symbol.detail_span)
.unwrap_or_default();
format!("{head}{body}")
}
/// The fenced half of a hover card: one section for a declaration complete
/// where it is named, two — header, then body detail — for a non-ANSI split
/// port. Each section is the declaration's own lines plus its attached
/// comment, cut to card size independently.
fn fenced_sections(
text: &str,
index: &LineIndex,
primary: TextRange,
detail: Option<TextRange>,
) -> Option<String> {
let section = |span: TextRange| fenced(&attached_lines(text, index, span)).unwrap_or_default();
let first = section(primary);
let second = detail.map(section).filter(|s| !s.is_empty());
let joined = match second {
Some(second) if !first.is_empty() => format!("{first}\n\n{second}"),
Some(second) => second,
None => first,
};
(!joined.is_empty()).then_some(joined)
}
// ----------------------------------------------------------------------
// comments attached to a declaration
// ----------------------------------------------------------------------
/// The lines a declaration was written on, plus every comment that documents
/// it, in source order. The three sources are independent — a declaration can
/// carry all three at once:
///
/// * a comment on the declaration's own line is already in those lines;
/// * the comment-only lines directly **above** attach — the walk stops at the
/// first line that is not comment-only, so a line carrying another port
/// (and its trailing comment) never contributes;
/// * the comment-only lines directly **below** attach, provided nothing else
/// could claim them: the first line after the block must be one
/// `only_a_closer_on` positively recognises, or the end of the file.
///
/// Only `//` lines and `/* ... */` complete on one line count; the interior
/// of a multi-line block comment is indistinguishable from code without
/// lexing, and a hover card that guessed would be the wrong-line lie the
/// snippet guards exist to prevent.
fn attached_lines(text: &str, index: &LineIndex, span: TextRange) -> String {
let Some((first, last)) = section_lines(index, span) else {
return String::new();
};
let line = |n: u32| {
index
.line_range(n)
.and_then(|r| text.get(r.start as usize..r.end as usize))
// A line's range ends before its `\n` but *after* the `\r` a CRLF
// file puts in front of it, which would land in the middle of the
// card's fenced block. Display text only; the buffer is untouched.
.map(|line| line.strip_suffix('\r').unwrap_or(line))
};
let decl: Vec<&str> = (first..=last).map(|n| line(n).unwrap_or("")).collect();
let mut above: Vec<&str> = Vec::new();
let mut n = first.saturating_sub(1);
while n >= 1 && comment_only(line(n).unwrap_or("")) {
above.push(line(n).unwrap_or(""));
n -= 1;
}
let mut below: Vec<&str> = Vec::new();
let mut n = last + 1;
while comment_only(line(n).unwrap_or("")) {
below.push(line(n).unwrap_or(""));
n += 1;
}
// The guard on the below half: the block is this declaration's only when
// the line after it cannot be another declaration — a closer, or the end
// of the file, where nothing follows to claim it. Anything else, a
// wrapped declaration's bare `input` included, is another declaration's
// leading comment.
let claimed_by_nothing_else = match line(n) {
Some(next) => only_a_closer_on(next),
None => true,
};
if !claimed_by_nothing_else {
below.clear();
}
above.into_iter().rev().chain(decl).chain(below).collect::<Vec<_>>().join("\n")
}
/// The 1-based (first, last) line numbers a span's lines cover.
fn section_lines(index: &LineIndex, span: TextRange) -> Option<(u32, u32)> {
if span.end <= span.start {
return None;
}
let first = index.line_col(span.start).0;
let last = index.line_col(span.end - 1).0;
Some((first, last))
}
/// Whether a line is nothing but a comment.
fn comment_only(line: &str) -> bool {
let trimmed = line.trim();
trimmed.starts_with("//")
|| (trimmed.starts_with("/*") && trimmed.ends_with("*/") && trimmed.len() >= 4)
}
/// Whether a line carries nothing but a closer — the only shape that lets a
/// comment block above it belong to the declaration *before* it.
///
/// The question a below-comment asks is "could anything after this block
/// claim it?", and the only honest textual answer is a whitelist: a line is
/// safe when every word on it is a block terminator, which includes a line
/// with no words at all (`);`, a blank line, punctuation). Everything else —
/// a name, a direction keyword, the bare `input` a *wrapped* declaration
/// begins with — reads as another declaration and the comment stays with it.
///
/// The bias is the point. This is textual on purpose: the disk path of a
/// cross-file hover has no parse to ask, and only a false "another
/// declaration is here" is safe, because it merely declines to attach a
/// comment — the direction that cannot lie. A false "nothing here" shows one
/// declaration's comment on another's card, which is the one thing this
/// feature promises never to do.
fn only_a_closer_on(line: &str) -> bool {
let code = match line.find("//") {
Some(at) => &line[..at],
None => line,
};
code.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
.filter(|word| !word.is_empty())
.all(is_closer_word)
}
/// The words that end a block a declaration can live in, and nothing else:
/// what a comment block below a *last* declaration is followed by.
fn is_closer_word(word: &str) -> bool {
matches!(word, "end" | "endmodule" | "endinterface" | "endtask" | "endfunction")
}
// ----------------------------------------------------------------------
@@ -221,53 +384,55 @@ fn local_text(doc: &Document, symbol: &Symbol) -> String {
const SNIPPET_LINES: usize = 5;
const SNIPPET_CHARS: usize = 400;
/// The source of a declaration in another file, fenced for the card.
/// The source of a declaration in an **open** buffer, fenced for the card.
///
/// The index holds only `{file, name_span, kind}` and no text
/// (`docs/features/workspace-index/README.md`), so the line is fetched here,
/// at hover time, from whichever text the span is actually valid against.
/// The index holds spans, kinds and lines but no text
/// (`docs/features/workspace-index/README.md`), so the *source* is fetched
/// here, at hover time, from whichever text the span is actually valid
/// against. A closed file is served by `Workspace::file_view` in the caller
/// instead, so this function never touches the disk.
///
/// `None` — no snippet, today's card unchanged — wherever the two could
/// disagree: an unreadable file, a span the text does not cover, or a span
/// covering something other than the name that was hovered. A hover that
/// prints the wrong line is worse than one that prints none.
/// disagree: the span the live buffer does not cover, or a span covering
/// something other than the name that was hovered. A hover that prints the
/// wrong line is worse than one that prints none.
fn declaration_snippet(ws: &Workspace, def: &Def, name: &str) -> Option<String> {
// The file is open, so the index's span is against its *last saved*
// text and an unsaved edit above the declaration has already moved it.
// Find the same declaration logically instead, exactly as `nav.rs`
// does, and read the live buffer at the live span.
let path = ws.index().path(def.file)?;
match ws.document_for_path(path) {
// The file is open, so the index's span is against its *last saved*
// text and an unsaved edit above the declaration has already moved it.
// Find the same declaration logically instead, exactly as `nav.rs`
// does, and read the live buffer at the live span.
Some(target) => {
let symbol = live_symbol(ws, target, def, name)?;
if !spells_exactly(&target.text, symbol.name_span, name) {
return None;
}
fenced(target.positions().whole_lines(symbol.decl_span))
}
// Not open: disk text is what the index was built from, so the
// recorded span is the one to trust.
None => {
let text = ws.text_of(path)?;
if !spells_exactly(&text, def.name_span, name) {
return None;
}
let index = LineIndex::new(&text);
fenced(Positions::new(&text, &index).whole_lines(def.name_span))
}
let target = ws.document_for_path(path)?;
let symbol = live_symbol(ws, target, def, name)?;
if !spells_exactly(&target.text, symbol.name_span, name) {
return None;
}
fenced_sections(
&target.text,
&target.line_index,
symbol.decl_span,
symbol.detail_span.or(def.detail_span),
)
}
/// The live symbol in an open buffer that *is* this indexed declaration.
///
/// Only the declarations spelling `name` are probed — `indexed_def_for_symbol`
/// is two index lookups per candidate, and every other symbol in the buffer
/// was going to fail the name test anyway. `symbols_named` hands them over in
/// declaration order, so the first-match tie-break between two live
/// declarations of one name is the one the old whole-buffer scan made.
fn live_symbol<'a>(
ws: &Workspace,
target: &'a Document,
def: &Def,
name: &str,
) -> Option<&'a Symbol> {
target.semantics.symbols().iter().find(|symbol| {
symbol.name == name && indexed_def_for_symbol(ws, target, symbol) == Some(def)
})
target
.semantics
.symbols_named(name)
.filter_map(|id| target.semantics.symbol(id))
.find(|symbol| indexed_def_for_symbol(ws, target, symbol) == Some(def))
}
/// The text a span covers, or `None` when the span is not inside `text` on
@@ -708,6 +873,254 @@ mod tests {
);
}
// ------------------------------------------------------------------
// non-ANSI split ports: two sections, each with its comment
// ------------------------------------------------------------------
const SPLIT: &str = "\
module alu (
// the operand
data_in,
result // the result
);
input signed [31:0] data_in; // 32-bit operand A
output reg [63:0] result;
endmodule
";
#[test]
fn a_split_port_hovers_as_two_sections_with_their_comments() {
// The same card from both places the port is declared: the header
// name and the body declaration.
let (ws, uri) = document(SPLIT);
for needle in ["data_in,", "data_in;"] {
let body = text_of(&hover(&ws, &uri, at(SPLIT, needle)).expect("hover"));
assert!(body.contains("**port** `data_in`"), "the heading: {needle:?} -> {body}");
// Section one: the header, with the comment-only line above it.
assert!(
body.contains("```systemverilog\n // the operand\n data_in,\n```"),
"the header section, comment attached: {needle:?} -> {body}"
);
// Section two: the body declaration, with its same-line comment.
assert!(
body.contains(
"```systemverilog\ninput signed [31:0] data_in; // 32-bit operand A\n```"
),
"the detail section, comment included: {needle:?} -> {body}"
);
// Two sections, not one merged block: two fences for one card.
assert!(
body.matches("```systemverilog").count() >= 2,
"two fenced sections: {needle:?} -> {body}"
);
}
}
#[test]
fn a_comments_below_a_declaration_attach_only_when_no_port_follows_them() {
// Below-comments attach when only the closer follows them (nothing
// else could they document)…
let below = "module alu (data_in);\ninput [7:0] data_in;\n// the operand\nendmodule\n";
let (ws, uri) = document(below);
let body = text_of(&hover(&ws, &uri, at(below, "data_in;")).expect("hover"));
assert!(
body.contains("input [7:0] data_in;\n// the operand"),
"a comment under the last declaration is attached: got {body}"
);
// …but a comment block sitting just above the *next* port's
// declaration is that port's leading comment, not this one's.
let stolen = "module alu (data_in, result);\ninput [7:0] data_in;\n// about result\noutput result;\nendmodule\n";
let (ws, uri) = document(stolen);
let body = text_of(&hover(&ws, &uri, at(stolen, "data_in,")).expect("hover"));
assert!(
!body.contains("// about result"),
"the next port's leading comment is not stolen: got {body}"
);
// …and it does reach the port it documents.
let body = text_of(&hover(&ws, &uri, at(stolen, "result;") + 1).expect("hover"));
assert!(body.contains("// about result"), "attached to its own port: got {body}");
}
#[test]
fn an_old_style_task_argument_hovers_as_two_sections_too() {
// QA, PDS-3: a task or function argument named in the header and
// finished in the body is the same split shape a module port is, and
// now gets the same two-section card.
let text = "\
module m;
// the operand
task t(a);
input [7:0] a; // 8 bits wide
$display(a);
endtask
endmodule
";
let (ws, uri) = document(text);
for needle in ["a);", "a; //"] {
let body = text_of(&hover(&ws, &uri, at(text, needle)).expect("hover"));
assert!(
body.contains("```systemverilog\n // the operand\n task t(a);\n```"),
"the header section: {needle:?} -> {body}"
);
assert!(
body.contains("```systemverilog\n input [7:0] a; // 8 bits wide\n```"),
"the body declaration's section: {needle:?} -> {body}"
);
}
}
#[test]
fn a_wrapped_next_declaration_keeps_its_own_leading_comment() {
// QA, PDS-1: the guard used to ask whether the line after a
// below-comment carried an identifier the port grammar could not
// account for. A declaration that *wraps*, with its direction keyword
// alone on the first line, carries no such identifier there — so the
// guard read "no other port here" and handed `result`'s comment to
// `data_in`. Only a line positively recognised as a closer may let a
// comment through now.
let wrapped = "\
module alu (data_in, result);
input [7:0] data_in;
// about result
input
[7:0] result;
endmodule
";
let (ws, uri) = document(wrapped);
let body = text_of(&hover(&ws, &uri, at(wrapped, "data_in;")).expect("hover"));
assert!(
!body.contains("// about result"),
"a wrapped next declaration's comment is not stolen: got {body}"
);
// …and it reaches the port it was written for, above its own lines.
let body = text_of(&hover(&ws, &uri, at(wrapped, "result;")).expect("hover"));
assert!(
body.contains("// about result\ninput\n [7:0] result;"),
"attached above the wrapped declaration it documents: got {body}"
);
}
#[test]
fn a_wrapped_declaration_keeps_the_comment_below_it() {
// The other half of PDS-1: a wrapped declaration that really is the
// last one still takes the comment under it, because what follows the
// comment is a closer.
let text = "\
module alu (data_in);
input
[7:0] data_in;
// the operand
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover"));
assert!(
body.contains("input\n [7:0] data_in;\n// the operand"),
"the last, wrapped declaration takes the comment below it: got {body}"
);
}
#[test]
fn a_declaration_shows_the_comments_above_beside_and_below_it_at_once() {
// The owner's rule reads the three sources independently: same line,
// above, below. QA, PDS-2 — the implementation used to run a priority
// chain, so an above-comment or a trailing one silently suppressed
// the block below even when nothing else could claim it.
let text = "\
module alu (data_in);
// above
input [7:0] data_in; // beside
// below
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover"));
assert!(
body.contains("// above\ninput [7:0] data_in; // beside\n// below"),
"all three comments, in source order: got {body}"
);
}
#[test]
fn a_header_port_shows_the_comments_above_and_below_it_at_once() {
// PDS-2's own repros, both in one header: an above-comment (repro 1)
// and a same-line trailing comment (repro 2) each used to suppress
// the block below, which only `);` follows.
let text = "\
module alu (
// above
data_in, // beside
// below
result
);
input [7:0] data_in;
input result;
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in,")).expect("hover"));
// `result` follows the block, so it is `result`'s comment, not this
// port's — the guard stays exactly as strict as it was.
assert!(!body.contains("// below"), "another port's comment is not stolen: got {body}");
assert!(
body.contains(" // above\n data_in, // beside"),
"above and beside both attach: got {body}"
);
// With nothing but the closer after it, the same block does attach.
let last = "\
module alu (
// above
data_in // beside
// below
);
input [7:0] data_in;
endmodule
";
let (ws, uri) = document(last);
let body = text_of(&hover(&ws, &uri, at(last, "data_in ")).expect("hover"));
assert!(
body.contains(" // above\n data_in // beside\n // below"),
"all three attach when only the closer follows: got {body}"
);
}
#[test]
fn the_line_above_a_header_port_does_not_leak_its_trailing_comment() {
// `result, // the result` above `data_in`'s own line: the line above
// carries another port, so its trailing comment stays result's.
let text = "\
module alu (
result, // the result
data_in
);
input [7:0] data_in;
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in\n")).expect("hover"));
assert!(!body.contains("the result"), "not the port above's comment: got {body}");
}
#[test]
fn a_cross_file_split_port_shows_both_sections() {
let sub = "module sub (\n addr,\n ready\n);\ninput logic [15:0] addr;\noutput ready;\nendmodule\n";
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("splitx", &[("sub.sv", sub), ("top.sv", top)]);
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(
body.contains("```systemverilog\n addr,\n```"),
"the header section, from the index's spans: got {body}"
);
assert!(
body.contains("```systemverilog\ninput logic [15:0] addr;\n```"),
"the detail section, from the index's detail span: got {body}"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn hovering_a_declaration_shows_its_own_info() {
let text = "module top;\n wire a;\nendmodule\n";
@@ -772,6 +1185,92 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read() {
// The round's central claim: `file:line` for an indexed declaration is
// `Def::lines`, recorded when the file was scanned, so the heading
// costs no read at all. Proved by removing the file from under the
// index — a heading that still names the line cannot have read it.
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("headingfromindex", &[("sub.sv", PORTS), ("top.sv", top)]);
fs::remove_file(dir.join("sub.sv")).expect("remove");
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(body.contains("**port** — declared in `sub.sv:2`"), "got {body}");
// The snippet is the half that really wanted the text, and it is
// dropped rather than guessed at — exactly as it always was for a
// file that cannot be read.
assert!(!body.contains("```systemverilog"), "no snippet without text: got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_second_hover_into_one_closed_file_reads_nothing() {
// The other half: the snippet's read is shared through
// `Workspace::file_view`, so the file is read once and the next hover
// into it — the same card, or another name in the same file — is
// served from what that read left behind. Observed the only honest
// way: rewrite the file behind the server's back and require the
// second card to be the first one. Stale text can only ever *omit* a
// snippet (the `spells_exactly` guard), never show a wrong line.
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("viewshared", &[("sub.sv", PORTS), ("top.sv", top)]);
let first = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(first.contains("input logic [7:0] addr"), "premise: got {first}");
fs::write(dir.join("sub.sv"), "module sub (\n input logic [15:0] addr\n);\nendmodule\n")
.expect("write");
let second = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert_eq!(second, first, "the second hover did not read the file again");
let _ = fs::remove_dir_all(&dir);
}
/// QA (2026-08-28): the staleness window the README's Assumptions section
/// claims — "a line is a fact about the same snapshot the span is... where
/// the file has changed on disk with nothing telling the server, both are
/// stale together" — reproduced rather than taken on faith, and in the
/// one shape that could actually disagree: the index was built from the
/// *original* `sub.sv`, but `sub.sv` is rewritten on disk — no `didSave`,
/// no watcher event, no `update_one`/`rebuild_index` call, so the index is
/// never told — **before the view cache ever reads it**, so the first
/// hover's disk read sees the *new* bytes under the *old* span and offset.
/// The heading must still show the line the index recorded at the last
/// scan (stale, not a fresh-read line the index never computed), and the
/// snippet, reading the genuinely current text, must find the old span no
/// longer spells `addr` there and drop itself via `spells_exactly` rather
/// than show whatever now sits at that byte range.
#[test]
fn an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet() {
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("staleheading", &[("sub.sv", PORTS), ("top.sv", top)]);
// Edited behind the server's back, before any hover has read this
// file at all: four lines inserted above the module, so `addr`'s true
// line is now 6 — and the byte offset the index still holds for it
// (from the *original* `sub.sv`) now lands inside a comment, not
// `addr`. The view cache is empty for this path, so the hover below
// is a genuinely fresh disk read of the edited bytes.
fs::write(
dir.join("sub.sv"),
"// one\n// two\n// three\n// four\nmodule sub (\n input logic [7:0] addr,\n\
\x20 output logic ready\n);\nendmodule\n",
)
.expect("write");
let after = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(
after.contains("**port** — declared in `sub.sv:2`"),
"the heading must show the line the index recorded, not the file's true current \
line (6), until something reindexes it: got {after}"
);
assert!(
!after.contains("```systemverilog"),
"the snippet must be dropped, not show the comment the stale span now lands on: \
got {after}"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_package_member_shows_its_declaration_line() {
let pkg =
@@ -1142,18 +1641,15 @@ mod qa_hover_declarations {
let _ = fs::remove_dir_all(&dir);
}
/// Angle 2 (CRLF): a multi-line snippet from a CRLF file keeps the `\r`
/// on every line except the last, where `cut_to_size`'s `trim_end`
/// strips it. `local_text` (the in-file branch) has the same property —
/// this is not new to this round, but it is real: the fenced block for a
/// module header spanning multiple CRLF lines carries an embedded `\r`
/// before an interior `\n`. Cosmetic (most renderers show a fenced block
/// verbatim, so a stray `\r` is invisible or a non-issue in practice),
/// not a correctness break — filed as a low-severity finding rather than
/// a masked-corruption risk, since the text shown is still exactly the
/// bytes on disk.
/// Angle 2 (CRLF): a multi-line snippet from a CRLF file used to keep the
/// `\r` on every line except the last, where `cut_to_size`'s `trim_end`
/// stripped it — an embedded control character in the middle of a fenced
/// block. QA filed it (hover-declarations finding 2, port-detail-spans
/// PDS-4); `attached_lines` now strips the carriage return as it composes
/// each line, so the fence holds `\n`-separated lines whatever the file's
/// line endings are. Display text only: nothing writes to the buffer.
#[test]
fn a_crlf_multiline_snippet_keeps_interior_carriage_returns() {
fn a_crlf_multiline_snippet_carries_no_carriage_returns() {
// `wide`'s `decl_span` is its whole body (a module, like `PORTS` in
// the dev's own tests), so its live-path snippet spans several CRLF
// lines and is exactly where an interior, un-trimmed `\r` would show.
@@ -1172,9 +1668,10 @@ mod qa_hover_declarations {
let body = text_of(&hover(&ws, &uri, at(top, "wide u")).expect("hover"));
assert!(body.contains("module wide ("), "got {body:?}");
assert!(!body.contains('\r'), "no carriage return survives into the card: got {body:?}");
assert!(
body.contains("wire w0;\r\n"),
"an interior CRLF line keeps its \\r inside the fence: got {body:?}"
body.contains("module wide (\n input logic a\n);\n wire w0;"),
"the lines read as written, joined with plain newlines: got {body:?}"
);
let _ = fs::remove_dir_all(&dir);
}
@@ -1310,19 +1807,21 @@ mod qa_hover_declarations {
let _ = fs::remove_dir_all(&dir);
}
/// Angle 7 (perf smell): a hover resolving into a large *closed* file
/// reads the whole file from disk and builds a fresh `LineIndex` over it
/// — twice, once inside `locate::line_number` for the heading and once
/// inside `declaration_snippet` for the snippet, since neither shares the
/// other's read. Not a correctness bug (hover is a rare, single-shot
/// request, and `text_of`/`LineIndex::new` are linear), but a measurable,
/// avoidable doubling of I/O and scan work on every disk-path hover.
/// Ignored by default (it writes/reads ~30 MB and just measures); run
/// with `cargo test --release -p lucisv_server large_closed -- --ignored
/// --nocapture` to see the number.
/// Angle 7 (perf smell): the **first** hover resolving into a large
/// *closed* file reads the whole file from disk and builds a fresh
/// `LineIndex` over it. It once did that twice — heading and snippet
/// independently — then once, through a per-hover memo, and since
/// `hover-line-index` (2026-08-28) it does it once *per file per
/// generation of that file*: the heading no longer wants any text at all
/// (`Def::lines`), and the snippet's read is held in
/// `Workspace::file_view` for the next hover. So this number is the first
/// touch, which is the one that still costs; the repeat is measured in
/// `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`. Not a
/// correctness assertion, just the number; run with `cargo test --release
/// -p lucisv_server large_closed -- --ignored --nocapture` to see it.
#[test]
#[ignore = "perf measurement, not a correctness assertion — see QA log"]
fn hovering_into_a_large_closed_file_reads_it_twice() {
fn hovering_into_a_large_closed_file_reads_it_once() {
let dir = temp_dir("bigfile");
let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n");
for n in 0..600_000 {
@@ -1350,10 +1849,15 @@ mod qa_hover_declarations {
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
let elapsed = start.elapsed();
assert!(body.contains("[7:0] addr"), "got {body}");
let start = std::time::Instant::now();
let _ = hover(&ws, &uri, at(top, "addr(8")).expect("hover");
let again = start.elapsed();
eprintln!(
"hover into a {:.1} MB closed file took {:?} (reads the file + builds a LineIndex twice)",
"hover into a {:.1} MB closed file took {:?} the first time (one read + one \
LineIndex, for the snippet alone) and {:?} the second (nothing read)",
sub.len() as f64 / 1_000_000.0,
elapsed
elapsed,
again
);
let _ = fs::remove_dir_all(&dir);
}
+141 -21
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,25 +138,79 @@ 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
/// the scope resolves to right now — the form a scan publishing what it
/// has indexed so far uses.
///
/// `known` is the scan's whole work list rather than the files it has
/// reached, so the known-file and folded-spelling tables are complete from
/// the first publish: which files *exist* is settled the moment the scope
/// is resolved, and only the edges are discovered file by file. One
/// `relearn` for the batch, for the same reason
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
/// its index tables once.
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
self.incdirs = incdirs.to_vec();
self.relearn(known);
for (path, text) in batch {
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
@@ -198,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,
@@ -211,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.
@@ -244,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.
///
@@ -263,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
+83
View File
@@ -568,6 +568,89 @@ mod tests {
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some());
}
#[test]
fn a_store_from_any_previous_facts_format_is_dropped_not_misread() {
// Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT`
// and `VERSION` — so the header's format field is the only thing that
// can catch them. Written as a loop rather than against one number so
// it cannot go stale the next time a record grows a field: it was
// pinned at 2 for the `detail_span` bump (QA finding,
// `docs/features/port-detail-spans/README.md`) and would have gone on
// testing 2 forever.
let dir = TempDir::new("factsformats");
let file = dir.file("m.sv", M);
let encoded = facts(&file, M).encode().expect("encodes");
for format in 1..FACTS_FORMAT {
let old_format_store = format!(
"lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n",
line(content_hash(M.as_bytes()), &encoded)
);
std::fs::write(dir.path.join(FILE), old_format_store).expect("write");
let cache = IndexCache::open(Some(dir.path.clone()));
assert!(
cache.facts_for(&file, M).is_none(),
"a format-{format} record must not be read as a format-{FACTS_FORMAT} one"
);
}
// And the belt to that brace: a record really written in the previous
// 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(&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
// appended to, and reopening reads the fresh record back.
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.record(&facts(&file, M), M);
let text = dir.store_text();
assert!(
text.starts_with(&header()),
"the store was replaced under this build's header: {text}"
);
assert!(
IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some(),
"reopening reads the freshly written record back"
);
}
/// 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, 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")
}
#[test]
fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() {
// The one shape `create_new` introduces: a zero-byte store, left by a
+30 -4
View File
@@ -281,10 +281,13 @@ fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)>
// no trailing newline, nothing typed after it yet — it shares the
// trigger token's `span.end`. Skipping it here is what lets a trigger at
// the true end of the file still fire (QA find, 2026-08-25).
let index = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset)?;
//
// Token ends rise across the vector, so the tokens ending at or before
// `offset` are a prefix of it: no token outside that prefix could have
// satisfied the reverse sweep this replaced, and inside it the sweep's
// remaining condition is the `Eof` test alone.
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let index = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof)?;
let last = doc.tokens.get(index)?;
if last.span.end != offset {
return None;
@@ -412,6 +415,29 @@ mod tests {
(ws, uri, position)
}
/// [`triggered`] used to sweep the token vector backwards from its end for
/// the last non-`Eof` token ending at or before the cursor. It now bounds
/// that sweep with a binary search; the token it lands on must be the same
/// one at every byte.
#[test]
fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() {
let text = crate::state::mixed_buffer(20);
let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.clone());
let doc = ws.document(&uri).expect("open");
for offset in 0..=text.len() as u32 {
let swept = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset);
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let searched =
doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof);
assert_eq!(swept, searched, "at offset {offset}");
}
}
/// The same, in a SystemVerilog buffer.
fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) {
asking_in("/rtl/top.sv", text, needle)
+22 -8
View File
@@ -3,12 +3,15 @@
//! The workspace index deliberately keeps no file contents
//! (`docs/features/workspace-index/README.md`), so a span in another file has
//! to be converted against that file's text, fetched here with the same
//! open-buffer-beats-disk precedence the index rebuild uses.
//! open-buffer-beats-disk precedence the index rebuild uses — from the
//! buffer's own line index when there is one, and otherwise through
//! `Workspace::file_view`, which reads a closed file at most once per
//! generation of it rather than once per question about it.
use std::path::Path;
use lsp_types::Location;
use vlog_parser::{LineIndex, TextRange};
use vlog_parser::TextRange;
use crate::convert::Positions;
use crate::state::Workspace;
@@ -17,17 +20,28 @@ use crate::uri::path_to_uri;
/// The location of a byte span inside a workspace file.
pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location> {
let uri = path_to_uri(path)?;
let text = ws.text_of(path)?;
let index = LineIndex::new(&text);
let range = Positions::new(&text, &index).range(span);
Some(Location { uri, range })
if let Some(doc) = ws.document_for_path(path) {
return Some(Location { uri, range: doc.positions().range(span) });
}
let view = ws.file_view(path)?;
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
}
/// The 1-based line a byte offset falls on, for hover text that names a file
/// and a line rather than jumping to it.
///
/// An open buffer answers from the line index it already carries; a closed
/// file answers from the shared view cache. **An indexed declaration should
/// not come here at all** — `Def::lines` already holds its line, recorded when
/// the file was indexed, and that answer costs nothing
/// (`docs/features/hover-line-index/README.md`). What is left for this
/// function is the spans the index records no line for, which today is a
/// `` `define``'s.
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
let text = ws.text_of(path)?;
Some(LineIndex::new(&text).line_col(offset).0)
if let Some(doc) = ws.document_for_path(path) {
return Some(doc.line_index.line_col(offset).0);
}
Some(ws.file_view(path)?.lines.line_col(offset).0)
}
/// How a file is named in hover text: its file name, which is what a Verilog
+152 -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;
@@ -29,6 +30,8 @@ mod locate;
mod nav;
mod on_type;
mod pairs;
#[cfg(test)]
mod perf;
mod ports;
mod rename;
mod selection;
@@ -62,10 +65,39 @@ use lsp_types::{
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
};
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()?;
@@ -77,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();
@@ -91,14 +124,49 @@ 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)?)?;
Server::new(connection, roots, abilities, storage).run()?;
// The message loop parses every buffer it is handed, so it does not run
// on the main thread: that stack is whatever the OS and `ulimit -s` left
// it, and the parser's nesting limit only turns over-deep input into a
// diagnostic above `PARSE_STACK_SIZE` (below it the overflow aborts the
// whole server, taking the editor session with it). Nothing else here
// parses — `lsp-server`'s reader and writer threads move JSON, and the
// forwarder in `Server::queue` moves messages.
std::thread::Builder::new()
.name("lucisv-main".to_string())
.stack_size(PARSE_STACK_SIZE)
.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.
@@ -396,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
@@ -537,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();
@@ -719,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
+657 -13
View File
@@ -31,7 +31,19 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
}
match path_to_uri_or_self(ws, uri) {
Some(target) => {
vec![Location { uri: target, range: doc.positions().range(symbol.name_span) }]
let positions = doc.positions();
// A non-ANSI port's *complete* declaration is the body
// `input wire clk;`, so that is where a jump lands first —
// the header name it jumped from stays second, exactly the
// two sections its hover card shows.
let mut locations = Vec::with_capacity(2);
if let Some(detail) = symbol.detail_span.filter(|span| !span.is_empty()) {
locations
.push(Location { uri: target.clone(), range: positions.range(detail) });
}
locations
.push(Location { uri: target, range: positions.range(symbol.name_span) });
locations
}
None => Vec::new(),
}
@@ -166,8 +178,22 @@ pub(crate) fn indexed_def_for_symbol<'a>(
doc: &Document,
symbol: &Symbol,
) -> Option<&'a Def> {
let path = doc.path.as_deref()?;
let file = ws.index().file_id(path)?;
let file = ws.index().file_id(doc.path.as_deref()?)?;
indexed_def_in_file(ws, doc, symbol, file)
}
/// [`indexed_def_for_symbol`] with the document's own [`FileId`] already in
/// hand.
///
/// Split out for `indexed_references`, which asks about every reference in one
/// buffer: the path lookup is a binary search whose comparisons are whole path
/// `cmp`s, and it answers the same thing for all of them.
fn indexed_def_in_file<'a>(
ws: &'a Workspace,
doc: &Document,
symbol: &Symbol,
file: vlog_semantic::FileId,
) -> Option<&'a Def> {
let defs = if symbol.scope == doc.semantics.file_scope() {
ws.index().units(&symbol.name)
} else {
@@ -206,9 +232,27 @@ fn indexed_references(
for (_, doc) in ws.open_documents() {
let Some(path) = doc.path.as_ref() else { continue };
// Every reference in this buffer is answered against the same indexed
// file, so the path lookup — a binary search comparing whole paths —
// is taken once per buffer rather than once per reference.
let file = ws.index().file_id(path);
for (id, reference) in doc.semantics.references().iter().enumerate() {
// A use can only name `target.def` if it spells the name that
// declaration declares, and `target.name` is exactly that name.
// One string compare replaces two index lookups and a scope walk
// for every *other* name in the buffer, which in a big top is all
// but a handful of them. The argument that this changes no answer
// is in `docs/features/references-nav/README.md`. The empty-span
// check below is deliberately *not* hoisted here: an ambiguous use
// aborts the whole collection whether or not it has a span.
if reference.name != target.name {
continue;
}
let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) {
Some(symbol) => indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def),
Some(symbol) => {
file.and_then(|file| indexed_def_in_file(ws, doc, symbol, file))
== Some(&target.def)
}
None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) {
Some(ExternalTarget::Resolved(def)) => def == &target.def,
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(&target.def) => {
@@ -227,11 +271,15 @@ fn indexed_references(
let span = ws
.document_for_path(&target.declaration_path)
.and_then(|doc| {
doc.semantics.symbols().iter().find_map(|symbol| {
(symbol.name == target.name
&& indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def))
.then_some(symbol.name_span)
})
// Same name-keyed lookup `hover.rs::live_symbol` makes, for
// the same reason: only same-named declarations can be this
// one, and the order they come in is declaration order either
// way, so the first match is unchanged.
doc.semantics
.symbols_named(&target.name)
.filter_map(|id| doc.semantics.symbol(id))
.find(|symbol| indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def))
.map(|symbol| symbol.name_span)
})
.unwrap_or(target.declaration_span);
found.push((target.declaration_path, span));
@@ -292,9 +340,14 @@ fn in_file_references(
let Some(symbol_id) = symbol_at(&doc.semantics, offset) else { return Vec::new() };
let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() };
let positions = doc.positions();
// `occurrences` sorts, so the spans arrive in the order a walker wants —
// the same batch conversion `locations` already does for the cross-file
// answer. A signal used ten thousand times in one file is an ordinary
// shape, and one-span-at-a-time conversion re-measures a line per span.
let mut walker = positions.walker();
occurrences(&doc.semantics, symbol_id, include_declaration)
.into_iter()
.map(|span| Location { uri: target.clone(), range: positions.range(span) })
.map(|span| Location { uri: target.clone(), range: walker.range(span) })
.collect()
}
@@ -310,23 +363,71 @@ 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;
}
let positions = doc.positions();
// Sorted spans, one walker — see `in_file_references`, which converts the
// same list the same way.
let mut walker = positions.walker();
Some(
spans
.into_iter()
.map(|span| DocumentHighlight {
range: positions.range(span),
range: walker.range(span),
kind: Some(DocumentHighlightKind::TEXT),
})
.collect(),
)
}
/// 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.
///
@@ -362,6 +463,7 @@ fn occurrences(
#[cfg(test)]
mod tests {
use super::*;
use crate::perf::mean;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
@@ -601,6 +703,56 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member() {
// A harder equivalence case than the one above: `W` is a module (a
// *unit*, filed in `units`) and, spelled identically, a package
// member (filed in `members`) — the prefilter's one string compare
// must not let either bucket answer for the other. `top.sv` is also
// edited live after opening, so the overlay's answer has to come from
// the unsaved buffer, not the file `find_references`'s own oracle
// would otherwise re-read from disk.
let dir = temp_dir("xrefs_equivalence_unit_and_member");
let w_mod = "module W;\nendmodule\n";
let w_pkg = "package p;\n localparam W = 4;\nendpackage\n";
let top_saved = "module top;\n W u_w ();\n wire [p::W-1:0] x;\nendmodule\n";
for (name, text) in [("w.sv", w_mod), ("p.sv", w_pkg), ("top.sv", top_saved)] {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let top_uri = path_to_uri(&dir.join("top.sv")).expect("uri");
// An unsaved edit: a second live instantiation of `W`, not yet saved.
let top_live = "module top;\n W u_w ();\n W u_w2 ();\n wire [p::W-1:0] x;\nendmodule\n";
ws.set_document(top_uri, top_live.to_string());
let w_uri = path_to_uri(&dir.join("w.sv")).expect("uri");
ws.set_document(w_uri.clone(), w_mod.to_string());
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
ws.set_document(p_uri.clone(), w_pkg.to_string());
// The module `W`: its declaration and both live instantiations, never
// the package member spelled the same way.
let module_offset = at(w_mod, "W");
let indexed_module = references(&ws, &w_uri, module_offset, true);
let walked_module =
vlog_refactor::find_references(&ws.sources(), &dir.join("w.sv"), module_offset, true)
.expect("the walk answers");
assert_eq!(indexed_module, locations(&ws, walked_module));
assert_eq!(indexed_module.len(), 3, "declaration + 2 live instantiations, not the member");
// The package member `W`: its declaration and the one qualified use,
// never the module.
let member_offset = at(w_pkg, "W");
let indexed_member = references(&ws, &p_uri, member_offset, true);
let walked_member =
vlog_refactor::find_references(&ws.sources(), &dir.join("p.sv"), member_offset, true)
.expect("the walk answers");
assert_eq!(indexed_member, locations(&ws, walked_member));
assert_eq!(indexed_member.len(), 2, "declaration + the one qualified use, not the module");
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "manual indexed-navigation latency probe"]
fn qa_indexed_references_latency_over_a_large_workspace() {
@@ -648,6 +800,223 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
// ------------------------------------------------------------------
// latency probes for a big open buffer
//
// `#[ignore]`d, asserting nothing about duration — the house shape from
// `perf.rs`, whose `mean` they borrow so every number in this repo is
// taken the same way. The numbers they print are recorded in
// `docs/features/references-nav/README.md`.
//
// cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored \
// --nocapture --test-threads=1
// ------------------------------------------------------------------
/// A declaration small enough that nothing about it is the measurement.
const PROBE_SUB: &str =
"module sub (input logic clk, input logic [31:0] data_in);\nendmodule\n";
/// A big top level: `blocks` four-line blocks of ordinary RTL — a wire, an
/// assign, a register and its update — then `instances` instantiations of
/// `sub`. Every block declares two names and uses four, so ten thousand
/// blocks is a forty-thousand-line file carrying tens of thousands of
/// locally resolved references: exactly the buffer the open-document
/// overlay in `indexed_references` has to walk past to answer anything.
///
/// One `acc` is used by every block, so the file also carries a *local*
/// name with thousands of occurrences — the worst case for the in-file
/// fallback, which converts one span at a time.
///
/// Its own generator rather than `perf::generated_module`'s, because that
/// one instantiates nothing and a probe about instantiations needs some.
fn generated_top(blocks: usize, instances: usize) -> String {
let mut src = String::from(
"module top (\n input logic clk,\n input logic rst_n,\n \
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n \
wire acc;\n assign acc = rst_n;\n",
);
for n in 0..blocks {
src.push_str(&format!(
" wire [31:0] w_{n};\n \
assign w_{n} = data_in ^ {{32{{rst_n}}}} ^ {{32{{acc}}}};\n \
reg [31:0] r_{n};\n always @(posedge clk) r_{n} <= w_{n};\n"
));
}
for n in 0..instances {
src.push_str(&format!(" sub u_{n} (.clk(clk), .data_in(data_in));\n"));
}
src.push_str(" assign data_out = data_in;\nendmodule\n");
src
}
/// Both directions of a cross-file references request, with a big buffer
/// open — the owner's report of 2026-08-28, measured.
#[test]
#[ignore = "manual references-latency probe — see docs/features/references-nav/README.md"]
fn qa_references_latency_with_a_big_open_top() {
use std::hint::black_box;
let dir = temp_dir("refs_big_top");
let top_text = generated_top(10_000, 4);
let sub_path = dir.join("sub.sv");
let top_path = dir.join("top.sv");
fs::write(&sub_path, PROBE_SUB).expect("write");
fs::write(&top_path, &top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let top_uri = path_to_uri(&top_path).expect("uri");
let sub_uri = path_to_uri(&sub_path).expect("uri");
ws.set_document(top_uri.clone(), top_text.clone());
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
let use_site = at(&top_text, "sub u_0");
let declaration = at(PROBE_SUB, "sub");
let local = top_text.rfind("<= w_").expect("a local use") as u32 + 3;
let common = top_text.rfind("{32{acc}}").expect("a use of acc") as u32 + 4;
let references_in_top =
ws.document(&top_uri).map(|doc| doc.semantics.references().len()).expect("top is open");
// The answers, before any timing: a measurement of a request that
// answered nothing is worthless.
assert_eq!(references(&ws, &top_uri, use_site, true).len(), 5, "declaration + 4 instances");
assert_eq!(references(&ws, &sub_uri, declaration, true).len(), 5, "the same five");
assert_eq!(definition(&ws, &top_uri, use_site).len(), 1);
assert_eq!(references(&ws, &top_uri, local, true).len(), 3, "one wire, in this file only");
assert_eq!(references(&ws, &top_uri, common, true).len(), 10_002, "`acc`, everywhere");
let runs = 20;
let from_use = mean(runs, || {
black_box(references(&ws, &top_uri, black_box(use_site), true));
});
let from_declaration = mean(runs, || {
black_box(references(&ws, &sub_uri, black_box(declaration), true));
});
let to_definition = mean(runs, || {
black_box(definition(&ws, &top_uri, black_box(use_site)));
});
let in_file = mean(runs, || {
black_box(references(&ws, &top_uri, black_box(local), true));
});
let in_file_common = mean(runs, || {
black_box(references(&ws, &top_uri, black_box(common), true));
});
let highlights = mean(runs, || {
let doc = ws.document(&top_uri).expect("open");
black_box(document_highlights(doc, black_box(common)));
});
eprintln!(
"big open top ({} KB, {references_in_top} references): \
references from the use site {from_use:?}, \
from the declaration {from_declaration:?}, \
definition from the use site {to_definition:?}, \
references on a local wire used 3× (the in-file fallback) {in_file:?}, \
on one used 10 001× {in_file_common:?}, \
documentHighlight on that one {highlights:?}",
top_text.len() / 1000,
);
let _ = fs::remove_dir_all(&dir);
}
/// The other half of the owner's report: what jumping *into* a file costs
/// when the folder it lives in was not in the index's scope yet.
#[test]
#[ignore = "manual didOpen/scope-widening latency probe — see docs/features/references-nav/README.md"]
fn qa_didopen_latency_when_a_new_folder_widens_the_scope() {
use std::hint::black_box;
let dir = temp_dir("didopen_scope");
fs::create_dir_all(dir.join("rtl")).expect("rtl dir");
fs::create_dir_all(dir.join("lib")).expect("lib dir");
for n in 0..400 {
fs::write(
dir.join("rtl").join(format!("m{n}.sv")),
format!("module m{n};\n wire w;\n assign w = 1'b0;\nendmodule\n"),
)
.expect("write");
}
fs::write(dir.join("lib").join("sub.sv"), PROBE_SUB).expect("write");
let top_text = generated_top(10_000, 4);
let top_path = dir.join("rtl").join("top.sv");
fs::write(&top_path, &top_text).expect("write");
// The default rung: the folder scope. Nothing is in scope until a
// buffer is opened, so the first `didOpen` is itself a widening.
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
let top_uri = path_to_uri(&top_path).expect("uri");
ws.set_document(top_uri.clone(), top_text.clone());
ws.rebuild_index();
let covered = ws.index().files().len();
// A `didOpen` the scope already covers: one `Document::new` and a
// publish, and `server.rs` runs no rescan at all.
let sibling = dir.join("rtl").join("m0.sv");
let sibling_uri = path_to_uri(&sibling).expect("uri");
let sibling_text = fs::read_to_string(&sibling).expect("read");
let inside = mean(20, || {
ws.set_document(sibling_uri.clone(), sibling_text.clone());
});
// A `didOpen` in a folder the scope does not cover: the same
// `Document::new`, and then the whole rescan `server.rs` runs when
// `scope_dirs()` moved — which re-reads and re-parses every file in
// the widened scope. Until 2026-08-28 the open big buffer was one of
// them; it now goes in from the analysis it already holds, which is
// what the last two pairs of numbers below are about
// (`docs/features/index-scope/README.md`).
let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri");
let widening = mean(5, || {
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
black_box(ws.rebuild_index());
});
let rescan = mean(5, || {
black_box(ws.rebuild_index());
});
// Where the buffer's share goes, on the same buffer: what a rescan
// used to pay for one open file — a whole parse for the index facts,
// then a second lex for the completion words — against what it pays
// since 2026-08-28, which is the two walks over the analysis and the
// token stream the buffer already holds.
let (reparse, reused, relex, rewords) = {
let doc = ws.document(&top_uri).expect("open");
(
mean(3, || {
black_box(vlog_semantic::FileFacts::of(top_path.clone(), &top_text));
}),
mean(3, || {
black_box(doc.facts(top_path.clone()));
}),
mean(3, || {
let tokens = vlog_parser::tokenize(&top_text).expect("it lexes");
black_box(crate::candidates::words_of_tokens(&tokens));
}),
mean(3, || {
black_box(doc.words());
}),
)
};
// The same rescan with the big buffer closed, so its share of the
// rescan is a subtraction rather than a guess.
ws.close_document(&top_uri);
let without = mean(5, || {
black_box(ws.rebuild_index());
});
eprintln!(
"didOpen with a {} KB buffer already open, {covered} files in scope: \
a file the scope already covers {inside:?}; \
one in a new folder (didOpen + rescan) {widening:?}; \
the rescan alone {rescan:?}, and {without:?} with the big buffer closed. \
That buffer's own share: facts {reparse:?} parsed vs {reused:?} reused, \
words {relex:?} re-lexed vs {rewords:?} reused",
top_text.len() / 1000,
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn include_declaration_drops_the_declaration_and_nothing_else() {
let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv");
@@ -755,6 +1124,109 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_same_named_port_in_another_open_buffer_is_a_different_symbol() {
// The name prefilter's risk case, asserted from both sides: two
// modules declare a port `clk`, both files are open, and each port's
// references are its own. A prefilter that let a spelling stand in for
// an identity would merge these two answers.
let dir = temp_dir("xrefs_same_name");
let sub = "module sub (input logic clk);\nendmodule\n";
let top = "module top;\n sub u_a (.clk(1'b0));\nendmodule\n";
let other = "module other (input logic clk);\n wire w;\n assign w = clk;\nendmodule\n";
for (name, text) in [("sub.sv", sub), ("top.sv", top), ("other.sv", other)] {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let mut uri_of = |name: &str, text: &str| {
let uri = path_to_uri(&dir.join(name)).expect("uri");
ws.set_document(uri.clone(), text.to_string());
uri
};
let sub_uri = uri_of("sub.sv", sub);
uri_of("top.sv", top);
let other_uri = uri_of("other.sv", other);
assert_eq!(
places(&references(&ws, &sub_uri, at(sub, "clk"), true)),
vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)],
"`sub`'s port: its declaration and the connection to it"
);
assert_eq!(
places(&references(&ws, &other_uri, at(other, "clk"), true)),
vec![("other.sv".to_string(), 0), ("other.sv".to_string(), 2)],
"`other`'s port: its declaration and its own use"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn two_packages_declaring_one_name_keep_their_references_apart() {
// The same attack through the member table rather than the port table:
// `p::WIDTH` and `q::WIDTH` spell one name and are two declarations,
// and the file using both is open.
let dir = temp_dir("xrefs_two_packages");
let p = "package p;\n localparam WIDTH = 8;\nendpackage\n";
let q = "package q;\n localparam WIDTH = 16;\nendpackage\n";
let a = "module a;\n wire [p::WIDTH-1:0] x;\n wire [q::WIDTH-1:0] y;\nendmodule\n";
for (name, text) in [("p.sv", p), ("q.sv", q), ("a.sv", a)] {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri");
ws.set_document(a_uri.clone(), a.to_string());
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
ws.set_document(p_uri.clone(), p.to_string());
assert_eq!(
places(&references(&ws, &p_uri, at(p, "WIDTH"), true)),
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)],
"`p`'s WIDTH only — `q::WIDTH` on the next line is another symbol"
);
// And from the use side, the same set.
assert_eq!(
places(&references(&ws, &a_uri, at(a, "p::WIDTH") + 3, true)),
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)]
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn every_in_file_occurrence_is_converted_against_its_own_line() {
// The in-file fallback converts its spans with one walker now. A
// walker handed an out-of-order span answers a stale column, so the
// shape that would catch it: many occurrences, each on a line with a
// wide character before it, plus one on the same line as another.
let mut text = String::from("module m;\n wire a;\n");
for n in 0..20 {
text.push_str(&format!(" // é 🎉 {n}\n assign b{n} = a + a;\n"));
}
text.push_str("endmodule\n");
let (ws, uri) = document(&text);
let found = references(&ws, &uri, at(&text, "wire a") + 5, true);
assert_eq!(found.len(), 41, "the declaration and two uses per block");
let doc = ws.document(&uri).expect("open");
let positions = doc.positions();
for location in &found {
let line = location.range.start.line as usize;
let offset = positions.offset(location.range.start);
assert_eq!(
text.get(offset as usize..offset as usize + 1),
Some("a"),
"line {line} must point at the name"
);
assert_eq!(location.range.end.character, location.range.start.character + 1);
}
// documentHighlight walks the same list and must agree with it.
let highlights = document_highlights(doc, at(&text, "wire a") + 5).expect("a symbol");
let ranges: Vec<_> = highlights.iter().map(|h| h.range).collect();
assert_eq!(ranges, found.iter().map(|l| l.range).collect::<Vec<_>>());
}
#[test]
fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() {
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv");
@@ -843,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");
+51 -5
View File
@@ -26,7 +26,7 @@ use vlog_parser::token::{Token, TokenKind};
use crate::format;
use crate::pairs;
use crate::state::Document;
use crate::state::{first_token_from, first_token_reaching, Document};
/// The character the client is told to trigger on. A newline is the one
/// keystroke that opens a line whose indentation nobody has chosen yet.
@@ -71,8 +71,14 @@ fn statement_edit(doc: &Document, position: Position, config: &Config) -> Option
let offset = doc.positions().offset(position);
// The character the client named has to actually be there, and it has to
// be a `;` the lexer sees: one inside a string or a comment ends no
// statement, and re-laying-out its line would be a guess.
let typed = doc.tokens.iter().find(|token| token.span.end == offset)?;
// statement, and re-laying-out its line would be a guess. A token that
// ends exactly at `offset` is the first one that *reaches* it — everything
// before ends earlier, everything after ends later — so a binary search
// finds what the sweep this replaced found.
let typed = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|t| t.span.end == offset)?;
if !typed.is_sym(SEMICOLON) {
return None;
}
@@ -264,9 +270,12 @@ fn inside_a_comment(token: &Token, at: u32) -> bool {
/// line the user has just opened has none.
fn first_on_line(doc: &Document, content: u32) -> Option<&Token> {
let line = doc.line_index.line_col(content).0;
doc.tokens
// Every token before this index starts before `content`, so none of them
// could have satisfied the sweep this replaced; within the tail the sweep's
// remaining condition is the `Eof` test alone.
doc.tokens[first_token_from(&doc.tokens, content)..]
.iter()
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
.find(|token| token.kind != TokenKind::Eof)
.filter(|token| doc.line_index.line_col(token.span.start).0 == line)
}
@@ -646,6 +655,43 @@ mod tests {
f(ws.document(&uri).expect("open"))
}
/// The `;` handler used to sweep the token vector for the token ending at
/// the cursor. Every byte of a buffer full of touching tokens must still
/// name the same token — or no token, where the sweep found none.
#[test]
fn the_token_ending_at_the_cursor_is_the_one_the_sweep_returned() {
let text = crate::state::mixed_buffer(20);
with(&text, |doc| {
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().find(|token| token.span.end == offset);
let searched = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|t| t.span.end == offset);
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
}
});
}
/// The same, for the indent handler's "first token at or after this byte":
/// [`first_on_line`] is compared against the sweep it was written as.
#[test]
fn the_first_token_on_a_line_is_the_one_the_sweep_returned() {
let text = crate::state::mixed_buffer(20);
with(&text, |doc| {
for content in 0..=text.len() as u32 {
let line = doc.line_index.line_col(content).0;
let swept = doc
.tokens
.iter()
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
.filter(|token| doc.line_index.line_col(token.span.start).0 == line);
let searched = first_on_line(doc, content);
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at byte {content}");
}
});
}
fn config(indent_width: usize) -> Config {
Config { indent_width, ..Config::default() }
}
File diff suppressed because it is too large. Load diff
+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");
+32 -2
View File
@@ -13,7 +13,7 @@ use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind}
use vlog_parser::TextRange;
use crate::pairs::analyze;
use crate::state::Document;
use crate::state::{first_token_reaching, Document};
/// One chain per requested position, in the order they were asked for.
///
@@ -41,7 +41,17 @@ fn chain(doc: &Document, offset: u32) -> SelectionRange {
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
let mut spans = Vec::new();
if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) {
// The first token that reaches `offset` is the first that can cover it,
// and — because the tokens after it all start no earlier — the only one
// the sweep this replaced could ever have returned. Note that `covers`
// takes `span.end` inclusively, so this is deliberately *not*
// `Document::token_at`: at a byte two adjacent tokens share, the sweep
// answered with the earlier one and so does this.
if let Some(token) = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|token| covers(token.span, offset))
{
spans.push(token.span);
}
items(&doc.tree.items, offset, &mut spans);
@@ -219,6 +229,26 @@ mod tests {
Document::new(None, text.to_string(), &WorkspaceIndex::default())
}
/// The innermost step of a chain used to come from a sweep of the whole
/// token vector; it now comes from a binary search. `covers` takes
/// `span.end` inclusively, so at a byte two adjacent tokens share the
/// sweep answered with the earlier of the two — this pins that the search
/// answers with the earlier one too, at every byte of a buffer written to
/// have plenty of them.
#[test]
fn the_innermost_step_is_the_token_the_sweep_returned_at_every_offset() {
let text = crate::state::mixed_buffer(20);
let doc = doc_of(&text);
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().find(|token| covers(token.span, offset));
let searched = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|token| covers(token.span, offset));
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
}
}
/// The chain for the first occurrence of `needle`, as the source text of
/// each step, innermost first.
fn steps(text: &str, needle: &str) -> Vec<String> {
File diff suppressed because it is too large. Load diff
+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
File diff suppressed because it is too large. Load diff
+8
View File
@@ -77,6 +77,11 @@ impl From<VerificationError> for FormatError {
/// The output is only returned if it re-lexes to the same token stream as the
/// input (comments included) and formatting it again is a fixed point;
/// otherwise the caller gets an error and must leave the original text alone.
///
/// Parses `source` (twice, for verification), so call this only on a thread
/// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one
/// lets sufficiently nested input abort the process instead of returning
/// `Err` (see `docs/features/recursion-limit/README.md`).
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
let output = format_once(source, config).map_err(FormatError::Source)?;
verify_equivalence(source, &output)?;
@@ -93,6 +98,9 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
/// formatter output, and both checks are global. Convergence is checked by
/// replaying the same per-item decisions against the output — see
/// `docs/features/range-formatting/README.md`.
///
/// Same stack requirement as [`format_source`]: needs a thread with at least
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
pub fn format_range(
source: &str,
config: &Config,
+6 -4
View File
@@ -7,13 +7,15 @@
//! the formatter at all.
use vlog_formatter::{format_source, Config, FormatError};
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH};
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH, PARSE_STACK_SIZE};
/// Formatting the deepest legal tree peaks around 4 MiB of stack in an
/// unoptimized build, more than a default test thread's 2 MiB.
/// Formatting the deepest legal tree peaks around 5.9 MiB of stack in an
/// unoptimized build, more than a default test thread's 2 MiB. The size is
/// the one every production parse site is given, so these tests fail if the
/// guarantee is ever cut below what the depth limit needs.
fn format_deep(source: String) -> Result<String, FormatError> {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.stack_size(PARSE_STACK_SIZE)
.spawn(move || format_source(&source, &Config::default()))
.expect("spawn formatter thread")
.join()
+1 -1
View File
@@ -14,7 +14,7 @@ pub mod token;
pub use lexer::{tokenize, LexError};
pub use line_index::LineIndex;
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError};
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError, PARSE_STACK_SIZE};
pub use span::TextRange;
pub use token::KEYWORDS;
+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";
+91 -13
View File
@@ -160,13 +160,40 @@ const DRIVE_STRENGTHS: &[&str] = &[
/// How deeply constructs may nest before the parser gives up.
///
/// Chosen from measured stack use, not from taste: nested statements are the
/// most expensive family at ~62 KiB of stack per level in an unoptimized
/// build, so formatting an input that trips the limit peaks at ~3.9 MiB —
/// comfortably under the 8 MiB default main-thread stack, and ~0.5 MiB in
/// an optimized build. Real RTL nests roughly an order of magnitude less
/// than this; see `docs/features/recursion-limit/README.md`.
/// most expensive family at ~94 KiB of stack per level in an unoptimized
/// build, so the whole pipeline on an input that trips the limit peaks at
/// ~5.9 MiB there and ~0.8 MiB in an optimized build. That budget is only
/// safe on a thread big enough to hold it, which is what
/// [`PARSE_STACK_SIZE`] names — this limit bounds how *many* levels run, not
/// what one costs. Real RTL nests roughly an order of magnitude less than
/// this; see `docs/features/recursion-limit/README.md`.
pub const MAX_NESTING_DEPTH: u32 = 64;
/// How much stack a thread that parses must be given.
///
/// [`MAX_NESTING_DEPTH`] turns over-deep input into a parse error instead of
/// a stack overflow, but only on a thread that can hold the levels it *does*
/// allow: the guard fires at level 64, and reaching level 64 costs stack. On
/// a smaller thread the overflow happens first, and a stack overflow is an
/// abort, not a `Result` — the whole process dies. So the stack has to fit
/// the limit; the limit is not lowered to fit some thread's stack.
///
/// Measured worst case for the full pipeline (tokenize → parse → analyze →
/// format → verify) over every nesting family, on input sized to trip the
/// limit: **~5.9 MiB unoptimized, ~0.8 MiB optimized** (nested `case`, the
/// fattest family). 16 MiB is that with 2.7× to spare, which is the margin
/// this wants: unoptimized frame sizes drift upward with the compiler — the
/// same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB in 2026-08-28
/// on rustc 1.97 — and there is no recoverable failure mode to fall back to.
///
/// Every thread that may reach a parse is spawned with at least this:
/// `std::thread::Builder::new().stack_size(PARSE_STACK_SIZE)`, or
/// `rayon::ThreadPoolBuilder::new().stack_size(PARSE_STACK_SIZE)`. Thread
/// stacks are committed by the OS a page at a time, so an unused one costs
/// address space rather than memory. `docs/features/recursion-limit/README.md`
/// lists every site.
pub const PARSE_STACK_SIZE: usize = 16 * 1024 * 1024;
/// How many links a left-nested chain may add to the tree on one path.
///
/// Some constructs are parsed by a loop rather than by recursion — postfix
@@ -178,9 +205,9 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
/// the two limits together no matter how chains and nesting are combined.
///
/// It is larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap —
/// ~6 KiB of stack per link in an unoptimized build against ~62 KiB for a
/// nested statement, so a maximal chain peaks near 1.5 MiB, well under the
/// ~3.9 MiB that maximal statement nesting already costs — and because long
/// ~9 KiB of stack per link in an unoptimized build against ~94 KiB for a
/// nested statement, so a maximal chain peaks near 2.4 MiB, well under the
/// ~5.9 MiB that maximal statement nesting already costs — and because long
/// flat chains are the one shape real RTL does produce (a 256-term generated
/// sum, a 64-bit parity XOR). Raising it, unlike raising
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
@@ -241,6 +268,10 @@ pub struct Parser<'a> {
/// `source` must be the exact text `tokens` were lexed from: the constructs
/// lucisv keeps verbatim (`constraint`, `covergroup` — see
/// `docs/features/classes/README.md`) copy their bytes out of it by span.
///
/// Recurses with input nesting: call this only on a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
/// instead of returning `Err`.
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
Parser::new(tokens, source, false).parse_source_file()
}
@@ -253,6 +284,10 @@ pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
/// still spans the whole file. `source` must be the exact text `tokens` were
/// lexed from. On a well-formed file the tree is identical to [`parse`]'s and
/// the diagnostics are empty.
///
/// Same stack requirement as [`parse`]: needs a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
/// parses of the same over-deep input overflow at the same depth.
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
let mut p = Parser::new(tokens, source, true);
match p.parse_source_file() {
@@ -4898,13 +4933,15 @@ mod tests {
}
}
/// Parse on a thread with a generous stack. Nesting all the way to
/// [`MAX_NESTING_DEPTH`] peaks around 4 MiB in an unoptimized build,
/// which is more than the 2 MiB a default test thread gets — the shipped
/// binary parses on the main thread, which has 8 MiB.
/// Parse on the stack every production parse site is given. Nesting all
/// the way to [`MAX_NESTING_DEPTH`] peaks around 5.9 MiB in an
/// unoptimized build, which is more than the 2 MiB a default test thread
/// gets — hence [`PARSE_STACK_SIZE`], and hence the fact that the tests
/// spell it rather than a number of their own: what they exercise is the
/// stack the shipped binaries actually run on.
fn parse_deep(src: String) -> PResult<SourceFile> {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.stack_size(PARSE_STACK_SIZE)
.spawn(move || parse(tokenize(&src).expect("lex error"), &src))
.expect("spawn parser thread")
.join()
@@ -5014,6 +5051,47 @@ mod tests {
));
}
/// `n` copies of a block opener and its closer around one statement, in
/// an `initial` — the shape generated RTL nests.
fn nested_stmt_blocks(open: &str, close: &str, n: usize) -> String {
format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
open.repeat(n),
close.repeat(n)
)
}
#[test]
fn deep_nesting_errors_for_every_block_form() {
let d = 200;
// `fork`/`join` blocks are statements like `begin`/`end`.
assert_too_deep(nested_stmt_blocks("fork\n", "join\n", d));
// `case` carries the fattest frame in the grammar; the arm's own
// statement is a second gated level per source level.
assert_too_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", d));
// Bodies that need no closer still recurse through the body
// statement.
assert_too_deep(nested_stmt_blocks("foreach (a[j])\n", "", d));
assert_too_deep(nested_stmt_blocks("while (c)\n", "", d));
assert_too_deep(nested_stmt_blocks("for (int i = 0; i < 4; i++)\n", "", d));
// Nested module declarations (IEEE 1800 §23.4) nest items, not
// statements, so they are gated by `parse_item`.
assert_too_deep(format!("{}wire w;\n{}", "module m;\n".repeat(d), "endmodule\n".repeat(d)));
}
#[test]
fn the_fattest_block_forms_still_parse_at_the_limit() {
// The stack these tests run on is `PARSE_STACK_SIZE`, so this is the
// load-bearing direction: the deepest *legal* input in the two most
// expensive families has to fit the stack every production parse site
// is given. `module` + `initial` + `begin` + the innermost statement
// and its expression cost six levels between them.
let n = MAX_NESTING_DEPTH as usize - 6;
parse_deep(nested_stmt_blocks("fork\n", "join\n", n)).expect("legal `fork` nesting");
parse_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", n))
.expect("legal `case` nesting");
}
#[test]
fn chain_just_below_the_limit_parses() {
parse_deep(chain(".b", MAX_CHAIN_LENGTH as usize))
+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
// ----------------------------------------------------------------------
+22
View File
@@ -142,6 +142,7 @@ impl<'a> Binder<'a> {
kind,
name_span,
decl_span,
detail_span: None,
scope,
child_scope: None,
});
@@ -501,6 +502,27 @@ impl<'a> Binder<'a> {
ScopeKind::Function | ScopeKind::Task => SymbolKind::TfArg,
_ => SymbolKind::Port,
};
// A non-ANSI port's body declaration (`input signed [31:0] data_in;`)
// completes a port the header only named (`data_in,`). `declare`
// below attaches it as a reference to that header symbol — and here,
// the whole declaration's span is recorded on the symbol as where its
// direction, type and width are written. First writer wins, so a
// header that names a port twice is the linter's to complain about
// and this stays deterministic.
//
// An old-style task or function argument (`task t(a);` finished by
// `input [7:0] a;`) is the same header-names-it, body-completes-it
// shape and merges through the same `declare`, so it is recorded on
// the same terms — matching on `kind` rather than on `Port` alone.
let names = &self.scopes[scope.0 as usize].names;
for d in &p.declarators {
if let Some(&existing) = names.get(d.name.as_str()) {
let symbol = &mut self.symbols[existing.0 as usize];
if symbol.kind == kind && symbol.detail_span.is_none() {
symbol.detail_span = Some(span);
}
}
}
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
}
+99 -5
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, 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 = 2;
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,40 @@ 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
// written before it is discarded whole rather than read field-shifted
// by two (`docs/features/port-detail-spans/README.md`).
match decl.detail_span {
Some(span) => self.range(span),
None => {
self.num(0);
self.num(0);
}
}
// The declaration's lines, on the same unconditional-pair rule: the
// name's line, then the detail span's or `0` for the `None` above.
// `FACTS_FORMAT` is bumped for these two fields, so a store written
// before them is discarded rather than read short by two
// (`docs/features/hover-line-index/README.md`).
self.num(decl.lines.name);
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) {
@@ -298,7 +360,39 @@ impl<'a> Reader<'a> {
fn decl(&mut self) -> Option<Decl> {
let name = self.text()?;
let kind = kind_of(self.next()?)?;
Some(Decl { name, name_span: self.range()?, kind })
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.
let start = self.num()?;
let end = self.num()?;
let detail_span = (start != 0 || end != 0).then_some(TextRange::new(start, end));
// A line is 1-based, so `0` is the `None` here too — and a detail line
// is present exactly when a detail span is, which a record written by
// this format always agrees with.
let name_line = self.num()?;
let detail_line = self.num()?;
// 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> {
+29 -4
View File
@@ -31,9 +31,10 @@ pub use model::{
SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, 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;
@@ -52,6 +53,12 @@ pub struct Semantics {
symbol_positions: Vec<(TextRange, SymbolId)>,
/// Non-empty reference-name spans, sorted by start for cursor lookup.
reference_positions: Vec<(TextRange, ReferenceId)>,
/// Every symbol id, sorted by the name it declares, ties in declaration
/// order — so looking a name up is a binary search rather than a walk of
/// every symbol. A side table rather than a `HashMap<String, _>` because
/// this way `Semantics` does not carry a second copy of every name it
/// already holds, and it is cloned per document.
by_name: Vec<SymbolId>,
}
/// Build the symbol table for one parsed file. `src` must be the text the
@@ -97,7 +104,12 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
.map(|(i, reference)| (reference.name_span, ReferenceId(i as u32)))
.collect();
reference_positions.sort_by_key(|(span, _)| (span.start, span.end));
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions }
// A *stable* sort by name, so symbols sharing a name keep the order they
// were declared in — the order a caller filtering `symbols()` by name
// would have seen, which is what makes swapping the two an identity.
let mut by_name: Vec<SymbolId> = (0..symbols.len() as u32).map(SymbolId).collect();
by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name));
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name }
}
/// Point every import at the package it names, when this file declares it.
@@ -145,6 +157,19 @@ impl Semantics {
self.symbols.get(id.0 as usize)
}
/// Every declaration that spells `name`, in declaration order — the same
/// symbols, in the same order, that filtering [`Semantics::symbols`] by
/// name yields, without walking the ones that cannot match.
pub fn symbols_named(&self, name: &str) -> impl Iterator<Item = SymbolId> + '_ {
// Two binary searches over the name-sorted side table: the first name
// that is not less than the one asked for, then the first one past it.
let spelling = |id: &SymbolId| self.symbol(*id).map_or("", |symbol| symbol.name.as_str());
let start = self.by_name.partition_point(|id| spelling(id) < name);
let rest = self.by_name.get(start..).unwrap_or(&[]);
let end = rest.partition_point(|id| spelling(id) == name);
rest.get(..end).unwrap_or(&[]).iter().copied()
}
/// The declaration whose *name* covers `offset` — a cursor sitting on a
/// declared name, not anywhere in its declaration.
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
+7
View File
@@ -57,6 +57,13 @@ pub struct Symbol {
/// Byte range of the construct that owns the name (the whole `module`,
/// the whole declarator, the whole port declaration).
pub decl_span: TextRange,
/// Where the *complete* declaration is written, when that is not
/// `decl_span`: a non-ANSI port's header names it and a body `input
/// signed [31:0] data_in;` finishes it, so hover and go-to-definition
/// point here — the line that carries the direction, the type and the
/// width — while `name_span`/`decl_span` stay in the header. `None` for
/// every declaration that is complete where it is named.
pub detail_span: Option<TextRange>,
/// The scope the name is bound in.
pub scope: ScopeId,
/// The scope this declaration opens, for the kinds that open one
+367 -19
View File
@@ -19,7 +19,7 @@ use std::path::{Path, PathBuf};
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
use crate::{analyze, classes, instantiations, Semantics};
@@ -35,8 +35,108 @@ 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
/// non-ANSI port's body `input wire clk;`. A cross-file hover shows these
/// lines; `None` for every declaration complete where it is named.
pub detail_span: Option<TextRange>,
/// Which lines those spans fall on, read while the file was indexed.
pub lines: DeclLines,
}
/// Where a declaration sits in its file, counted in **lines**, computed when
/// that file is indexed.
///
/// The index keeps no file text, so before this every `file:line` a server
/// printed for an indexed declaration cost a read of the declaring file and a
/// whole [`LineIndex`] over it — the thing a cross-file hover into a closed
/// file was mostly spending its time on. A line is four bytes per declaration,
/// a few tens of KB for a workspace of 20 000 modules, and it is the whole of
/// what a heading needs.
///
/// **One value per declaration, so it extends by gaining a field.** Members
/// are [`Decl`]s exactly as units are, so a module's ports already carry their
/// 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.
pub name: u32,
/// 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 {
/// The lines a declaration's spans fall on, read off its file's line
/// index. 1-based, so `name` is what `LineIndex::line_col` reports and
/// what a `file:line` prints.
fn of(lines: &LineIndex, name_span: TextRange, detail_span: Option<TextRange>) -> 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.
@@ -112,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.
@@ -291,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
@@ -324,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 {
@@ -375,7 +546,19 @@ impl WorkspaceIndex {
/// server refreshes every overlay after it, exactly as it does after a
/// rebuild).
pub fn update_file(&mut self, path: PathBuf, src: &str) {
let facts = facts_of(path.clone(), src);
self.update_facts(facts_of(path, src));
}
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
/// known — read from a cache, or from an analysis the caller already holds
/// ([`FileFacts::from_analysis`]) — so the update costs no parse at all.
///
/// Exactly [`WorkspaceIndex::update_file`] with the parse already done, the
/// same way [`IndexBuilder::add_facts`] is [`IndexBuilder::add_file`] with
/// the parse already done: same contract, same result. Whether the record
/// really describes the file is the caller's business.
pub fn update_facts(&mut self, facts: FileFacts) {
let path = facts.path.clone();
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
// The common case — a saved file the index already holds. Only the
// names this file declared before or declares now can have moved,
@@ -396,6 +579,52 @@ impl WorkspaceIndex {
}
}
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
/// many files at once — and for **one** merge rather than one each.
///
/// Same contract as both — what comes out is the index a full
/// [`WorkspaceIndex::build`] over the records it now holds would have
/// produced — **provided each path appears once in `records`**. It holds
/// for the same reason theirs does: the records are kept path-sorted and
/// one file to a path, and [`WorkspaceIndex::merge`] is then the same loop
/// [`IndexBuilder::finish`] runs over the same list. A batch that names
/// one path twice is an update applied twice, so the **last** record wins,
/// where a `build` over the same duplicated input keeps the *first*
/// (`index_order` dedups) — the update semantic is the right one for an
/// "absorb what changed" API, and the one caller that feeds a scan
/// (`Scan::work`) is deduped before anything is staged. QA pinned the
/// divergence
/// (`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`).
///
/// One merge, because a merge is a pass over **every** record the index
/// holds: a scan that merged after each of its files would be quadratic in
/// the size of the workspace, which is measured rather than argued in
/// `docs/features/scan-interleave/README.md`. A caller feeding a scan
/// therefore batches — it stages records as it takes them and folds a
/// batch in only when something is about to read the index.
///
/// `gone` is dropped first, so a path in both lists ends up held: a file
/// that moved out of one scan's scope and back into the next's is one
/// file, not a removal that happens to run second.
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]) {
for path in gone {
if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) {
self.files.remove(at);
self.facts.remove(at);
}
}
for facts in records {
match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) {
Ok(at) => self.facts[at] = facts,
Err(at) => {
self.files.insert(at, facts.path.clone());
self.facts.insert(at, facts);
}
}
}
self.merge(None);
}
/// Drop one file from the index, reporting whether it was there.
///
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
@@ -425,13 +654,18 @@ impl WorkspaceIndex {
}
for symbol in self.workspace_symbols("") {
out.push_str(&format!(
"sym {} in {:?} {:?} {}:{}..{}\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.name_span.end,
symbol.def.decl_span.start,
symbol.def.decl_span.end,
symbol.def.lines.name,
symbol.def.lines.detail,
symbol.def.lines.positions
));
}
for (definition, sites) in &self.reference_sites {
@@ -466,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() {
@@ -543,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 {
@@ -643,16 +890,46 @@ 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) -> Decl {
Decl { name: symbol.name.clone(), name_span: symbol.name_span, kind: symbol.kind }
/// 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, kind: self.kind }
Def {
file,
name_span: self.name_span,
decl_span: self.decl_span,
kind: self.kind,
detail_span: self.detail_span,
lines: self.lines,
}
}
}
@@ -662,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,
@@ -716,10 +994,44 @@ impl FileFacts {
/// Read off what one file contributes to an index — the parse
/// [`IndexBuilder::add_file`] does, exposed so a caller that stores the
/// result can do the parse itself exactly once.
///
/// Parses `src` internally, so call this only on a thread with at least
/// `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one lets
/// sufficiently nested input abort the process instead of producing a
/// diagnostic (see `docs/features/recursion-limit/README.md`).
pub fn of(path: PathBuf, src: &str) -> FileFacts {
facts_of(path, src)
}
/// The same record read off an analysis the caller **already has** — the
/// tree, the `` `define`` table and the [`Semantics`] of one file — instead
/// of from that file's text.
///
/// This is the second half of [`FileFacts::of`], made callable on its own:
/// `of` is `tokenize` + `parse_tolerant` + [`analyze`] followed by exactly
/// this function, so a caller that has done that work once (a language
/// server holding an open buffer's finished analysis) gets the record the
/// parse would have produced without paying for the parse a second time.
/// The two paths are the same code and cannot drift; what the caller
/// promises is only that `tree`, `defines`, `sem` and `lines` all describe
/// the text `path` currently holds.
///
/// `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, src, lines)
}
/// The file these facts were read from.
pub fn path(&self) -> &Path {
&self.path
@@ -730,13 +1042,29 @@ impl FileFacts {
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines) = parse_and_collect(src);
let sem = analyze(&tree, src);
// One pass over the source's newlines, so every declaration below can be
// 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, src, &lines)
}
/// Read off what one file contributes, from its finished analysis.
fn facts_from_analysis(
path: PathBuf,
tree: &SourceFile,
defines: DefineTable,
sem: &Semantics,
src: &str,
lines: &LineIndex,
) -> FileFacts {
let mut facts = FileFacts {
path,
defines,
units: Vec::new(),
members: Vec::new(),
instantiations: edges_of(&tree),
subclasses: inheritance_of(&tree),
instantiations: edges_of(tree, src, lines),
subclasses: inheritance_of(tree),
references: Vec::new(),
};
let Some(file_scope) = sem.scope(sem.file_scope()) else {
@@ -749,8 +1077,8 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
if !is_unit(unit.kind) || unit.name_span.is_empty() {
continue;
}
facts.units.push(Decl::of(unit));
collect_members(&sem, unit, &mut facts.members);
facts.units.push(Decl::unit(unit, src, lines));
collect_members(sem, unit, lines, &mut facts.members);
}
let exported: HashSet<(u32, u32)> = facts
.units
@@ -792,7 +1120,7 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
/// 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| {
@@ -806,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(),
},
))
})
@@ -831,7 +1171,12 @@ fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> {
}
/// Read off the names another file may reach *into* this unit for.
fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) {
fn collect_members(
sem: &Semantics,
unit: &Symbol,
lines: &LineIndex,
out: &mut Vec<(String, Decl)>,
) {
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
return;
};
@@ -842,13 +1187,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
continue;
}
out.push((unit.name.clone(), Decl::of(member)));
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,
// so this recursion terminates.
if member.kind == SymbolKind::Class {
collect_members(sem, member, out);
collect_members(sem, member, lines, out);
}
}
}
@@ -862,10 +1207,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
/// the first file is parsed. Getting that ordering from here rather than
/// re-deriving it is what keeps a watched build and a plain
/// [`WorkspaceIndex::build`] the same index in the same order.
pub fn index_order<'a>(
files: impl IntoIterator<Item = (PathBuf, &'a str)>,
) -> Vec<(PathBuf, &'a str)> {
let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect();
///
/// Generic in what rides beside the path — a borrowed `&str` for a caller that
/// holds the texts, an owned `String` for one that is handing them over — so a
/// scan that owns its work list gets the same ordering from the same function
/// rather than sorting for itself.
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)> {
let mut sources: Vec<(PathBuf, T)> = files.into_iter().collect();
sources.sort_by(|a, b| a.0.cmp(&b.0));
// A path handed over twice is one file; the first copy wins.
sources.dedup_by(|a, b| a.0 == b.0);
+151
View File
@@ -0,0 +1,151 @@
//! Deeply nested input against the stack the parse actually runs on.
//!
//! `vlog_parser` turns nesting past `MAX_NESTING_DEPTH` into an ordinary
//! diagnostic, but only above `PARSE_STACK_SIZE`: reaching level 64 costs
//! stack, and a thread too small to hold it overflows before the guard ever
//! fires — an abort, not a `Result`. These tests run the whole indexing
//! pipeline (tokenize → tolerant parse → `analyze` → facts) on exactly that
//! stack, so they fail if either half of the contract is cut.
//!
//! Reported 2026-08-28: 500 nested `begin`/`end` through `FileFacts::of`
//! aborted the process on a default 2 MiB test thread.
use std::path::PathBuf;
use vlog_parser::PARSE_STACK_SIZE;
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
/// Run `f` on the stack every production parse site is given — the CLI's
/// worker thread and rayon pool, the language server's message loop. Not a
/// generous number picked for the test: the constant itself, so shrinking
/// the guarantee below what the depth limit needs fails here.
fn on_parse_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
.spawn(f)
.expect("spawn a parse-sized thread")
.join()
.expect("the parse thread died")
}
/// The index one file's facts build, read off on the same stack.
fn index_of(src: String) -> WorkspaceIndex {
on_parse_stack(move || {
let mut builder = IndexBuilder::new();
builder.add_facts(FileFacts::of(PathBuf::from("/w/deep.sv"), &src));
builder.finish()
})
}
/// `n` nested `begin`/`end` inside an `initial`, in a module.
fn nested_begins(n: usize) -> String {
format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(n),
"end\n".repeat(n)
)
}
/// Every block-structured shape that nests, at a depth far past the limit.
/// Each is `(name, source)`; the innermost body is a statement or an item, so
/// the shape is what real generated code would produce, not a bare skeleton.
fn deep_block_shapes(n: usize) -> Vec<(&'static str, String)> {
let stmt = |open: &str, close: &str| {
format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
open.repeat(n),
close.repeat(n)
)
};
vec![
("begin/end", nested_begins(n)),
("if/begin", stmt("if (c) begin\n", "end\n")),
("fork/join", stmt("fork\n", "join\n")),
("case/endcase", stmt("case (s)\n1: ", "endcase\n")),
("foreach", stmt("foreach (a[j])\n", "")),
("while", stmt("while (c)\n", "")),
("for", stmt("for (int i = 0; i < 4; i++)\n", "")),
(
"else-if chain",
format!(
"module m;\ninitial\n{}x <= 0;\nendmodule\n",
"if (c) x <= 1; else\n".repeat(n)
),
),
(
"generate if",
format!(
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
"if (1) begin\n".repeat(n),
"end\n".repeat(n)
),
),
(
"generate for",
format!(
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
"for (i = 0; i < 2; i = i + 1) begin\n".repeat(n),
"end\n".repeat(n)
),
),
(
"nested modules",
format!("{}wire w;\n{}", "module m;\n".repeat(n), "endmodule\n".repeat(n)),
),
(
// Not legal SystemVerilog at all — a `task` cannot open inside a
// task body — so this errors early rather than on depth. It is
// here because "errors early" is a claim about the stack too.
"nested tasks",
format!(
"module m;\n{}x = 1;\n{}endmodule\n",
"task t;\n".repeat(n),
"endtask\n".repeat(n)
),
),
(
"nested functions",
format!(
"module m;\n{}f = 1;\n{}endmodule\n",
"function int f;\n".repeat(n),
"endfunction\n".repeat(n)
),
),
("nested parens", {
format!("module m;\nassign x = {}1{};\nendmodule\n", "(".repeat(n), ")".repeat(n))
}),
]
}
#[test]
fn five_hundred_nested_blocks_are_indexed_not_aborted() {
// The reported repro, verbatim in shape. The depth limit rejects the
// `initial` block, tolerant recovery turns it into an error leaf, and the
// module around it is still a fact — a graceful result, not a dead
// process.
let index = index_of(nested_begins(500));
assert_eq!(index.files().len(), 1);
assert_eq!(index.units("m").len(), 1, "the module survives the unparsable body");
}
#[test]
fn no_block_shape_can_abort_the_parse_stack() {
// 400 levels is far past `MAX_NESTING_DEPTH` for every family, so each of
// these either errors on depth or errors earlier; what is asserted is
// that the pipeline *returns* on the guaranteed stack. A regression here
// is a SIGABRT, so the assertion below is secondary — reaching it is the
// test.
for (name, src) in deep_block_shapes(400) {
let index = index_of(src);
assert_eq!(index.files().len(), 1, "{name}");
}
}
#[test]
fn nesting_just_under_the_limit_still_yields_its_facts() {
// Legal depth, so nothing is rejected and the whole 64-level tree is
// parsed, analyzed and walked on this stack — the expensive direction,
// and the one a smaller stack fails first.
let index = index_of(nested_begins(vlog_parser::parser::MAX_NESTING_DEPTH as usize - 6));
assert_eq!(index.units("m").len(), 1, "a legally deep file is indexed like any other");
}
+86
View File
@@ -510,6 +510,92 @@ endmodule
assert_eq!(body.resolved(), Some(a));
}
#[test]
fn a_non_ansi_port_records_where_its_body_declaration_completes_it() {
let src = "\
module m (a, b);
input [7:0] a;
output b;
endmodule
";
let s = sem(src);
let a = symbol_named(&s, "a");
let detail = a.detail_span.expect("the body declaration's span");
assert!(
src[detail.start as usize..detail.end as usize].starts_with("input [7:0] a"),
"the detail site covers the body declaration: {:?}",
&src[detail.start as usize..detail.end as usize]
);
// ...while the name stays in the header.
assert_eq!(&src[a.name_span.start as usize..a.name_span.end as usize], "a");
assert!(a.name_span.start < detail.start);
// An ANSI port is complete where it is named: no detail site.
let ansi = sem("module m (input wire clk);\nendmodule\n");
assert_eq!(symbol_named(&ansi, "clk").detail_span, None);
}
#[test]
fn an_old_style_task_argument_records_its_body_declaration_too() {
// `task t(a);` names the argument and `input [7:0] a;` finishes it —
// the same shape a non-ANSI module port has, merged by the same
// `declare`, so it carries the same detail site (QA, PDS-3).
let src = "\
module m;
task t(a);
input [7:0] a;
$display(a);
endtask
endmodule
";
let s = sem(src);
let a = symbol_named(&s, "a");
assert_eq!(a.kind, SymbolKind::TfArg);
let detail = a.detail_span.expect("the body declaration's span");
assert_eq!(&src[detail.start as usize..detail.end as usize], "input [7:0] a;");
assert!(a.name_span.start < detail.start, "the name stays in the header");
// An argument complete where it is named has no detail site, as before.
let ansi = sem("module m;\n task t(input [7:0] a);\n endtask\nendmodule\n");
assert_eq!(symbol_named(&ansi, "a").detail_span, None);
}
#[test]
fn looking_a_name_up_answers_exactly_what_scanning_every_symbol_would() {
// The name-keyed lookup exists so a caller never walks the whole symbol
// table to find the declarations spelling one name. It is only a
// substitution if it answers the same symbols in the same order — and the
// order is what decides the tie when one buffer holds two declarations of
// one name, as a mid-edit buffer does.
// One scope never binds a name twice (`bind::declare`), so two
// declarations of one name means two scopes — a buffer holding an old
// module and its half-written replacement, which is the tie
// `hover::live_symbol` has to break.
let src = "\
module m (input wire dup);
wire other;
endmodule
module n (input wire [7:0] dup);
endmodule
";
let s = sem(src);
for name in ["dup", "other", "m", "n", "absent"] {
let scanned: Vec<SymbolId> = s
.symbols()
.iter()
.enumerate()
.filter(|(_, sym)| sym.name == name)
.map(|(i, _)| SymbolId(i as u32))
.collect();
let looked_up: Vec<SymbolId> = s.symbols_named(name).collect();
assert_eq!(looked_up, scanned, "the two answers must agree for {name}");
}
// The one that matters: two `dup`s, and the first is the earlier one.
let dups: Vec<SymbolId> = s.symbols_named("dup").collect();
assert_eq!(dups.len(), 2, "{dups:?}");
assert!(dups[0].0 < dups[1].0, "declaration order, so the first match is the first written");
}
#[test]
fn a_hierarchical_name_resolves_only_its_head() {
let src = "\
+582 -2
View File
@@ -2,10 +2,11 @@
//! package members, and the corpus acceptance run.
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
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.
@@ -789,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";
@@ -1102,6 +1134,122 @@ fn removing_a_file_gives_the_index_a_whole_build_would_have() {
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
}
#[test]
fn absorbing_a_batch_gives_the_index_a_whole_build_would_have() {
// The batch form the interleaved scan feeds
// (`docs/features/scan-interleave/README.md`), against the same witness
// every other incremental path is held to. Every shape at once: a file
// replaced, two files added — one of which sorts *first*, so every id
// moves — and one dropped.
let held = [
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
("gone.sv", "module gone;\nendmodule\n"),
];
let mut ws = index(&held);
assert_eq!(ws.files().len(), 3, "premise");
let batch = [
("a.sv", "module sub;\nendmodule\n"),
("m.sv", "module m;\n sub u1 ();\n sub u2 ();\nendmodule\n"),
("zz.sv", "class leaf extends base;\nendclass\n"),
];
ws.absorb(
batch.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(),
&[PathBuf::from("gone.sv")],
);
let mut expected: Vec<(&str, &str)> = vec![("z.sv", held[1].1)];
expected.extend(batch);
assert_eq!(
ws.fingerprint(),
index(&expected).fingerprint(),
"a batch folded in is the index a whole build over what is left would have"
);
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the added file took FileId(0)");
assert!(ws.units("gone").is_empty(), "and the dropped one is gone");
assert_eq!(ws.instantiations_of("sub").len(), 2, "the replaced file's new edges are in");
assert_eq!(ws.subclasses_of("base").len(), 1);
}
#[test]
fn absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index() {
// What makes a *publish* free of consequence: the scan folds records in
// whenever it happens to be asked a question, so how the same records are
// grouped into batches must not reach the result.
let records = |files: &[(&str, &str)]| -> Vec<FileFacts> {
files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect()
};
let files = [
("a.sv", "module sub;\nendmodule\n"),
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
("dup.sv", "module m;\nendmodule\n"),
];
let mut whole = WorkspaceIndex::default();
whole.absorb(records(&files), &[]);
let mut piecemeal = WorkspaceIndex::default();
for one in &files {
piecemeal.absorb(records(std::slice::from_ref(one)), &[]);
}
assert_eq!(whole.fingerprint(), piecemeal.fingerprint());
assert_eq!(whole.fingerprint(), index(&files).fingerprint(), "and both are a whole build");
assert_eq!(piecemeal.units("m").len(), 2, "the duplicate name is still disambiguated");
}
#[test]
fn absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records() {
// QA attack (`docs/features/scan-interleave/README.md`, absorb attacks):
// a duplicate path inside one batch. Not constructible through the scan
// that actually feeds `absorb` — `Scan::work` is built from `index_order`,
// which already dedupes by path — but `absorb` is a public entry point on
// `WorkspaceIndex`, and its doc comment claims "what comes out is the
// index a full build over the records it now holds would have produced."
// `WorkspaceIndex::build` goes through `index_order`, which keeps the
// *first* of a duplicate path (`Vec::dedup_by`'s contract). `absorb`'s own
// loop walks `records` left to right and overwrites on a hit, keeping the
// *last*. So handed the exact same two records for one path, the two
// entry points disagree — the claimed equivalence does not hold for a
// batch with a duplicate path. Filed as a finding, not fixed here: which
// one should win is a design call, not a QA fix.
let files = [
("a.sv", "module first_shape;\nendmodule\n"),
("a.sv", "package second_shape;\nendpackage\n"),
];
let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
let mut absorbed = WorkspaceIndex::default();
absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]);
assert_eq!(absorbed.files().len(), 1, "one file survives either way");
assert_ne!(
built.fingerprint(),
absorbed.fingerprint(),
"build (first-wins) and absorb (last-wins) disagree on a duplicate path in one batch"
);
// Naming what absorb actually did, so a fix that changes this is a
// deliberate, visible diff rather than a silent behavior change.
assert_eq!(
absorbed.fingerprint(),
index(&[("a.sv", files[1].1)]).fingerprint(),
"absorb kept the second (last) record for the duplicate path"
);
}
#[test]
fn absorbing_nothing_changes_nothing() {
// A publish with nothing staged and a finish with nothing left are both
// this call, and neither may disturb an index that is already right.
let files = [("a.sv", "module a;\nendmodule\n")];
let mut ws = index(&files);
let before = ws.fingerprint();
ws.absorb(Vec::new(), &[]);
assert_eq!(ws.fingerprint(), before);
ws.absorb(Vec::new(), &[PathBuf::from("never_held.sv")]);
assert_eq!(ws.fingerprint(), before, "dropping a file the index never held is harmless");
}
#[test]
fn removing_a_file_moves_the_disambiguation_winner() {
// The sharpest thing a removal can do to a *derived* answer: the file that
@@ -1266,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);
}
@@ -1551,8 +1709,257 @@ 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
/// printing `file:line` never has to read the file
/// (`docs/features/hover-line-index/README.md`). The awkward offsets are the
/// point: line 1 has no newline before it, the last line has none after it,
/// and both are where an off-by-one lives.
#[test]
fn every_declared_names_line_is_recorded_when_the_file_is_indexed() {
// No trailing newline, so `last_t` really is on the file's last line.
let src = "module first;\nendmodule\n\n// a comment\npackage p;\n localparam W = 8;\n\
endpackage\ntypedef int last_t;";
let index = index(&[("/w/m.sv", src)]);
let line_of = |name: &str| index.units(name).first().expect(name).lines.name;
assert_eq!(line_of("first"), 1, "a declaration on line 1");
assert_eq!(line_of("p"), 5);
assert_eq!(line_of("last_t"), 8, "the last line, with no newline after it");
assert_eq!(index.member("p", "W").first().expect("W").lines.name, 6, "members too");
// The line really is the line the text says it is: every recorded line's
// range, sliced out of the source, contains the name it was recorded for.
for (name, line) in [("first", 1), ("p", 5), ("last_t", 8)] {
let text = src.lines().nth(line as usize - 1).expect("that many lines");
assert!(text.contains(name), "line {line} is {text:?}, which does not declare {name}");
}
}
/// A `\r\n` file and multi-byte text before a declaration do not shift its
/// line: lines are counted in newlines, not in bytes or in characters.
#[test]
fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() {
let crlf = "// one\r\n// two\r\nmodule m;\r\nendmodule\r\n";
assert_eq!(index(&[("/w/c.sv", crlf)]).units("m").first().expect("m").lines.name, 3);
// Three-byte characters and a four-byte emoji ahead of the declaration:
// the byte offset of `m` is far past 3, its line is not.
let wide = "// héllo ✓ 🎉\n// ünïcödé\nmodule m;\nendmodule\n";
assert!(wide.find("module m").expect("a module") > 20, "premise: the bytes are wide");
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
/// another table.
#[test]
fn a_split_ports_two_lines_ride_the_same_carrier() {
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
let split = index(&[("/w/s.sv", src)]);
let def = split.member("m", "clk").first().expect("the port");
assert!(def.detail_span.is_some(), "premise: this port is split");
assert_eq!(def.lines.name, 2, "the header names it on line 2");
assert_eq!(def.lines.detail, Some(4), "and the body finishes it on line 4");
// An ANSI port is complete where it is named, and says so in both fields.
let ansi = index(&[("/w/a.sv", "module m (\n input wire clk\n);\nendmodule\n")]);
let def = ansi.member("m", "clk").first().expect("the port");
assert_eq!(def.detail_span, None);
assert_eq!((def.lines.name, def.lines.detail), (2, None));
}
/// The lines survive the record format, which is what makes them free on a
/// cached scan rather than only on a parsed one.
#[test]
fn a_declarations_lines_survive_the_record_round_trip() {
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
let facts = FileFacts::of(PathBuf::from("/w/s.sv"), src);
let line = facts.encode().expect("encodes");
let back = FileFacts::decode(&line).expect("decodes");
assert_eq!(back, facts, "every field, lines included");
let mut builder = vlog_semantic::IndexBuilder::new();
builder.add_facts(back);
let restored = builder.finish();
let def = restored.member("m", "clk").first().expect("the port");
assert_eq!((def.lines.name, def.lines.detail), (2, Some(4)));
}
/// QA (2026-08-28): the single-decl fixture `index_cache`'s own format-bump
/// test strips is not the only shape a genuine format-3 record could take —
/// a file declaring *two* units is the shape where a field-shift attack would
/// actually have somewhere plausible to land: if stripping the first decl's
/// two line fields shifted every read two fields early, the fields it would
/// then misread as `(name_line, detail_line)` are the *second* decl's own
/// `name` and `kind` strings. Both are always non-numeric — a Verilog
/// identifier cannot start with a digit and `kind_name` writes only letters —
/// so `Reader::num` fails on them and `decode` returns `None` rather than
/// quietly building a `Decl` out of someone else's fields. Proved directly
/// here, generalizing `index_cache`'s stripper to more than one declaration,
/// rather than only argued.
#[test]
fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
let src = "module a; endmodule\nmodule b; endmodule\n";
let facts = FileFacts::of(PathBuf::from("/w/two.sv"), src);
let encoded = facts.encode().expect("encodes");
let format_3 = strip_every_decls_line_fields(&encoded, 2, 0);
assert_ne!(format_3, encoded, "premise: fields were actually removed");
assert!(
FileFacts::decode(&format_3).is_none(),
"a two-unit format-3 record decoded as a format-4 one: {format_3}"
);
// The mixed case: one unit with a member that has a real detail span (a
// split port), so the decls being stripped are not even the same width
// of *content* — only of field count, which is what the format promises.
let split = "module m (\n clk\n);\n input wire clk;\nendmodule\n\
module other; endmodule\n";
let facts = FileFacts::of(PathBuf::from("/w/mixed.sv"), split);
let encoded = facts.encode().expect("encodes");
let format_3 = strip_every_decls_line_fields(&encoded, 2, 1);
assert_ne!(format_3, encoded, "premise: fields were actually removed");
assert!(
FileFacts::decode(&format_3).is_none(),
"a mixed unit+member format-3 record decoded as a format-4 one: {format_3}"
);
}
/// 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");
// 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 * (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
@@ -1658,3 +2065,176 @@ fn a_degenerate_file_still_makes_a_record() {
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}");
}
}
// ----------------------------------------------------------------------
// Facts from an analysis the caller already has (index-scope, 2026-08-28)
// ----------------------------------------------------------------------
/// The analysis a server holds for an open buffer, built exactly the way
/// `lucisv_server::state::Document::new` builds it — one lex, the tree from a
/// clone of that token stream, the define table off the same tokens, and the
/// same all-or-nothing lex-failure branch.
fn as_a_server_analyzes(
src: &str,
) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics, vlog_parser::LineIndex) {
let (tokens, tree) = match tokenize(src) {
Ok(tokens) => {
let (tree, _) = parse_tolerant(tokens.clone(), src);
(tokens, tree)
}
Err(_) => (Vec::new(), parse_source_tolerant(src).0),
};
let defines = collect_defines(&tokens);
let sem = analyze(&tree, src);
(tree, defines, sem, vlog_parser::LineIndex::new(src))
}
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
///
/// The record format is the comparison — the encoded line is every field the
/// index and the persistent store ever read — so a byte-equal line is the
/// whole equivalence. Two paths that could drift here would be a corruption
/// seed: the index would describe a buffer by facts its own parse disagrees
/// with.
#[test]
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
let crafted = [
// Nothing at all, and nothing that lexes.
"",
" \n\t\n",
"this is not verilog\n",
"module m;\n \"unterminated\n",
"// just a comment\n",
// The declaration kinds `facts_of` reads off the file scope.
"package p;\n localparam W = 8;\n typedef logic [W-1:0] word_t;\n\
\x20 function int f(int a); return a; endfunction\nendpackage\n",
"module top #(parameter N = 4) (input logic clk, output logic q);\n\
\x20 sub u_a (.clk(clk));\n sub u_b (.clk(clk));\nendmodule\n",
// Classes, inheritance, and a class nested in a package.
"class base; endclass\nclass derived extends base;\n int x;\nendclass\n",
"package pkg;\n class inner extends outer_base;\n typedef int t;\n endclass\nendpackage\n",
// `define`s, including a parameterised one and an `undef`.
"`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n`undef WIDTH\n\
module m; logic [`WIDTH-1:0] w; endmodule\n",
// External candidates: imports, scope resolution, port connections.
"import other_pkg::*;\nimport third_pkg::thing;\nmodule m;\n\
\x20 other_pkg::word_t w;\n assign w = thing;\n child u (.port_a(w));\nendmodule\n",
// An instantiation at file scope — deliberately *not* an edge — and a
// generate body, which is one site however many instances it makes.
"sub u_orphan (.clk(clk));\nmodule m;\n generate for (genvar i = 0; i < 4; i++) begin\n\
\x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n",
// A tree with error nodes: the tolerant parse still contributes.
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n",
];
for src in crafted {
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, src, &lines);
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
assert_eq!(
from_analysis.encode(),
from_text.encode(),
"and so do their encoded forms for {src:?}"
);
}
}
/// The same claim over every file of the real corpus, which is where the
/// constructs nobody thought to craft live.
#[test]
fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !root.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut files = Vec::new();
corpus_files(&root, &mut files);
files.sort();
assert!(!files.is_empty(), "corpus/ exists but holds no Verilog");
let mut checked = 0usize;
for path in &files {
let Ok(src) = std::fs::read_to_string(path) else {
continue;
};
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, &src, &lines);
assert_eq!(
from_analysis.encode(),
from_text.encode(),
"the records differ for {}",
path.display()
);
checked += 1;
}
eprintln!("facts equivalence: {checked} corpus files, every record byte-identical");
}
fn corpus_files(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
corpus_files(&path, out);
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
out.push(path);
}
}
}
/// An index built from records read off analyses is the index the parses
/// build, byte for byte — the house witness, at index scale rather than at one
/// file's.
#[test]
fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text() {
let files = [
("/w/pkg.sv", "package p;\n localparam W = 8;\n class c; int x; endclass\nendpackage\n"),
("/w/sub.sv", "module sub (input logic clk, input logic [7:0] d);\nendmodule\n"),
(
"/w/top.sv",
"import p::*;\n`define TAG 1\nmodule top;\n logic [W-1:0] w;\n\
\x20 sub u_a (.clk(w[0]), .d(w));\n sub u_b (.clk(w[0]), .d(w));\nendmodule\n",
),
("/w/kid.sv", "class kid extends c;\nendclass\n"),
("/w/junk.sv", "module broken (;\n"),
];
let from_text = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
let mut builder = vlog_semantic::IndexBuilder::new();
// Deliberately not path order: the reuse must not smuggle an ordering in.
for (path, src) in files.iter().rev() {
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
builder.add_facts(FileFacts::from_analysis(
PathBuf::from(*path),
&tree,
&defines,
&sem,
src,
&lines,
));
}
let from_analyses = builder.finish();
assert_eq!(from_analyses.fingerprint(), from_text.fingerprint());
// And the same through the incremental door: `update_facts` must leave the
// index `update_file` would have left.
let mut updated = from_text.clone();
let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n";
let (tree, defines, sem, lines) = as_a_server_analyzes(changed);
updated.update_facts(FileFacts::from_analysis(
PathBuf::from("/w/pkg.sv"),
&tree,
&defines,
&sem,
changed,
&lines,
));
let mut parsed = from_text.clone();
parsed.update_file(PathBuf::from("/w/pkg.sv"), changed);
assert_eq!(updated.fingerprint(), parsed.fingerprint(), "update_facts == update_file");
}
+290
View File
@@ -0,0 +1,290 @@
# change-debounce
## Goal
Stop paying a full reanalysis for every keystroke. Before this round each
`textDocument/didChange` notification ran `set_document` immediately — lex,
parse, `analyze`, `resolve_external`, lint, publish — so a burst of ten
keystrokes cost ten of everything and nine of those answers were thrown away
before anyone could read them. A `didChange` now only records the buffer's new
text as *dirty*; the analysis runs at the first moment anything actually needs
it: the next request, the next non-`didChange` notification, or a 150 ms
quiet-period timer in the message loop. The buffer's **text** is still exactly
current after every notification — only the analysis of it is deferred — so
nothing that reads `didChange` results out of order can see a stale buffer.
On a 10 000-line file one deferred keystroke saves 31 ms of work
(`docs/perf/README.md`); a ten-keystroke burst saves nine of them.
## Assumptions
- **A client sends a burst, not a single change.** Typing produces
notifications faster than 150 ms apart; the debounce only pays off while
that is true, and costs at most 150 ms of latency when it is not.
- **150 ms is short enough not to be felt and long enough to coalesce a
burst.** It is the same order as the debounce every mainstream language
server uses. It is a constant (`CHANGE_DEBOUNCE` in `server.rs`), not a
setting: a knob here would be one more thing to get wrong, and no user has
asked for one (`TODO.md` §7, "no option explosion").
- **Diagnostics are the one answer nobody requests.** A pushing client never
asks for them, so waiting for "the next request" alone would leave a file
undiagnosed indefinitely for a user who types and then stops. That is the
whole reason the timer exists, rather than flushing only on demand.
- **A flush is cheap to trigger from anywhere.** `flush_dirty` returns
immediately when nothing is dirty, so the calls at the top of `request` and
`notification` cost a `Vec::is_empty` on every message.
- **Order within a burst does not matter, order across buffers does.** Dirty
buffers are flushed oldest-first (`mark_dirty` replaces an entry in place
rather than moving it to the back), so the sequence of `publish` calls a
client sees for two edited files is the order they were first edited in.
- **Losing an unanalyzed change with its buffer is correct.** `didClose`
drops the buffer's pending text: there is nothing left to flush it into,
and the client is not looking at the file any more. The drop happens at the
*top* of `notification`, ahead of the universal flush — doing it in the
`didClose` arm is too late, because the flush has already run by then (QA,
CD-1). Closing one buffer says nothing about the others, so every other
dirty buffer flushes on that same notification exactly as before.
## Handshakes
- **Amends `docs/features/incremental-sync/README.md`'s pinned invariant.**
That round promised "one `didChange` = one `set_document` = one generation
bump, however many ranges". The promise is now: **one *flush* is one
`set_document`, one generation bump and one `publish` per dirty buffer** —
however many ranges *and however many notifications* were coalesced into it.
Everything the old promise protected still holds: the generation counter
(which is `docs/features/pull-diagnostics/README.md`'s whole `resultId`)
never moves twice for work that happened once, and never fails to move for
a buffer whose text changed. `incremental-sync`'s own test,
`one_notification_is_one_generation_bump_however_many_ranges`, still passes
unchanged, because the test helper flushes after each notification — which
is exactly the quiet-period timer firing.
- **Observable consequence, pinned in `crates/lucisv_server/tests/e2e.rs`**
(`incremental_changes_are_advertised_and_applied_over_the_wire`):
**intermediate diagnostics states are no longer published**. Two changes
arriving back to back — the first breaking a line, the second finishing it
— used to produce three publishes (open, broken, fixed) and now produce two
(open, composed). Every state that *is* published is a state the buffer
really passed through; there are simply fewer of them. That test asserted
the old count and now asserts the new one, with the reason written beside
it.
- **Consumes `sync::apply_changes` unchanged.** Ranged changes are composed
against the newest text the server holds, which while a buffer is dirty is
the *pending* text, not the last analyzed one. `Server::notification` looks
in `dirty` before `workspace.document`. Nothing in `sync.rs` moved.
- **Consumes `lsp_server`'s queue as a `std::sync::mpsc` receiver.** The
timer is `Receiver::recv_timeout` on the queue `cancel-request` already
introduced (`docs/features/cancel-request/README.md`); no thread and no
timer object was added. A `Disconnected` receiver ends the loop exactly as
the old `while let Ok(..)` did.
- **Promises every request still sees the client's own changes.** The flush
at the top of `Server::request` runs before dispatch, so a request answered
after a `didChange` is answered from that change's analysis — the order
contract the loop always had. The large-file fast path is behind that
flush, not in front of it.
- **No protocol change, no settings change, no index change.** The
capabilities advertised at `initialize` are byte-identical.
## Status / TODO
- [x] `dirty: Vec<(Uri, String)>` on `Server` — newest text per buffer, in
first-dirtied order.
- [x] `mark_dirty` replaces in place, so a burst does not reorder buffers.
- [x] `flush_dirty` — one `set_document` + one `publish` per dirty buffer.
- [x] `didChange` composes ranges against the pending text when there is one.
- [x] Flush on every request, before dispatch.
- [x] Flush on every notification that is not a `didChange`.
- [x] `CHANGE_DEBOUNCE` (150 ms) quiet-period flush in `run`, via
`recv_timeout`, only while something is dirty.
- [x] `didClose` drops the buffer's pending change — before the flush, so the
drop is real (QA, CD-1), pinned by
`closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`.
- [x] Test: a burst is one reparse
(`a_burst_of_changes_coalesces_into_one_reparse`).
- [x] Server tests drive one notification at a time, so the test helper
`change()` flushes — documented there as the timer firing.
- [x] e2e: the publish count and the reason for it.
- [ ] Not done: a flush for a *long* burst that never pauses (a paste-and-hold
or a client replaying a file's history sends changes closer together
than 150 ms forever). Today such a burst is analyzed when it ends or
when the next request arrives. A "flush after N pending changes"
backstop is the obvious answer if anyone ever reports it; it is not
written because no client behaves that way and an untested backstop is
worse than none.
## Work log
**2026-08-28 — dev.** Implemented as part of the LSP performance round
(plan: "Improve LSP performance + hover accuracy", part A1).
- The deferral is a `Vec`, not a `HashMap`: it holds one entry per *dirty*
buffer, which is one in practice and two while a user alt-tabs. A linear
scan of that is cheaper than hashing a `Uri`, and the `Vec` gives the flush
order for free.
- Deferred **analysis only, never text**. The alternative — deferring
`apply_changes` too and keeping a queue of unapplied changes — was
rejected: every reader of `Document::text` would then need to know about
the queue, and the ones that forgot would be silently wrong. Composing the
text eagerly keeps the pending state to exactly one `String` that only
`didChange` and `flush_dirty` know about.
- The flush points were chosen to be exhaustive rather than clever: *every*
request and *every* notification except the one being deferred. Anything
that needs analysis is downstream of one of those two, so there is no
handler that has to remember to flush for itself.
- `run` only arms the timeout while something is dirty, so an idle server
still blocks in `recv()` and wakes for nothing.
- The server unit tests drive notifications one at a time through a helper
rather than through the loop, so no burst ever forms and nothing would
flush them; the helper flushes explicitly, which is the timer's behavior.
Three tests that hand-rolled a `didChange` notification were moved onto
that helper.
**2026-08-28 — dev (QA fix).**
- **CD-1 — fixed.** The `didClose` arm's `dirty.retain` was dead code: the
universal flush at the top of `notification` had already drained `dirty`
through `std::mem::take` by the time the arm ran, so a buffer closed
mid-edit paid a full `Document::new` and published its real diagnostics one
line before the close cleared them. The retain moved to the top of
`notification`, *ahead* of the flush, guarded on the method name; the arm's
comment now says where the drop happened instead of pretending to do it.
- The uri has to be read without consuming the notification, since
`extract` takes it by value and the arm below still needs it. That is a
four-line `closing_uri` beside `extract`, deserializing a clone of the
params — a `didClose`'s params are a single uri, so the clone is not
worth avoiding with a peek into the raw `Value`. `None` (params that do
not parse) drops nothing, which is exactly what the arm below already
does with the same params.
- The "flush on every notification but `didChange`" rule is unchanged: the
flush still runs for `didClose`, and every *other* dirty buffer still
goes through it. What changed is only that the closing buffer is no
longer in `dirty` when it does.
- Pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`
(`server.rs`): two buffers dirtied with text that would diagnose, one
closed with no request in between; the generation bumps exactly once (the
buffer still open), the closed buffer gets exactly one publish and it is
the clearing one, and the other buffer's pending edit is published as
usual. Verified the test fails on the pre-fix code — `left: 5, right: 4`
on the generation assertion — before keeping it.
## QA log
**2026-08-28 — QA.** Gates run and green: `cargo fmt --check`,
`cargo clippy --all-targets --workspace -- -D warnings`, `cargo test
--workspace` (0 failed everywhere; `lucisv_server`: 1179 passed, 19 ignored
perf tests), `cargo test -p vlog_formatter` (114 passed). All findings below
were reproduced with temporary `#[test]`s added to `server.rs`, run, and then
removed once confirmed — none are left in the tree.
- **Finding CD-1 (medium — contradicts a checked-off invariant, wastes work,
does not corrupt anything).** `didClose` does **not** actually drop a
buffer's pending dirty change before analyzing it. `Server::notification`
(`server.rs:1247`) flushes unconditionally for any non-`didChange` method
(`server.rs:1253`, `if method != DidChangeTextDocument::METHOD { self
.flush_dirty(); }`) — and `didClose` is such a method. That flush runs
*before* the `match` statement even reaches the `DidCloseTextDocument::
METHOD` arm (`server.rs:1407`), so by the time `self.dirty.retain(|(pending,
_)| *pending != uri)` executes (`server.rs:1413`), `flush_dirty` has already
drained `self.dirty` via `std::mem::take` — the retain is a no-op in the
normal flow. Net effect: closing a buffer that was mid-edit costs one full,
wasted reparse + `publish` of the real (about-to-be-discarded) diagnostics,
immediately followed by the close handler's own `send_diagnostics(uri,
Vec::new())` clearing them — **two** publishes instead of the zero extra
ones the design claims. This directly contradicts both the checked-off
status-line "`[x]` `didClose` drops the buffer's pending change" and the
code comment beside the (dead) retain: "there is nothing left to flush it
into" — there is, and it does get flushed.
- Repro (temporary test, `server.rs`, removed after confirming): open a
clean buffer (`module m;\nendmodule\n`), drain the open publish, note
`generation`, send one `didChange` to `module m;\n wire ;\nendmodule\n`
(introduces a parse error, buffer stays dirty — `generation` provably
unchanged, `dirty` non-empty), then send `didClose` with **no** request
in between (`session.notify`, which calls `Server::notification`
directly, exactly the production path — no manual flush helper
involved). Observed: `generation` bumps by exactly one during the
`didClose` call (`2` → `3`), and `session.published()` returns **2**
messages: one carrying the real parse-error diagnostic
(`"expected identifier (found \";\")"`), then one with `diagnostics: []`.
- Not a data-corruption bug — the client ends up with the correct final
state (empty diagnostics for a closed file) — but it is a real,
reproducible functional gap in exactly the case the debounce is supposed
to help most: a user who edits and then immediately closes a buffer pays
the full analysis cost the feature exists to avoid, silently. Left
unfixed (not small/unambiguous — the right fix wants a decision about
whether the top-of-`notification` flush should special-case `didClose`,
or whether `didClose` should remove its own `dirty` entry *before* that
flush runs, which touches the "flush on every notification but
`didChange`" rule this round explicitly checked off).
- **Attack angles from the brief, checked and clean:**
- *An un-flushed edge, generally.* Every request and every non-`didChange`
notification flushes at its own top (`server.rs:1253` for notifications,
the equivalent at the top of `request`), so the only genuinely
un-flushed state is "nothing has asked for analysis yet" — which is
exactly what the quiet-period timer exists to bound at 150 ms, and the
documented, un-checked TODO item (a burst that never pauses) is real but
already honestly disclosed, not silently missing.
- *`didChange` on a file the client never opened.* `mark_dirty` does not
require a prior `didOpen`, and neither did the pre-debounce
`set_document` call it replaces — `flush_dirty`'s `set_document` creates
the buffer exactly as before. No new behavior here.
- *`didChange` racing `didSave`.* `didSave` is not `didChange`, so it
flushes first (`server.rs:1253`) — a save's reindex always sees the
latest edited text analyzed, never a stale buffer racing a fresh disk
scan.
- *Version-number ordering.* The server does not track LSP version numbers
at all (`publishDiagnostics`'s own `version` field is hard-coded `None`
at `server.rs:1848`, unchanged by this round) — nothing new to get out of
order.
- *Pending vs. analyzed text observed inconsistent by a request.* Cannot
happen: `request` flushes before dispatch (`server.rs`'s `fn request`),
so a request is always answered from the analysis of whatever is
currently held, dirty or not.
- *The `e2e.rs` publish-count change (3 → 2).* Confirmed the buffer
genuinely passed through both published states and no diagnostic was
lost: traced `incremental_changes_are_advertised_and_applied_over_the_wire`
— the two `didChange` notifications and the `textDocument/formatting`
request all arrive in one write to the mock transport, so the request's
own top-of-`request` flush (or the burst's internal ordering) coalesces
both notifications into the one flush that produces publish #2; publish
#1 is the clean `didOpen`. The removed middle publish (the transiently
*broken* half-edited state) was never a state a real, unhurried client
would see anyway — it is the debounce's whole point.
- *`a_burst_of_changes_coalesces_into_one_reparse`.* Re-derived by hand:
`generation` provably does not move across the two-notification burst,
then moves by exactly one at the first request after it, and `dirty` is
empty afterward — matches the claimed semantics exactly.
- **Perf claims (A1's "before/after" in `docs/perf/README.md`).** Arithmetic
over already-measured numbers, not a separate measurement — reviewed there,
no finding.
## Review
**2026-08-28 — lead.** Accepted. Gates re-run independently of both agents:
`cargo fmt --check` clean, `cargo clippy --all-targets --workspace -D
warnings` silent, `cargo test --workspace` green.
The shape is right. Deferring analysis while applying text immediately is the
standard split, and flushing before every request and before every
non-`didChange` notification means no handler ever reads a stale buffer —
today's correctness guarantee is preserved exactly, and only keystroke-storm
reparses are coalesced. The quiet-period timer in `run()` matters as much as
the coalescing: diagnostics are the one answer a client never asks for, so a
burst that ends in silence still gets drawn.
QA's CD-1 was a real finding and correctly diagnosed: the universal flush ran
*before* the `didClose` arm, so the arm's `retain` was dead and a buffer
closed mid-burst paid a full `Document::new` and published diagnostics for a
file the user had stopped looking at, only to clear them a line later. The
fix drops the pending text ahead of the flush rather than special-casing the
flush, which keeps "every other dirty buffer still flushes" true by
construction. The dev verified the pinning test fails on pre-fix code before
keeping it; that is the right standard.
The one honest cost is recorded in `docs/perf/README.md` and is not hidden: a
keystroke with *nothing* following it now publishes at 164 ms rather than one
flush, because it waits out the 150 ms quiet period. Any request flushes
early, so a real editor sees 4.35 ms / 37.6 ms instead — but the regression
is real for a client that asks for nothing, and the number is written down
rather than argued away.
+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
+123
View File
@@ -59,6 +59,15 @@ entirely whenever it could be the wrong line.
is the only thing that colours a hover card.
- Nothing is added to `Def`, to the facts file, or to `FACTS_FORMAT`; a cache
written before this round is still current after it.
**Superseded 2026-08-28 by `docs/features/port-detail-spans/README.md`**,
which adds `Def::detail_span`, writes it in every declaration record and
bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is
discarded. This round's own promise held while it was this round's to
make; the index is text-free either way (a span is not text).
**Superseded again 2026-08-28 by `docs/features/hover-line-index/README.md`**,
which adds `Def::lines` (each declaration's line number) and bumps
`FACTS_FORMAT` 3 → 4. Same reading: a line number is not text either, and
it is what makes this feature's heading free.
- The heading line `**label** — declared in `file:line`` is unchanged, so a
client (or a test) reading only that half sees exactly what it saw before.
@@ -119,6 +128,17 @@ The character cap counts `char`s and cuts on a boundary.
- Not done, deliberately: no facts/cache change, nothing in `vlog_semantic`,
no TODO.md edit (no existing checklist item covers this; §8's hover items
are all already checked, and inventing one is out of scope).
- [x] **2026-08-28**: one disk read per file per hover (`disk_view` memo);
QA finding 4 closed.
- [x] **2026-08-28**: `live_symbol` (and `nav::indexed_references`) look a
name up instead of scanning every symbol, with the first-match
tie-break pinned by test.
- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior
`\r` into the fence; QA finding 2 closed.
- [x] **2026-08-28** (`docs/features/hover-line-index/README.md`): the disk
path's heading costs no read at all (`Def::lines`) and its snippet's
read is shared across hovers, so the second hover into a closed file is
free. `disk_view` is gone, subsumed by `Workspace::file_view`.
## Work log
@@ -164,6 +184,103 @@ The character cap counts `char`s and cuts on a boundary.
| `a_declaration_spanning_many_lines_is_cut_at_the_line_limit` | the line cap, via an open module whose `decl_span` is its body |
| `two_files_declaring_one_name_each_get_their_own_snippet` | ambiguous name: both headings, both snippets |
### 2026-08-28 — dev (performance: one disk read, one name lookup)
Parts A2 and A3 of the "Improve LSP performance + hover accuracy" round.
Behavior of every card is unchanged; both items are the same answer, reached
with less work. Numbers in `docs/perf/README.md`.
- **A2 — one read per file per hover.** A hover into a *closed* file used to
read that file and build a `LineIndex` over it twice: once in
`locate::line_number` for the `file:line` heading, once in
`declaration_snippet` for the fenced lines. This is QA's finding 4 below,
and it is now closed. `symbol_hover` holds a per-request memo — one
`(path, text, LineIndex)` in `disk_view` — that the heading and the snippet
both read, and `declaration_snippet` no longer touches the disk at all: it
is now the *open-buffer* path only, with the closed-file path inlined in
`symbol_hover` beside the heading it shares a read with. The
`spells_exactly` guard applies on both paths exactly as before. A card
naming one file twice (two declarations in one file) now pays for one read,
not two, which is why the memo is keyed by path rather than being a single
`Option` per candidate.
- Measured: 34 ms → 16.3 ms on QA's own 31.7 MB measurement, and 141 µs of
a 148 µs hover at 10 000 lines is that one read. See `docs/perf`.
- QA's measurement test was renamed
`hovering_into_a_large_closed_file_reads_it_twice` →
`..._reads_it_once`, since the doubling it was named for is gone. The QA
log below still names the old spelling; that section is QA's to amend.
- **A3 — `live_symbol` stops scanning every symbol.** Walking the whole
buffer's symbol table and calling `nav::indexed_def_for_symbol` (two index
lookups) on every symbol whose name happened to match — and reaching every
symbol whose name did not — became a name-keyed lookup:
`vlog_semantic::Semantics::symbols_named(name)`, two binary searches over a
side table of symbol ids sorted by name, built once during `analyze`. Only
same-named declarations are probed. A side table rather than a
`HashMap<String, Vec<SymbolId>>` so that `Semantics` — which is cloned per
document — does not carry a second copy of every name it already holds;
four bytes per symbol against a `String` per symbol.
- **The tie-break is preserved.** The map's lists are built by walking the
symbols in order, so `symbols_named` yields declaration order — the same
order, and the same first match, the old `symbols().iter().find(..)`
made. Pinned by `looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
in `crates/vlog_semantic/tests/semantics.rs`, which compares the two
answers directly and asserts the earlier declaration comes first. QA's
`duplicate_live_declarations_of_one_name_pick_the_first_one_silently`
(finding 3 below) still passes, unchanged.
- `nav.rs`'s `indexed_references` had the same scan-by-name for the
declaration's live span; it is the same swap and was made in the same
change, for the same reason.
- `vlog_refactor::ports.rs:1154` has a third one (`symbols().iter()
.position(|s| s.name == port && …)`). It is not a trivial swap — the
predicate carries a kind and a span test and the code wants the
*position* as a `SymbolId` — and it is in another crate, so it is left
alone and recorded here rather than done.
- Cost: four bytes per symbol. Measured saving on the lookup alone:
8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`).
### 2026-08-28 — dev (the heading stops reading the file at all)
Round `hover-line-index` — full argument, measurements and tests in
`docs/features/hover-line-index/README.md`. What changed *here*:
- **The `External` arm's disk branch no longer reads anything for the
heading.** `Def` now carries `lines: DeclLines`, recorded when the file was
indexed, so `**port** — declared in `sub.sv:2`` is a field lookup. The live
branch is untouched and still asks the open buffer's own line index, because
that buffer may hold unsaved edits the index has not seen — the same reason
`declaration_snippet` matches a `Def` to a live symbol logically.
- **`disk_view` was deleted.** Its job — one read per file per hover — is now
`Workspace::file_view`'s, which does it once per file per *generation of that
file*, so the next hover into the same file reads nothing. The four points
that drop a held view are listed in that round's Handshakes.
- **`spells_exactly` and both caps are untouched**, and a stale held view can
only ever make a snippet vanish. Every existing test in this file passed
unmodified.
- **One corner moved deliberately**: a closed file that cannot be *read* now
still gets its line in the heading (`sub.sv:2` rather than a bare `sub.sv`),
because the line no longer depends on the read. Pinned by
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read`.
- Measured: a hover into a 12 MB closed file, 6.2 ms → **0.95 µs** on the
second hover; the 31.7 MB probe above, 17.0 ms → **4.4 µs** on the second.
The first touch is unchanged, because the snippet genuinely wants the text.
### 2026-08-28 — dev (CRLF, closing QA finding 2)
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
`\r` inside the fence — is **fixed**, as part of `port-detail-spans`' PDS-4.
Every line a card shows now goes through `attached_lines`, which strips a
trailing `\r` as it composes each line; that covers both this feature's
snippet path and `local_text`'s in-file path, which QA named as having the
same property, because both reach it through `fenced_sections`. Display
text only: no buffer is written.
- QA's pinned regression test was named for the old behaviour
(`a_crlf_multiline_snippet_keeps_interior_carriage_returns`) and asserted
it; it is now `a_crlf_multiline_snippet_carries_no_carriage_returns` and
asserts the opposite, plus that the lines read as written. The QA log below
still names the old spelling; that section is QA's to amend.
- No other change to this feature. `spells_exactly`, the caps and the
disk/live split are untouched.
## QA log
### 2026-08-27 — QA
@@ -277,6 +394,12 @@ charter's "note it, don't redesign" rather than attempted.
`hovering_into_a_large_closed_file_reads_it_twice`, `hover.rs:1325`. Run
with `cargo test --release -p lucisv_server large_closed -- --ignored
--nocapture`.
- **Amended 2026-08-28 — QA.** Closed by A2 (`docs/perf/README.md`):
`symbol_hover`'s `disk_view` memo now shares one read + one `LineIndex`
between the heading and the snippet. Re-ran the same measurement (now
named `..._reads_it_once`): **17.0 ms**, against the documented
"34 ms → 16.3 ms" — matches within the run-to-run noise `docs/perf/
README.md` itself calls out. No longer an open finding.
**Verified, no finding** (angles from the charter that turned up nothing):
UTF-8 multi-byte content before a declaration, on the same file, does not
+551
View File
@@ -0,0 +1,551 @@
# hover-line-index
## Goal
The owner's report (2026-08-28): hovering a module instantiation is slow, and
hovering one of its ports — to see the port's own declaration — is slow on the
**first** try. Both land on the same code: a hover whose target is declared in
a *closed* file read that whole file and built a whole `LineIndex` over it, for
two things at once — the heading's `file:line`, and the fenced snippet of the
declaration. On a netlist-adjacent file that read is milliseconds, and nothing
was kept, so the *next* hover into the same file paid it again. The owner's
design, which this round implements: put each declared name's **line number**
into the index itself, where it costs a `u32` per declaration and is computed
once when the file is scanned. The heading then costs no file access at all,
and only the snippet still wants text — served from a small bounded cache of
closed files' text in `Workspace`, so the first touch pays one read and no
touch after it pays anything.
The shape of what that buys, measured below: a hover into a 12 MB closed file
goes **6.2 ms → 0.9 µs on the second hover** and stays 6.2 ms on the first;
the steady-state cross-file hover on a 10 000-line file goes **157 µs →
13 µs**. The round also *measured the other suspect* and did not fix it — see
Handshakes.
## Assumptions
- **A line is a fact about the same snapshot the span is.** `Def::name_span`
and `Def::lines.name` are read off one text in one pass, so a heading and a
snippet can never name different generations of a file. Where the file has
changed on disk with nothing telling the server, both are stale together,
which is strictly better than the previous shape — a stale *offset* looked
up in *fresh* text, whose line was arbitrary.
- **Lines are 1-based, and are exactly what `LineIndex::line_col` reports.**
That is what `locate::line_number` returned before, so the same headings come
out.
- **`FileFacts::from_analysis`'s caller has a line index already.** It is a
server holding an open buffer's finished `Document`, which carries one. So
the extra parameter costs the caller nothing, and `FileFacts::of` builds its
own — one pass over the source's newlines, about 1 % of the parse it sits
beside (`docs/perf/README.md`: `LineIndex::new` 115 µs against
`parse_tolerant` 14.3 ms at 10 000 lines).
- **The view cache is a cache and never a correctness input.** Every entry can
be dropped at any moment with no change to any answer; a *stale* entry can
only ever make a snippet disappear, never make it wrong, because
`hover::spells_exactly` still checks the text at the span against the hovered
name before anything is shown. That guard is unchanged and is still the last
line of defence.
- **Only closed files are cached.** `Workspace::file_view` returns `None` for a
path an open buffer speaks for: that buffer's `Document` already holds its
text and line index, and a second copy here would be a second opinion.
- **The index is still text-free.** A line number is not text, exactly as a
span is not text (`docs/features/workspace-index/README.md`'s promise, and
the same reading `port-detail-spans` took for `detail_span`).
## Handshakes
### `vlog_semantic` — `DeclLines`, and the carrier's extension story
```rust
/// Where a declaration sits in its file, counted in lines.
pub struct DeclLines {
pub name: u32, // 1-based line of the declared name
pub detail: Option<u32>, // 1-based line the detail span starts on
}
pub struct Def {
pub file: FileId,
pub name_span: TextRange,
pub kind: SymbolKind,
pub detail_span: Option<TextRange>,
pub lines: DeclLines, // new
}
// One added parameter, because a record now carries lines:
impl FileFacts {
pub fn from_analysis(path, tree, defines, sem, lines: &LineIndex) -> FileFacts;
}
pub const FACTS_FORMAT: u32 = 4; // was 3
```
**The carrier is one value per declaration, and it extends by gaining a
field.** That is the owner's explicit ask ("keep the implementation flexible so
we might even cache the port location") answered structurally rather than
promised:
- **Ports already ride it.** A module's ports and parameters are indexed as
*members*, and a member is a `Decl` exactly as a unit is — so
`index.member("sub", "addr").lines.name` is that port's line, recorded in the
same pass, with no extra table, no extra pass and no extra decision about
"small projects". The owner's optional second step was already paid for by
the first.
- **A split port's two lines ride it too.** A non-ANSI port is named in the
header and finished in the body (`detail_span`,
`docs/features/port-detail-spans/README.md`), and `DeclLines::detail` is that
body's line — the second position datum, already present, in the same value.
- **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. **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
(`CLAUDE.md`, "Simplicity first").
### `vlog_semantic` — `FACTS_FORMAT` 3 → 4, justified
A record's per-declaration group grew two fields. The rule written at the
constant is that **any** change to what a record holds bumps the format, and
the reason it is a whole-store discard rather than a migration is
`docs/features/index-persistence/README.md`'s: a reader that guessed at an
older layout would read last month's field order as this month's. Concretely,
a format-3 record read as a format-4 one would shift every field after the
first declaration by two — which is why the format field in the store's header
catches it first, and why `decode` rejects it even if something served it past
the header (both pinned, see Tests). The cost is one re-parse of the workspace
on the first scan after upgrading; the corpus measurement below says that is
about 175 ms.
### `vlog_semantic` — fingerprint
`WorkspaceIndex::fingerprint`'s `sym` line now carries `line=` and `detail=`.
That is what makes the house witness — incremental index == fresh build —
cover the new field rather than ignore it; every existing equivalence test
(`update_file`, `update_facts`, `add_facts` from records, the corpus sweep)
now compares lines as well as spans, and all of them stayed green unmodified.
### `lucisv_server::state` — the closed-file view cache
```rust
pub struct FileView { pub path: PathBuf, pub text: String, pub lines: LineIndex }
impl Workspace {
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>>;
}
```
Bounded by **four entries** and **8 MiB of text**, newest first, oldest
evicted. Two bounds because they answer two questions: how many files one
answer can name (a card names one or two; a references list walks a handful
before moving on), and how much memory a netlist-shaped file may cost. The
newest entry is kept whatever it weighs — one file can exceed the whole byte
budget on its own, and a cache that refused to hold it would be useless for
exactly the file it exists for — so a huge file simply evicts everything else.
**Every invalidation point, in full.** A view is dropped when:
| event | what is dropped | why |
|---|---|---|
| `set_document(uri, text)` — `didOpen`, `didChange`, a text-carrying `didSave` | that path's view | the buffer becomes the authority, and the held disk copy may predate the edits it carries |
| `close_document(uri)` | that path's view | disk is the authority again, and the view predates every save that buffer made |
| `update_one(path)` | that path's view | re-indexing one file *is* the claim its bytes moved |
| `rebuild_index_with(..)` | **all** views | a rescan says nothing about which file moved |
Those four are every path in the server that can change what a file holds:
`server.rs` reaches the first two directly from the sync notifications, and the
last two through `reindex_one` / `reindex`, which is where a save, a watched
file change, a client file operation and a settings change all land.
What survives all four is a file changed on disk with nothing telling this
server — and there the *index* is stale by the same event, which is precisely
what `spells_exactly` exists for.
### `lucisv_server::locate` — the sweep
`locate::line_number` and `locate::location` were the only two functions that
read a whole file to answer a position question, and `line_number`'s only
callers were `hover.rs`'s two. Both now take an open buffer's own line index
when there is one and the shared view otherwise; neither reads a file directly
any more. `location`'s open-buffer arm also stops cloning the whole buffer text
(`text_of` returns a `String`) on the way to a range. Mechanical, no behaviour
change: `location` is what `textDocument/definition`, references, the lens and
the hierarchies build their `Location`s from, and a references list over one
file now reads that file once instead of once per site.
An indexed declaration's line no longer goes through `line_number` at all —
`Def::lines` is the answer. What is left for it is the spans the index records
no line for, which today is a `` `define``'s (the macro hover card's
`defined in file:line`). Those ride the shared view, so a second macro hover
into one file is free; giving `Define` its own line would mean a field in
`vlog_parser`'s `Define` and is filed rather than done — it buys the first
touch of one card and costs a second crate a field.
### Suspect 2 — **reported, not fixed here; DELIVERED 2026-08-28** by `docs/features/scan-interleave/README.md`
The brief named a second suspect and asked for it to be measured and filed
rather than redesigned. It is real, and on the owner's own complaint it is by
far the larger of the two:
`Server::new` runs the whole startup scan **before** `run()`'s message loop
takes its first message. `main.rs` answers `initialize` (through
`initialize_finish`, which also consumes `initialized`) and only then builds
the `Server` — so everything a client sends the instant the handshake is done
sits in the OS pipe until the scan is over. Measured over a 200-file, 1 000-
line-each workspace with a filelist (so the startup scan really indexes it):
| the first hover of a session | cold store | warm store |
|---|---:|---:|
| issued the moment `initialized` was sent | **780 ms** | **287 ms** |
| the same hover once the scan is done | 64 µs | 61 µs |
Four orders of magnitude, and this round does not touch it: fixing it means
answering requests during the scan (or scanning on another thread), which is a
change to request scheduling and to what an answer *means* while the index is
half-built. `docs/features/index-persistence`'s store already takes it from
780 ms to 287 ms; the rest is the read, the completion word table's lex and
the include scan, which that feature's README already names as uncached.
**Request to whoever owns the message loop next:** this is where "the first
hover is really slow" mostly lives, and the probe that measures it is
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`.
**DELIVERED, 2026-08-28.** `docs/features/scan-interleave/README.md` took the
scan apart into per-file steps and drains the message queue between them, so a
startup scan long enough to be worth it answers requests while it runs. The
same probe, flipped and renamed
(`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`), now
reports **15.5 ms cold / 12.8 ms warm** where the table above says 780 / 287 —
and the scan's own total moved by under a percent. The request is closed; what
that round did *not* do (the files are still read eagerly, a rescan still makes
requests wait) is filed in its own Status/TODO with numbers.
## Measured
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
`--release`, `#[ignore]`d probes, `--test-threads=1`, means where the numbers
are small enough to need one. Every figure below was taken on 2026-08-28,
before and after, in the same session.
### Suspect 1 — the per-hover read
| what | before | after |
|---|---:|---:|
| hover on an **instantiation** into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms |
| — the same hover again | 5.75 ms | **0.95 µs** |
| hover on a **port** into the same file, first touch | 5.85 ms | 5.92 ms |
| — the same hover again | 5.71 ms | **0.99 µs** |
| hover into a 31.7 MB closed file, first touch (QA's own probe) | 17.0 ms | 16.8 ms |
| — the same hover again | 17.0 ms | **4.4 µs** |
| cross-file hover, 1 000-line target, mean of 20 | 39.8 µs | **4.7 µs** |
| cross-file hover, 10 000-line target, mean of 20 | 157 µs | **12.9 µs** |
| — one read + `LineIndex` of that file, for comparison | 149 µs | 158 µs |
Read the table as two claims. **The first touch is unchanged**, and it should
be: the snippet genuinely wants that file's text, and reading it is what the
6.2 ms is. **Every touch after it is free**, which is the shape the owner's
"slow on the FIRST try" report describes — and the heading half is free even
on the first touch, which is why a card with no snippet (an unreadable file, a
guard miss) now costs nothing at all.
### The price paid for it
| | before | after |
|---|---:|---:|
| whole 860-file corpus scan, no cache | 338 ms | 343 ms |
| — cold, filling the store | 372 ms | 374 ms |
| — warm, every file from the store | 197 ms | 200 ms |
| the store, 860 files | 2 312 802 B | 2 380 790 B |
The scan times are inside their own run-to-run noise: the added work is one
`LineIndex::new` per parsed file, which the flush breakdown puts at under 1 %
of that file's parse. The store grows **68 KB over 860 files — 2.9 %**, which
is the two decimal numbers per declaration over roughly 13 000 declarations,
and is the owner's "a few KB for 20 000 modules" measured on real source.
## Status / TODO
- [x] Measure both suspects before touching anything; both recorded above.
- [x] `DeclLines` on `Decl` and on `Def`, computed in `facts_from_analysis`
from the file's own `LineIndex`.
- [x] `FileFacts::from_analysis` takes the line index; `FileFacts::of` builds
one.
- [x] Record codec: two fields per declaration, `FACTS_FORMAT` 3 → 4, with the
justification above.
- [x] `WorkspaceIndex::fingerprint` carries the lines, so incremental == fresh
covers them.
- [x] `Workspace::file_view` — bounded, LRU, four named invalidation points.
- [x] `hover.rs`: heading from `Def::lines`, snippet from the shared view; the
per-request `disk_view` memo is gone, subsumed.
- [x] `locate.rs` swept onto the buffer's index / the shared view.
- [x] Tests (11 new, listed in the work log) and two new `#[ignore]`d probes.
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
- [ ] **Not done, deliberately: `` `define``s get no indexed line.** A
`Define` is `vlog_parser`'s, and giving it a line means a field in
another crate's public type plus its own record fields, to save the
*first* macro hover into one file and nothing after it. The shared view
already covers the repeat.
- [ ] **Not done, deliberately: the other `text_of` callers are untouched.**
`rename`, `ports`, `hierarchy`, `type_hierarchy`, `completion`,
`signature`, `inlay` and `nav` read whole files because they want whole
files, not a line — the sweep was for the position-only readers. Routing
them through the view cache would mean `text_of` handing out an `Rc`
instead of a `String`, which is a different change with a different
argument.
- [x] **Reported, not fixed *here*: the first request of a session waits out
the startup scan.** Numbers and the filed request are in Handshakes;
**delivered 2026-08-28** by `docs/features/scan-interleave/README.md`
(780 ms → 15.5 ms cold, 287 ms → 12.8 ms warm).
## Work log
### 2026-08-28 — dev
**Measured first, both suspects, before a line of the fix was written.** Two
new probes were needed and are part of the round:
`perf::hovering_into_a_big_closed_file_first_touch_and_repeat` (an
instantiation and a port, into a 12 MB file, first touch and repeat separately
— the existing probes all reported means, which hide exactly the first/repeat
split the owner's report is about) and
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` (over the wire,
against the real binary, two whole sessions so the persistent store is cold in
one and warm in the other). The second answered the brief's question about
suspect 2 with a number four orders of magnitude larger than suspect 1's, which
is worth saying plainly even though this round could not act on it.
**The carrier: a struct, not a bare `u32`.** `DeclLines { name, detail }`
rather than `line: u32` on `Decl`, because the *second* datum already exists —
a split port's body line — and because the owner asked for room for more. The
alternative shapes were both worse: a bare `u32` would have needed a second
field the day `detail` was wanted (and `detail` was wanted on day one), and a
parallel table keyed by declaration would have to be kept in step with `Decl`
through the merge, the incremental update and the record round-trip, for no
consumer that exists. `Option<u32>` for `detail` rather than a `0` sentinel in
the *type*, even though the *record* writes `0` for `None`: the record's
sentinel is a framing decision (the stream stays flat, exactly as
`detail_span`'s `0 0` already does) and the type's is an API decision, and
those two should not be forced to be the same thing.
**`from_analysis` grew a parameter rather than growing a `&str`.** It could
have taken `src: &str` and built its own index, but its one real caller —
`Document::facts` — already holds a `LineIndex` over exactly that text, and
handing it over is both cheaper and more honest about what the function needs.
The test helper `as_a_server_analyzes` grew a fourth return value for the same
reason.
**`FACTS_FORMAT` 3 → 4, not 2 → 3 as the brief said.** The brief was written
against a tree where `port-detail-spans` had not yet been counted; the constant
was already at 3 when this round started. Same rule, next number.
**The heading now comes from the index on the disk path, and that is a small
behaviour change in one corner.** Before, a closed file that could not be read
produced a bare `` `sub.sv` `` heading with no line; now it produces
`` `sub.sv:2` ``, because the line no longer depends on the file being
readable. That is more information and not less, it is the line the index
recorded from the text it indexed, and it is pinned by
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` — which
deletes the file and requires the heading to survive. Every other card is
byte-identical: the full suite passed unmodified before a single new test was
added, including the stale-span, guard, CRLF, cap and ambiguity tests.
**The live path was deliberately left alone.** An open buffer's heading still
comes from that buffer's own line index and *not* from `Def::lines`, because
the buffer may hold unsaved edits the index has not seen — the same reason
`declaration_snippet` matches a `Def` to a live symbol logically instead of
reading at the indexed span (`docs/features/hover-declarations/README.md`).
Zero I/O either way, so there is nothing to win by unifying them and a
correctness property to lose.
**`disk_view` is gone, subsumed.** Its whole job — one read per file per hover
— is now the view cache's, which does the same thing per *session* instead of
per request. The per-request memo would have been a second cache in front of
the first.
**Files touched.** `crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/{state.rs,locate.rs,hover.rs,index_cache.rs,perf.rs}`,
`crates/lucisv_server/tests/e2e.rs`, this README,
`docs/features/{hover-declarations,workspace-index,index-persistence}/README.md`,
`docs/perf/README.md`, `TODO.md`. No new dependency, no `unsafe`, no
`#[allow]`, no version bump, no commits.
**Tests added.**
| test | where | pins |
|---|---|---|
| `every_declared_names_line_is_recorded_when_the_file_is_indexed` | `vlog_semantic/tests/workspace.rs` | line 1, a middle line, the last line with no trailing newline, and a member's line — each checked against the source line's own text |
| `crlf_and_multibyte_text_do_not_shift_a_declarations_line` | same | `\r\n` line endings, and three- and four-byte characters ahead of the declaration |
| `a_split_ports_two_lines_ride_the_same_carrier` | same | the extension story: a non-ANSI port's header line *and* body line, and an ANSI port's `None` |
| `a_declarations_lines_survive_the_record_round_trip` | same | encode → decode → equal, and through `IndexBuilder` to a `Def` |
| `a_store_from_any_previous_facts_format_is_dropped_not_misread` | `lucisv_server/src/index_cache.rs` | **rewritten**: every format `1..FACTS_FORMAT` is discarded by the header, *and* a genuine format-3 record (today's minus the two line fields) fails `decode` even served past the header. Was pinned at the literal `2` and would have gone on testing 2 forever |
| `a_closed_files_text_is_read_once_and_then_reused` | `lucisv_server/src/state.rs` | the cache exists: the file is rewritten behind the server's back and the second view is the first |
| `a_file_an_open_buffer_speaks_for_has_no_view_of_its_own` | same | closed files only |
| `every_way_a_files_text_can_move_drops_its_view` | same | all four invalidation points, each by the same warm-change-event-check experiment |
| `the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text` | same | both bounds, LRU order, and that a file over the whole byte budget is still cached and evicts the rest |
| `a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` | `lucisv_server/src/hover.rs` | the round's central claim: the file is deleted and the heading still names its line, snippet correctly dropped |
| `a_second_hover_into_one_closed_file_reads_nothing` | same | the snippet's read is shared: the file is rewritten and the second card is the first |
Two `#[ignore]`d probes added (`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`,
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`); one existing probe
(`hovering_into_a_large_closed_file_reads_it_once`) grew a second timing so it
reports the repeat beside the first touch.
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` silent. `cargo test --workspace` green, 0 failed. The counts, by
binary: `lucisv_server`'s unit tests **1 210 passed / 24 ignored** (+6 passing,
+1 `#[ignore]`d probe), its `e2e` suite **56 passed / 2 ignored** (+1
`#[ignore]`d probe), `vlog_semantic`'s `workspace` suite **66 passed** (+4).
One test was renamed rather than added
(`a_store_from_the_previous_facts_format_is_dropped_not_misread` →
`a_store_from_any_previous_facts_format_is_dropped_not_misread`), so nothing
was quietly dropped.
## QA log
### 2026-08-28 — QA
Verdict: **SHIP.** No correctness bug found in the round's own code — every
finding below is a test-coverage gap, closed in this pass with permanent
regression tests. All seven charter items checked; details follow.
**1. Heading staleness — reproduced, and the documented window holds.**
Constructed the exact attack: index `sub.sv` from its original text, then
rewrite it on disk (`addr` moved from line 2 to line 6, and the byte offset
the index still holds for it now lands inside a comment) with no `didSave`, no
watcher event and no `update_one`/`rebuild_index` call — before any hover has
ever read the file, so the view cache is empty and the read the snippet does
is genuinely against the *new* bytes. Result: the heading still shows
`sub.sv:2` (the index's last-scanned line, not the file's true current one),
and the snippet is dropped by `spells_exactly` rather than showing whatever
now sits at that byte range — no wrong line and no wrong snippet, matching the
README's Assumptions ("both are stale together") exactly. Pinned:
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`
(`crates/lucisv_server/src/hover.rs`). The docs (this README's Assumptions
section, and `Workspace::file_view`'s doc comment at
`crates/lucisv_server/src/state.rs:1043`) already state this honestly — no
doc fix needed.
**2. `DeclLines` correctness — dev's tests already cover the awkward
offsets** (line 1, the last line with no trailing newline, CRLF, multi-byte
text ahead of the declaration, a split port's two lines, an ANSI port's
`None`) and check each recorded line against the source line's own text, not
just against a hand-computed expectation. No drift found; ran unmodified.
**3. View-cache attacks — three untested-but-correct paths, now covered.**
The cache's own logic (`trim_views`, `cached_view`,
`crates/lucisv_server/src/state.rs:349` and `:1061`) was already right by
inspection and by trace, but three of the charter's named attacks had no
regression test, meaning a future refactor could break any of them silently:
- *Recency, not insertion order.* `cached_view`'s `rotate_right` had no test
at all. Added
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`:
fills the cache, re-touches the oldest entry, adds a fifth file, and
requires the just-touched file to survive while the untouched one is what
falls off instead.
- *`update_one` selectivity.* Every existing invalidation test warms one
file's view at a time, so a hypothetical `update_one` that widened to
`views.clear()` would still pass all of them. Added
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`.
- *A second oversized file.* The existing bound test caches exactly one
file over the byte budget; it never tries a second one. Added
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`,
confirming the cache stays at one entry (the newest) rather than
accumulating unbounded huge files.
All three pass against the round's code unmodified — genuine coverage gaps,
not bugs.
**4. Format bump — the single-decl test's premise checked, and generalized.**
`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread`
genuinely constructs a format-3 record (verified by hand: `strip_the_line_
fields` removes exactly the two trailing fields of the one declaration `M`
has, and the record that results is what format 3 actually wrote — not merely
a v3 header over v4 bytes). That fixture has only one declaration, so it could
not have caught a field-shift that landed on a *second* declaration's fields
rather than on a tag literal. Added
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_
rejected_not_misread`, generalizing the stripper to N declarations (both units
and members) and covering a two-unit file and a mixed unit+split-port-member
file. Both decode to `None`, confirming the structural reason this is safe in
general: a field-shift by exactly one declaration's two line-fields always
lands either on a tag literal (`"M"`, `"I"`, …) or on the next declaration's
`name`/`kind` string fields, and a Verilog identifier can never parse as
`u32`, so `Reader::num` fails and `decode` returns `None` rather than building
a `Decl` out of someone else's fields. No misread constructed; the
"guilty until proven innocent" bar is met.
**5. Equivalence — confirmed, not just claimed.** `cargo test --workspace`
green with 0 failures both before and after this pass's additions (dev's
counts: `lucisv_server` 1210 passed/24 ignored, `vlog_semantic` `workspace` 66
passed — both unmodified by this pass except for the new tests below). Read
the `hover.rs` and `locate.rs` diffs directly: the live-buffer branch is
untouched, `location()`'s open-buffer arm is a straight substitution
(`doc.positions()` for the old `Positions::new(&text, &index)` built from a
clone of the same text), and the disk branch is the only place behavior can
differ — which is exactly the one documented corner (an unreadable closed
file now shows its indexed line). No other behavior change found.
**6. Numbers reproduced**, `--release`, this machine, this session:
- `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`: first
touch 5.75 ms (instantiation) / 5.65 ms (port), repeat 1.35 µs / 1.89 µs —
same order as the README's 6.23 ms / 0.95 µs and 5.92 ms / 0.99 µs; run-
to-run noise, not drift.
- `state::tests::qa_perf_cold_warm_and_half_warm_scans` (860-file corpus):
store size **2 380 790 bytes** — an exact match to the README's "after"
figure, confirming the +68 KB / 2.9 % growth claim against the real
corpus rather than trusting the doc's arithmetic. Scan times (325 / 350 /
186 ms) were in the same band as the README's (343 / 374 / 200 ms);
machine noise, no regression.
- `e2e::a_hover_issued_during_the_initial_scan_waits_for_it`: 748.7 ms cold
/ 274.0 ms warm for the first hover issued the moment `initialized` is
sent, vs. 26.3 µs / 40.2 µs once the scan is done — the same four-orders-
of-magnitude gap the README reports (780 / 287 ms vs. 64 / 61 µs). The
test genuinely exercises the wait (it asserts the answer resolves
correctly across files, and the two timings are taken across the real
wire protocol against the shipped binary) — the Handshake in this
README's "Suspect 2" section is accurate and not overstated.
**7. Full gates**, run after adding the tests above:
- `cargo fmt --all -- --check`: clean (after formatting the new tests —
two blocks needed `cargo fmt`'s wrapping, applied).
- `cargo clippy --all-targets --workspace`: clean, no warnings.
- `cargo test --workspace`: green. `lucisv_server` unit tests **1214
passed** (dev's 1210 + this pass's 4), `vlog_semantic` `workspace` suite
**67 passed** (dev's 66 + this pass's 1). 0 failed anywhere in the
workspace, including doctests.
- `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
**Tests added this pass** (5, all permanent regressions, all green):
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`,
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`,
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`,
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`
(all `crates/lucisv_server/src/`), and
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_rejected_not_misread`
(`crates/vlog_semantic/tests/workspace.rs`).
## Review
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
independently (fmt clean, clippy silent, 2440 workspace tests green).
This round is the owner's design implemented at the right altitude:
`DeclLines` as a field on the carrier the index already had — not a
parallel table — so ports got their lines for free through the member
entries and the extension story is "add a field, bump the format",
exactly the flexibility the owner asked for. The +68 KB store growth
on the 860-file corpus scales to the owner's 20 000-module thought
experiment at the few-tens-of-KB order they predicted. The `FileView`
cache is honest about its one unwatchable staleness case and leans on
`spells_exactly` correctly (a stale view omits, never lies); QA's
staleness repro pins the heading/snippet pair going stale *together*.
The dev's rewrite of the format-discard test from a pinned literal to
all-previous-formats is the kind of fix that outlives the round.
Suspect 2 — the first request of a session waiting 287–780 ms behind
the startup scan — is confirmed genuine by dev and QA independently
and is the dominant remainder of the owner's "slow on first try";
correctly filed as a Handshake, next round's work. Accepted; committed
by the lead.
+9
View File
@@ -75,6 +75,15 @@ slice that can panic.
and no bump would let a changed buffer answer "unchanged". One notification =
one reparse = one stamp = one `publish`. Pinned by
`one_notification_is_one_generation_bump_however_many_ranges`.
**Amended 2026-08-28 by `docs/features/change-debounce/README.md`**: a
`didChange` now records the composed text as dirty and the analysis runs at
the next flush, so the promise reads **one *flush* is one `set_document`,
one generation bump and one publish per dirty buffer** — however many
ranges *and however many notifications* it coalesced. What the promise
protects is unchanged: the counter never moves twice for work done once and
never fails to move for a buffer whose text changed. The test above still
passes as written; its helper flushes after each notification, which is the
quiet-period timer firing.
- **Changes what the client is told at `initialize`.**
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
+37 -2
View File
@@ -216,7 +216,33 @@ impl WorkspaceIndex {
- Since indexed navigation (2026-08-27), the private facts also carry compact
local/external reference records used to rebuild declaration-to-occurrence
postings. That encoding change bumped `FACTS_FORMAT` from 1 to 2; no cache
migration is attempted or needed.
migration is attempted or needed. **2 → 3** (2026-08-28,
`docs/features/port-detail-spans/README.md`): each declaration gained its
`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. **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`
checks **every** format this build is not, rather than the one literal
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.
@@ -350,7 +376,16 @@ name span `19..20`), no members, one instantiation edge (of `sub`, owned by
`m` whose name is at `19..20` and whose declaration runs `12..41`, with the
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 record is what lies between the hash field and the
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), 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.
**Any change to what a record holds or how it is written bumps
File diff suppressed because it is too large. Load diff
+21 -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.
@@ -216,6 +227,15 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
line reads `cached: <path>` where a parsed file's reads `indexing: <path>`,
and whose bar tick is identical — a cached file is a file of the work list,
and the bar flying through them is the point.
**Amended again (index-scope, 2026-08-28):** a third arm,
`IndexEvent::Analyzed`, for a file that went into the index from an **open
buffer's own finished analysis** rather than from a parse or from the store.
Its log line reads `analyzed: <path>`; its bar tick is identical again. It
deliberately adds **no** clause to the end message — one file out of a
workspace is not why a scan finished fast, and "N from cache" keeps meaning
the persistent store and nothing else, which is the sentence
`index-persistence`'s e2e transcripts assert. See
`docs/features/index-scope/README.md`.
- `begin` still carries **no** percentage: the first honest one is the first
file's.
+440
View File
@@ -0,0 +1,440 @@
# interactive-latency
## Goal
Make the request and notification paths a user *feels* — the ones that run
while they type and move the cursor — cost what they have to cost and no
more, and say with measured numbers where the rest of the time goes. Round 1
(`docs/perf/README.md`) established the baseline and named the open question
it could not answer from inside the crate: what a `didChange` →
`publishDiagnostics` round trip actually takes over the wire. This round
answers that, breaks one flush down stage by stage, and takes the
identity-safe wins the breakdown justifies — which turned out to be six token
lookups that were sweeping the whole buffer for something a binary search
answers in twenty nanoseconds. Nothing on the parse path was touched: the
measurements say the remaining cost is lexing and parsing, and that is a
change this round deliberately does not make.
## Assumptions
- **The token stream rises and never overlaps.** Every binary search added
here rests on one property of `Document.tokens`: the lexer emits tokens in
source order, so `end[i] <= start[i+1] <= end[i+1]` and both
`span.start < offset` and `span.end < offset` are monotone predicates over
the vector. That is the whole precondition `partition_point` needs, and it
is pinned by `state::tests::the_token_stream_rises_and_never_overlaps` —
the test that would fail first if the lexer ever changed shape. Nothing
here assumes tokens are non-empty: the `Eof` sentinel is zero-width, and
every argument below survives it.
- **No benchmark dependency**, unchanged from round 1: `std::time::Instant`,
`#[ignore]`d tests, no `criterion`. `CLAUDE.md` requires a written
justification for a new dependency and there is none to write.
- **A measurement asserts nothing about duration.** A test that fails when
the machine is busy is a test that gets deleted.
- **The e2e round trip is a real session.** It spawns the shipped binary and
speaks framed JSON-RPC at it, so the number includes the pipes, the JSON,
the debounce timer and the flush. It cannot be taken from inside the crate,
which is exactly why round 1 could not take it.
- **The generated module is uniform, and real RTL is not.** Both generators
build the same repeated four-line block. The numbers are a scale, not a
prediction for any given file.
## Handshakes
- **`vlog_parser` → this crate (consumed, unchanged).** The binary searches
consume the ordering property of `tokenize`'s output described above.
Nothing was asked of `vlog_parser` and nothing in it changed. If it ever
emits tokens out of order, the pinning test in `state.rs` fails before any
handler answers wrongly.
- **`state.rs` → `selection.rs`, `on_type.rs`, `completion.rs` (new,
internal).** Two free functions, `first_token_reaching` and
`first_token_from`, are published from `state.rs` beside `Document`. They
are the single place the monotonicity argument is written down; every call
site is one comparison on top of one of them. `inline.rs` uses a third
predicate (`span.end <= offset`) written at its own call site, because it
has one user and its own local proof.
- **`e2e.rs`'s `Live::finish` now returns the publish count** it saw on the
way out. Existing callers ignore the value, which compiles unchanged. The
count is what turns "the debounce coalesces a burst" from arithmetic into a
measurement.
- **Two copies of one generator.** `perf::generated_module` and the copy in
`tests/e2e.rs` must stay the same shape, or the in-crate table and the
over-the-wire table in `docs/perf/README.md` stop being readable against
one another. `lucisv_server` is a binary crate, so an integration test
cannot import the original; the copy is commented as such at both ends.
- **Nothing was asked of `vlog_linter`.** The lint pass costs 1.40 ms of a
32 ms flush at 10 000 lines and walks the tree once per rule; that is
recorded in `docs/perf/README.md` as a future round's work, not requested
here.
## Status / TODO
- [x] Phase 1 — a stage-by-stage breakdown of one flush at 1k and 10k lines:
`tokenize`, `tokens.clone()`, `parse_tolerant`, `collect_defines`,
`analyze`, `resolve_external`, `LineIndex::new`, and the
`diagnostics::all` pass a publish runs (which is *not* inside
`Document::new`, and which round 1's table did not account for).
`perf::breaking_down_one_flushed_keystroke`.
- [x] Phase 1 — the end-to-end round trip round 1 listed as its own open
TODO: `didChange` → `publishDiagnostics` against the real binary, for a
single change, for a burst of ten, and for the change-then-request
shape a real editor produces.
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`.
- [x] Phase 2 — six token lookups swapped from a sweep to a binary search,
each with a test that walks **every byte** of a buffer written to have
plenty of touching tokens and asserts the search returns exactly what
the sweep returned.
- [x] Phase 2 — the three sweeps that are inherent left alone, with the
reason written down (below).
- [x] Phase 3 — decided against every change the breakdown did not justify,
with the number for each (below).
- [x] Phase 4 — `docs/perf/README.md` refreshed: both of round 1's open
TODOs resolved or restated, every figure re-measured on this machine.
Not done, deliberately, and each with the number that would justify it — the
list lives in `docs/perf/README.md`'s *What it would take to go faster* so it
sits beside the measurements rather than in a feature's checklist.
## The Phase 2 call sites, one by one
The predicate each site wants is *not* always "the token containing this
offset", so `Document::token_at` is not a drop-in for any of them. Each swap
below is argued from the ordering property, and each argument is pinned by a
test that compares the new expression against the old one at every byte of
`state::mixed_buffer(20)` — a buffer written with `a=b;`-style adjacent
punctuation, comments and strings precisely because the bytes that could tell
a search from a sweep are the ones two tokens share.
**Changed and proven.**
| site | wanted | now | test |
|---|---|---|---|
| `selection.rs` `enclosing` | the first token with `start <= offset <= end` | `first_token_reaching`, then one `covers` check | `selection::tests::the_innermost_step_is_the_token_the_sweep_returned_at_every_offset` |
| `on_type.rs` `statement_edit` | the token with `end == offset` | `first_token_reaching`, then one `==` | `on_type::tests::the_token_ending_at_the_cursor_is_the_one_the_sweep_returned` |
| `on_type.rs` `first_on_line` | the first non-`Eof` token with `start >= content` | `first_token_from`, then `find` over the tail | `on_type::tests::the_first_token_on_a_line_is_the_one_the_sweep_returned` |
| `completion.rs` `is_procedural` | the *index* of the token with `start == offset` | `first_token_from`, then one `==` | `completion::tests::the_scope_gates_answer_what_their_sweeps_answered` |
| `completion.rs` `balanced` | every token whose start is in `[from, at)` | a slice between two `first_token_from`s | the same test |
| `inline.rs` `triggered` | the **last** non-`Eof` token with `end <= offset` | `partition_point`, then `rposition` over the prefix | `inline::tests::the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found` |
Two of these deserve their reasoning spelled out, because they are the two
where a careless swap would have changed an answer:
- **`selection.rs` takes `span.end` inclusively.** At a byte two adjacent
tokens share, `find(covers)` returned the *earlier* of the two, while
`Document::token_at` — which uses `TextRange::contains`, end exclusive —
would return the later one. `first_token_reaching` returns the earlier one,
which is why it is the right primitive here and `token_at` is not.
- **`completion.rs`'s `balanced` was sweeping the whole buffer.** Its filter
had no upper bound to break on, so a cursor anywhere in a 10 000-line file
walked all 94 961 tokens to reach a window a few dozen tokens wide. It is
the largest of the six by some way: 130 µs → 36 ns.
**Left alone, with the reason.**
- **`signature.rs` `enclosing_list` (:138) and `active_entry` (:231).**
Inherent. Both maintain a parenthesis-depth stack, and a depth at the
cursor is a function of *every* bracket before it — there is no prefix a
binary search may skip without recomputing what it skipped. Both already
break at the cursor rather than running to the end of the buffer, so
neither is a whole-buffer sweep; bounding the loop with a binary search
instead of the `break` would save one comparison per token and change
nothing else, which is not worth the edit.
- **`pairs.rs` `analyze` (:230).** Inherent, and not a position query at
all: it matches *every* scope keyword in the stream and returns the whole
pair set. There is no offset to search for.
- **`completion.rs` `in_comment_or_string` (:553).** Left, and its existing
doc comment already says why: comments are lexer trivia hanging off
whichever token happens to follow or precede them, so the token whose
`leading` holds a comment at a given byte is not the token a search for
that byte would find. A correct search would have to reason about
attachment; a wrong one would offer a completion list inside a comment.
This is the one remaining per-keystroke whole-buffer walk, and it is
recorded as such in `docs/perf/README.md` rather than guessed at.
- **`completion.rs` `word_tier` (:355), `candidates.rs` (:218),
`folding.rs` (:58).** Inherent: each needs every token in the file, not a
token at an offset.
## Work log
**2026-08-28 — dev (round 2).**
*Phase 1, measured first.* Added
`perf::breaking_down_one_flushed_keystroke` and
`perf::finding_one_token_against_sweeping_the_stream` to the existing
`perf.rs` module, and `a_keystroke_round_trip_over_the_wire` to `e2e.rs`.
The e2e measurement reuses the `Live` session helper that already existed in
that file for the watched-files test rather than adding a second one; the
only change to shared code is that `Live::finish` now returns the number of
`publishDiagnostics` it saw while shutting down. That count is the point: a
buffer left dirty by a burst is flushed before the next *request* is
answered, so by the time `shutdown` comes back every publish the burst was
going to produce has arrived. A burst of ten keystrokes produces **one**.
The breakdown decided everything that followed. At 10 000 lines a flush is
31 ms, and 24.5 ms of it is `tokenize` plus `parse_tolerant`. `analyze` is
11 %, the diagnostics pass another 4 % on top of the flush, and
`resolve_external` — which the round's brief named as a possible target — is
**49 µs, one part in six hundred**. There is nothing to skip there.
*Phase 2.* Six sweeps became binary searches, on the strength of the
`finding_one_token` measurement: 77 µs → 20 ns for a cursor lookup at 10 000
lines, and 130 µs → 36 ns for `balanced`'s window. The two primitives live in
`state.rs` beside `Document::token_at`, which is where the one-paragraph
monotonicity argument they all rest on is written; `inline.rs`'s third
predicate is written at its own call site because it has one user.
Every swap is pinned by a test that compares it against the code it replaced
at every byte of a shared awkward buffer (`state::mixed_buffer`, whose one
job is to have plenty of tokens that touch). Two of the six are *not* what
`Document::token_at` would have answered, and the table above says which and
why; a seventh candidate, `completion.rs`'s comment gate, was left alone
because no search of the token stream answers the question it asks.
*Phase 3 — nothing, on purpose.* The breakdown does not justify a change:
- Lex and parse are 79 % of a flush. Making them incremental is the only
lever left, and it is a large change under `CLAUDE.md`'s hard invariants 1
and 2. Written up in `docs/perf/README.md` with the number that would pay
for it; not attempted.
- `tokens.clone()` is 2.40 ms, 7.7 % of a flush, and is **load-bearing**:
`parse_tolerant` takes its token vector by value and steals the comments
out of it (`std::mem::take(&mut self.tokens[pos].leading)`,
`self.tokens[pos].trailing.take()`), so `Document.tokens` cannot be the
same vector — folding, the on-type comment test and completion's comment
gate all read that trivia. The clone is also already a win: before the
one-lex change it was a second `tokenize`, which this round measures at
12.5 ms. Removing it needs a cheaply-clonable `Token`, which is a
`vlog_parser` type change reaching the formatter. Written up, not
attempted.
- The lint pass walks the tree once per rule (`vlog_linter::lint`'s
`for rule in enabled`), but it is 1.40 ms against a 32 ms flush. Fusing the
walks is a `vlog_linter` refactor for 4 %. Written up, not attempted.
- `resolve_external` is 49 µs. Skipping it when the index generation has not
moved would save one part in six hundred of a flush and add a cache
invalidation rule to a path that currently has none. Not attempted, and
the number is the reason.
*The finding worth acting on is not a code change.* Over the wire, a lone
keystroke's round trip is 156 ms at 1 000 lines — of which 150 ms is the
change debounce's own quiet period, and 4.8 ms is the work. The same
keystroke followed by a request, which is what a real editor sends, is
**4.8 ms at 1 000 lines and 37 ms at 10 000**. So for the editors that ask
for anything after a change (VS Code asks for semantic tokens, inlay hints
and highlights), the debounce timer never runs and the flush is the whole
cost; for a client that asks for nothing, the felt latency is the timer.
`CHANGE_DEBOUNCE` is a product decision the previous round made deliberately
at 150 ms, so it was not touched — but it is now a measured number rather
than an assumed one, and `docs/perf/README.md` says so.
## QA log
**2026-08-28 — QA.** Verdict: **SHIP WITH FIXES noted, none applied** — one
methodology finding on the e2e measurement (not shipped code a user can hit),
one informational note verified harmless. Everything else attacked and held.
Gates, verbatim:
- `cargo fmt --check` — clean, no output.
- `cargo clippy --all-targets --workspace -- -D warnings` — clean, no
warnings.
- `cargo test --workspace` — every crate green: lucisv_server's unit binary
1192 passed / 21 ignored, its `e2e` integration binary 55 passed / 1
ignored (the perf test, run separately below), every other crate green
too. No `FAILED`, no `error[`.
- `cargo test -p vlog_formatter` — 31 + 1 + 4 + 6 + 2 + 22 + 114 + 0 passed
across its binaries, 0 failed.
- `cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1`
— 12 passed. Numbers reproduced within the noise the README itself budgets
(see below).
- `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
— 1 passed: `1000 lines: one change alone 161.9ms, a burst of ten 160.4ms
for 1 publish(es), one change a request follows 4.7ms` /
`10000 lines: one change alone 205.7ms, a burst of ten 199.0ms for 1
publish(es), one change a request follows 38.5ms` — matches
`docs/perf/README.md`'s 156/205/157/205/1/4.76/37.4 within reason.
**Attack angle 1 (identity claims).** All six call sites re-derived from the
source and checked against their sweep predicates by hand (`selection.rs`
`enclosing`, `on_type.rs` `statement_edit` and `first_on_line`,
`completion.rs` `is_procedural` and `balanced`, `inline.rs` `triggered`).
Every one of the existing per-site tests already walks **every byte** of
`mixed_buffer(20)` (not just a handful of offsets), so the exhaustive-diff
form the brief asked for is already what shipped, not something to widen.
Checked by hand and confirmed safe at the edges the brief named: offset 0,
the last byte, the `Eof` sentinel, an empty file, a file that fails to lex
(empty `tokens`), and a large-file fast-path document — `on_type.rs`'s own
`OnTypeFormatting::METHOD` arm in `server.rs:832` answers the empty edit list
before `level_at`/`first_on_line` ever run on a large doc; `completion.rs`'s
`completions` guards `doc.tokens.is_empty()` at `completion.rs:154` before
`is_procedural`/`balanced` are reachable; `inline.rs`'s `inline_completions`
guards the same at `inline.rs:237`; `selection.rs`'s `enclosing` and the two
`first_token_*` primitives themselves degrade safely on an empty slice
(`partition_point` on `&[]` is `0`, `.get(0)` on an empty `Vec` is `None`).
`selection.rs`'s inclusive-`covers`/exclusive-`token_at` distinction is real
and correctly *not* used — traced through `first_token_reaching` +
`covers` by hand at a shared boundary byte and it does return the earlier of
two touching tokens, matching the sweep it replaced.
**Attack angle 2 (the precondition).** `state::tests::the_token_stream_rises_and_never_overlaps`
exercises exactly one hand-written buffer
(`mixed_buffer(20)`), which is narrow on its own — no macros, no directives,
no unterminated constructs. Delegated to a sub-agent to read
`vlog_parser`'s lexer directly rather than trust the docstring's claim.
Finding: `vlog_parser`'s own `tests/spans.rs::assert_covers_source` already
asserts the same invariant (non-overlap, source order, full byte coverage,
comments included) over 40+ deliberately adversarial fixtures — macros,
`` `ifdef``/`` `include`` interleaving, attributes, CRLF, BOM, multi-byte
UTF-8 in strings and comments — and `tests/error_recovery.rs` fuzzes every
byte-prefix and every single-byte deletion of a corpus without panicking.
Every lexer error path (`skip_string`, `skip_block_comment`, the attribute
scanner) returns `Err` rather than a partial, possibly-violating `Vec<Token>`,
and `TextRange::new` clamps `end` to `max(start)` structurally. No plausible
gap found: the one narrow test in `state.rs` is sufficient because it rests
on an invariant `vlog_parser` proves far more thoroughly one layer down, and
the docs correctly point there rather than re-arguing it.
**Attack angle 3 (the e2e measurement's methodology) — one finding.**
- **IL-1 (medium) — the burst's "1 publish(es)" figure is not the robust,
order-independent count the code and the docs describe.**
`crates/lucisv_server/tests/e2e.rs:4696-4727`. `published` is computed as
`1 + live.finish()` (line 4727): the `1` is an unstated assumption that the
lone `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
right after the burst (line 4704) consumed *exactly* the burst's own
publish and nothing else, and `live.finish()`'s count only starts
accumulating after the "one change a request follows" loop ten lines later
(4714-4725) has already run — ten more iterations, each with its own
generic `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
(line 4722) that accepts *any* publish, not specifically the one its own
request just triggered. A stray or duplicate publish arriving from the
burst in that window would be silently absorbed by one of those ten waits
and never increment `published` or surface anywhere in the printed line.
The doc comment above the burst (line 4696-4699: "the count below is that
claim measured rather than reasoned about: any publish still to come
arrives before `shutdown` does") is true of `live.finish()`'s own drain —
nothing gets past *that* point unnoticed — but it is not true of the
window between the burst and the drain, which is exactly where a second
publish would have to be counted to falsify "exactly one". As written, the
test would print "1" whether the burst produced one publish or secretly
produced two, which is indistinguishable from the claim it's supposed to
be checking. In practice the debounce is understood to always coalesce to
one flush, so this is a soundness gap in the *measurement*, not evidence
of a real double-publish — but it means the "counted rather than reasoned
about" claim is itself partly reasoned about. Not fixed: closing it cleanly
means either running the burst as its own `Live` session finished
immediately after (so nothing else can absorb a stray), or having
`wait_for` tally every `publishDiagnostics` it ever passes over for the
life of the session — both are design choices for the dev, not a
QA drive-by edit.
- Everything else in this angle held. `Live::finish`'s drain (`e2e.rs:2231`)
really does read to `shutdown`'s response before returning, so nothing
published after the last explicit `wait_for` in a test is lost *at that
point* — it is specifically the mid-test absorption above that is the gap.
The 150 ms figure in the lone-keystroke row is the timer and not a stall:
reproduced at 161.9 ms / 205.7 ms against a documented 150 ms
`CHANGE_DEBOUNCE` plus a single flush (2.6 ms / 31.2 ms measured
separately), which accounts for the total without residue.
**Attack angle 4 (duplication) — one informational note, verified harmless.**
`perf::generated_module` (`crates/lucisv_server/src/perf.rs:42-57`) and its
copy in `crates/lucisv_server/tests/e2e.rs:4634-4649` are not byte-identical:
the `e2e.rs` copy appends ` // typing\n` before `endmodule` that the
original does not have, so the test has a stable, comment-only line to land
keystrokes on. The doc comment on the copy ("The two must stay the same
shape, or the two tables ... stop being readable against one another")
slightly overstates it — they differ by one line. Verified harmless: a
comment is lexer trivia and is never its own token, so `tokens.len()` is
identical between the two generators at the same `lines`, and the added ~12
bytes is noise against 29 KB / 309 KB files. The two perf tables do stay
readable against one another; no fix needed.
**Attack angle 5 (perf honesty).** Every figure in `docs/perf/README.md`'s
round-2 tables reproduced within the noise the document itself budgets for,
on a fresh `--release` run (see gates above for the two exact commands and
their output). Spot check on "the breakdown sums to `Document::new`'s
31.1 ms" — a claim the brief asked about but which, checked directly, is
**not actually written anywhere in either README**; nowhere does the text
assert the eight-stage breakdown sums to the `Document::new` figure. As a
sanity check anyway: summing this run's own breakdown stages inside
`Document::new` (tokenize 12.512 + parse_tolerant-with-clone 14.149 +
collect_defines 0.115 + analyze 3.174 + resolve_external 0.012 +
`LineIndex::new` 0.105 ≈ 30.07 ms) against the dedicated `Document::new`
figure from the same run (31.22 ms) leaves about 1.15 ms — 3.7% —
unaccounted for, which is consistent with the README's own caveat that the
breakdown "runs eight measurements back to back on one heap" and should be
read as *shares*, not as a sum that has to close exactly. No finding, since
no stronger claim than that is actually made.
**Attack angle 6 (regression sweep).** `cargo test --workspace` exercises
every one of the four handlers' existing suites unchanged and green
(selection.rs, on_type.rs, completion.rs, inline.rs — see gates above).
Adversarial shapes the brief named are already covered by name in the
existing suites and were spot-read to confirm they exercise the *changed*
code paths and not just the surrounding handler: `on_type.rs`
`a_semicolon_the_lexer_never_saw_ends_no_statement`,
`a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`,
`a_crlf_line_ending_is_never_touched_by_the_edit`; `completion.rs`
`a_buffer_that_does_not_lex_is_declined`; `inline.rs`
`a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at`,
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost`,
`crlf_line_endings_still_trigger`; `selection.rs`
`a_file_that_does_not_lex_still_answers_the_file_range`,
`an_empty_file_still_answers_one_degenerate_chain`.
**PDS-1..4 and CD-1, spot-checked in code rather than trusted from the
README.** `hover.rs:361` (`only_a_closer_on`) and `:373` (`is_closer_word`)
exist and `another_port_on`/`is_port_grammar_word` are gone — PDS-1 real.
`hover.rs:292-295` strips a trailing `\r` in the one line reader all three
`attached_lines` collections pass through — PDS-4 real. `server.rs:1247-1262`
(`notification`): the `dirty.retain` for `DidCloseTextDocument::METHOD` sits
*above* the `if method != DidChangeTextDocument::METHOD { self.flush_dirty() }`
call, guarded on the method name via a borrowed, cloned `closing_uri`
(`server.rs:2214`, reads `params` without consuming the notification) — CD-1
genuinely closed, not dead code any more. PDS-2/PDS-3 not independently
re-derived (no code-shape claim to check beyond what PDS-1/PDS-4 already
verify the same file's discipline on); taken on the strength of the named
tests, which are present and green.
## Review
**2026-08-28 — lead.** Accepted, with one methodology fix applied by me
(below). Gates re-run independently: fmt clean, clippy silent, workspace
tests green, formatter snapshot + idempotency suite green, the twelve `perf::`
measurements and the wire measurement both reproduce.
This round did the thing that makes a performance round worth anything: it
measured first and then declined to optimise three of the four things it had
been pointed at, with a number for each refusal. `resolve_external` at 49 µs
of a 31 ms flush disproved the brief's own hypothesis, and saying so is a
better outcome than a speculative cache on a path that has no invalidation
rule today. Lex and parse at 79 % is the real answer, and leaving incremental
parsing to a planned round rather than starting it opportunistically is
right — that work lands directly on hard invariants 1 and 2 and is not
something to attempt as the tail of a perf sweep.
The Phase 2 swaps are the part I looked at hardest, because six "obviously
identical" rewrites is exactly where a silent behaviour change hides. The
dev found the one that was *not* identical: `selection.rs`'s `covers` treats
`span.end` inclusively, so at a byte two tokens share, the sweep returned the
earlier token and `Document::token_at` would have returned the later one.
Building `first_token_reaching` instead of reaching for the existing helper
is the correct instinct, and differential-testing each new expression against
the predicate it replaced at every byte of a purpose-built buffer is the
right proof. Three call sites were left alone with reasons — signature help's
paren depth is inherently a prefix scan, `pairs.rs` is not a position query,
and completion's comment gate cannot be answered by any search of the token
stream because comments are trivia. Recording the last of those as the
remaining per-keystroke whole-buffer walk is more useful than a forced fix.
**Fix applied at review.** QA's IL-1 was right and I closed it directly
rather than spending another round: the burst-of-ten publish count was
`1 + finish()`, but the ten-iteration request loop sat between the burst and
the drain, and each of its `wait_for`s accepts *any* publish — so a second
publish the burst had produced would have been absorbed there and the figure
would still have read "1". The burst now runs last, immediately before the
drain, with the keystroke versions renumbered to stay monotonic. Re-measured
after the change: still exactly one publish at both sizes, and the row is now
counted rather than assumed. IL-2's overstated doc comment is corrected in
place — the two `generated_module` copies differ by one trivia line, which is
not a token and does not move a number.
+52 -14
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 |
@@ -21,15 +41,15 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` |
| `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` |
| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` |
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didSave` once per notification, and for a `didChange` once per **flush** (a typing burst publishes once, not once per keystroke — `docs/features/change-debounce/README.md`) — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, and the composed text is held **dirty** — one `set_document` + one `publish` per *flush*, which is the next request, the next other notification, or a 150 ms quiet period. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` and `docs/features/change-debounce/README.md` |
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` |
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built |
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md` |
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md`. The `file:line` half of a cross-file heading costs **no file access**: the line is recorded when the file is indexed (`Def::lines`), so only the snippet still reads, once per file per generation of it through `Workspace::file_view`: `docs/features/hover-line-index/README.md` |
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` |
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
@@ -233,17 +253,19 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`.
| layer | rebuilt when | cost |
|---|---|---|
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
| a document's `Semantics` + tokens + diagnostics | every `didOpen`, and every **flush** of the buffers a `didChange` left dirty — once per flush, however many ranges *and* however many notifications it coalesced (`docs/features/change-debounce/README.md`) | one file, full recompute — 2.6 ms at 1 000 lines, 31 ms at 10 000 (`docs/perf/README.md`) |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) |
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
| the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
deferred there. Incremental *sync* did not change that: the wire now carries
ranges, but a `didChange` still throws the whole `Document` away and builds a
new one — one reparse per notification, which is also the one generation bump
the pull-diagnostics `resultId` depends on.
**Per-file recompute** is the strategy TODO.md §6 states ("per-file recompute
is fine at Verilog file sizes"); salsa is explicitly deferred there.
Incremental *sync* did not change that: the wire carries ranges, but a flush
still throws the whole `Document` away and builds a new one. What changed on
2026-08-28 is *how often*: a `didChange` no longer triggers that recompute
itself, so a typing burst costs one reparse and one generation bump — still
exactly one of each per flush, which is what the pull-diagnostics `resultId`
depends on (`docs/features/change-debounce/README.md`).
**Which files exist: the folder scope, since 2026-08-27** (index-scope). The
index no longer walks the whole workspace by default. The ladder, highest
@@ -268,6 +290,19 @@ folder brings it into scope. `"lucisv.index.scope": "workspace"` restores the
pre-2026-08-27 behaviour in full. Rules, the clamp, the close decision and the
one `.gitignore` gap: `docs/features/index-scope/README.md`.
**And scope-relative in *time*, since 2026-08-28** (scan-interleave). A
**startup** scan of more than 64 files no longer blocks the message loop: it
indexes one file at a time and answers whatever the client has already sent
between two of them, so the first request of a session comes back in
milliseconds instead of waiting out the whole scan (780 ms → 15.5 ms cold over
200 files). The price is that such an answer reflects the index **as of that
moment** — a declaration in a file the scan has not reached yet does not exist
yet, in exactly the sense a declaration outside the scope does not exist. Two
narrowings keep that from reaching anywhere it is not worth it: a scan of 64
files or fewer runs one shot as it always did, and a request queued *behind* a
message that asked for a rescan waits for that rescan, so the loop's order
contract is unchanged. `docs/features/scan-interleave/README.md`.
**Open buffers override disk** in every index rebuild: the scope is walked,
each file read, and then every open document with a path replaces the disk
copy (adding itself if it exists only in the editor). So the index never
@@ -476,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:
+17 -12
View File
@@ -30,12 +30,13 @@ same invocation, regardless of thread count.
rather than streaming. For the sizes lucisv targets (a large RTL tree is tens
of MiB of source) this is acceptable; it is the reason `--stdout` over a
huge tree is no longer incremental.
- **8 MiB of worker stack is enough.** Taken from
`docs/features/recursion-limit/README.md`, which measured the worst-case
full-pipeline peak at ~3.9 MiB in a debug build and ~0.5 MiB in release.
The pool is built with exactly that number; rayon's own default is 2 MiB,
which would silently reintroduce the stack-overflow crash that feature
fixed.
- **Worker stacks are `vlog_parser::PARSE_STACK_SIZE`, not a number of this
feature's own.** Superseded 2026-08-28: this used to assume "8 MiB is
enough", from recursion-limit's then-measured ~3.9 MiB debug peak. That
peak is now measured at ~5.9 MiB (rustc 1.97, nested `case`), so the size
is no longer this feature's to pick — `build_pool` spells the parser's
constant, and recursion-limit owns the number. rayon's own default is
2 MiB, which would silently reintroduce the stack-overflow crash.
- **The `.gitignore` support is a documented subset, not git.** It is the
`--exclude` matcher plus anchoring, directory-only and negation. See
"gitignore subset" below for exactly what is and is not honoured. It is
@@ -98,11 +99,13 @@ A path named directly on the command line is never ignored, exactly as with
## Handshakes
- **Consumes `docs/features/recursion-limit/README.md`'s request:** that
README asks whoever lands parallelism to build the rayon pool with
`stack_size(8 * 1024 * 1024)` or larger, because a 2 MiB worker cannot
reach `MAX_NESTING_DEPTH` in a debug build (~3.9 MiB measured). Done in
`main.rs::build_pool`, with a test (`deep_file_formats_under_the_pool`)
that fails if the stack size is ever removed.
README asks whoever lands parallelism to build the rayon pool with a stack
big enough to reach `MAX_NESTING_DEPTH`, because a 2 MiB worker cannot.
Done in `main.rs::build_pool`. Since 2026-08-28 the size is the parser's
own `vlog_parser::PARSE_STACK_SIZE` rather than a literal here, so a
re-measurement of the worst case moves every parse site at once; the pin
test (`a_deeply_nested_file_formats_on_a_worker_thread`) still fails if
the pool's stack size is dropped.
- **Discharges `docs/features/cli-polish/README.md`'s handshake:** that
feature's `catch_panic` swapped the process-global panic hook with
`take_hook`/`set_hook` around every call, and flagged it as sound only
@@ -126,7 +129,9 @@ A path named directly on the command line is never ignored, exactly as with
- [x] `rayon` as the workspace's first third-party dependency, pinned
exactly, justified below.
- [x] Global pool built once at startup with an 8 MiB worker stack.
- [x] Global pool built once at startup with an 8 MiB worker stack
(re-pointed at `vlog_parser::PARSE_STACK_SIZE` on 2026-08-28, when the
worst case was re-measured past what 8 MiB comfortably covers).
- [x] One panic hook installed at startup; `catch_panic` uses a thread-local
flag instead of swapping hooks.
- [x] Per-file loop parallelised; outcomes reported in input order.
+448
View File
@@ -0,0 +1,448 @@
# port-detail-spans
## Goal
A non-ANSI port is declared in two places: the header names it (`data_in,`)
and a body declaration finishes it (`input signed [31:0] data_in;`). Every
fact a reader wants — direction, signedness, width — is in the second place,
and until this round hover and go-to-definition both pointed only at the
first, so hovering a port of an older-style module showed a bare name and a
comma. `vlog_semantic` now records, on the header symbol, the span of the body
declaration that completes it (`Symbol::detail_span`); the server shows both
in one hover card and offers both as definition locations, detail first. The
same field travels through the workspace index and its on-disk facts, so a
*cross-file* hover into a closed file gets the same two sections. Attached to
that, because a card that shows a declaration should show what the author
wrote about it: each section carries the comment that documents it.
## Assumptions
- **One name, one symbol, per scope.** `bind::declare` already turns a second
declaration of a name into a *reference* to the first, which is exactly how
a non-ANSI body declaration attaches to its header port. `detail_span` rides
on that existing mechanism; nothing new decides what "the same port" means.
- **First writer wins.** If a header somehow names a port twice, the first
body declaration to arrive records its span and later ones are ignored. The
result is deterministic, which is what matters here; a duplicated port is
the linter's complaint to make, not hover's.
- **`detail_span` is `None` for everything else.** An ANSI port, a wire, a
module — anything complete where it is named — has no detail site, and both
consumers render exactly the card they always did.
- **A real span is never empty**, so `(0, 0)` is free to mean `None` in the
facts codec. `bind_port_decl` only ever records a declaration's own span.
- **Comment attachment is textual, and errs towards attaching nothing.** The
disk path of a cross-file hover has no parse to ask, so the attachment rules
work on lines. Only `//` lines and single-line `/* … */` count as
comment-only; the interior of a multi-line block comment is
indistinguishable from code without lexing, and a hover card that guessed
would be the wrong-line lie the snippet guards exist to prevent.
- **A comment below a declaration belongs to the *next* declaration unless
nothing else could claim it.** `only_a_closer_on` answers that with a
whitelist, not a blacklist: the block attaches only when every word on the
line after it is a block terminator (`end`, `endmodule`, `endinterface`,
`endtask`, `endfunction`) — which includes a line with no words at all
(`);`, a blank line, punctuation) — or when there is no line after it at
all. Everything else, a bare `input` on the first line of a *wrapped*
declaration included, reads as another declaration. The bias is the whole
point: a false "another declaration is here" only ever declines to attach a
comment, the direction that cannot lie, while a false "nothing here" shows
one declaration's comment on another's card. (QA, PDS-1: the previous
keyword-blacklist form got that backwards and did lie.)
- **The three comment sources are independent**, as the owner's rule states
them: a declaration takes the comment on its own line *and* the block above
it *and* the block below it, each guarded on its own. Order is source
order. (QA, PDS-2: the first implementation ran them as a priority chain
and dropped a below-comment nothing else claimed.)
- **Comment attachment renders, it never rewrites.** A CRLF file's line ends
before its `\n` but after its `\r`, so `attached_lines` strips that `\r` as
it composes each line — display text only; no buffer is touched (QA,
PDS-4).
## Handshakes
- **`vlog_semantic::Symbol` gains a field** — `detail_span:
Option<TextRange>`. Additive, like `refactor-rename`'s `Target::Declaration`
before it (§2.6 of `topo.md`): every existing reader of `Symbol` compiles
and behaves identically, and the two struct literals that build a `Symbol`
(`bind.rs`) set it. `bind_port_decl` is where it is written.
- **`vlog_semantic::Def` gains the same field**, carried by the index's
internal `Decl`. `Def` is what `lucisv_server` navigates by, so this is the
wire that makes a *cross-file* hover show the body declaration. `Def`
derives `PartialEq`; two `Def`s that differ only in `detail_span` cannot
arise, because both come from the same `Decl`.
- **`facts.rs`'s on-disk format changes** — every declaration record now
carries two more numbers, written unconditionally (`0 0` for the `None`
that every ordinary declaration has) so the stream stays flat and the
reader stays a straight sequence of `num()`s. **`FACTS_FORMAT` is bumped
(2 → 3)**, so a store written by an earlier build is discarded whole:
`index_cache.rs`'s header line carries the number, and a header that is not
this build's means the file is not read at all. Without the bump an old
record would be *reinterpreted* — every field after a declaration's name
span shifted by two — rather than dropped, and only the reader's `done()`
check would stand between a shifted parse and a wrong answer. Dropping the
store costs one rescan, once, which is what the persistent index is for
(`docs/features/index-persistence/README.md`); it is the
`vlog_semantic/src/workspace.rs` choke-point rule in `topo.md` §3.3.
- **`nav.rs` and `hover.rs` agree, by construction.** Hover shows two
sections — header, then detail — and `nav::definition` returns two
locations in the same order, detail first, so "jump" lands where the card's
second block is and the card's first block is the second location. Both
read `symbol.detail_span`; there is no second rule for what a port's
declaration is. An empty detail span is filtered out in `nav.rs` rather
than trusted.
- **Consumes `hover-declarations`' guards unchanged.** `spells_exactly` still
gates every snippet read out of a file the index may be stale against;
`fenced_sections` is applied *after* that guard on the disk path, and after
`live_symbol` on the live path.
## Status / TODO
- [x] `Symbol::detail_span`, written by `bind_port_decl`, first writer wins —
for a module's non-ANSI port and for an old-style task/function
argument, which merge through the same `bind::declare`.
- [x] `Def::detail_span` + the index's `Decl` carrying it.
- [x] `facts.rs` codec: unconditional pair, `(0,0)` = `None`, `FACTS_FORMAT`
bumped so a stale store is not read as a fresh one.
- [x] `hover::fenced_sections` — one section, or header + detail.
- [x] `nav::definition` returns the detail location first.
- [x] Comment attachment (`attached_lines`): same-line, above and below, each
guarded on its own, all three at once where all three are written.
- [x] Tests: `vlog_semantic` records the span for a split port and not for an
ANSI one; hover shows two sections from either end of the port;
comments attach above, below, and are not stolen from the next port;
a cross-file split port shows both sections from the index.
- [x] **2026-08-28**: the below-comment guard is a closer whitelist, so a
*wrapped* next declaration keeps its own leading comment (QA, PDS-1).
- [x] **2026-08-28**: above / beside / below are independent (QA, PDS-2).
- [x] **2026-08-28**: an old-style task or function argument gets a
`detail_span` too (QA, PDS-3).
- [x] **2026-08-28**: a CRLF file's snippet carries no `\r` into the fence
(QA, PDS-4).
- [ ] Not done: `detail_span` for anything other than a port or a
task/function argument. An `extern`
method prototype and its out-of-body definition are the same
two-places-one-symbol shape and would fit the field exactly, but no
hover complaint has been filed about them and speculative generality is
what `CLAUDE.md` says not to build.
- [ ] Not done: a *doc-comment* model. The attachment above is positional and
deliberately dumb — no `///` convention, no markdown rendering of the
comment body, no stripping of `//`. That is a feature of its own if it
is ever wanted.
## Work log
**2026-08-28 — dev.** Implemented as part of the LSP performance round
(plan: "Improve LSP performance + hover accuracy", part B), continued by a
second dev after the first stopped mid-round; the code below is the first
dev's except where noted.
- `bind_port_decl` looks the declarator's name up in the scope it is binding
into *before* `bind_declarators` runs, because `declare` will turn the name
into a reference and there would be no symbol id to write on afterwards.
The lookup is the scope's own `names` map — the same map `declare` consults
— so "the same port" is decided in exactly one place.
- The codec writes the pair unconditionally rather than with a presence flag.
A flag would have kept old records readable at the cost of a branch in the
hot reader and a second thing to get wrong; dropping a stale record costs
one reparse of that file, once.
- Comment attachment was not in the plan. It is here because the first card
the two-section change produced looked wrong without it: a port's comment
sits on the line above or beside it, and showing the declaration without it
loses the only prose the author wrote. The rules are the narrowest ones
that never steal another declaration's comment, and each has a test.
- **Second dev, 2026-08-28**: **bumped `FACTS_FORMAT` 2 → 3**, which the
first dev's change owed and did not take. Its comment argued that a
pre-field record is "one field short, fails `done()`, and is dropped" —
true for the last declaration in a record, but a record with a declaration
followed by anything else is not short, it is *shifted*, and relying on a
trailing-length check to catch a field-order change is exactly what the
format number exists to make unnecessary. The workspace `VERSION` is also
in the store's header, but it has not moved this round, so without the bump
a store written by the released 0.12.1 would have been read by the new
codec. Otherwise no behavioral change: this README is the documentation the
round owed, and `cargo fmt` was run over `hover.rs`.
**2026-08-28 — dev (QA fixes, third dev).** Every finding in the QA log below
is addressed; each is marked fixed or left, with the reason.
- **PDS-1 — fixed.** `another_port_on`/`is_port_grammar_word` are gone,
replaced by `only_a_closer_on`/`is_closer_word` (`hover.rs`). The old
predicate asked "does this line carry an identifier the port grammar cannot
account for?", which is a blacklist: a line that is *only* keywords — the
first line of a wrapped `input\n [7:0] result;` — answered "no other
port here" and handed `result`'s comment to `data_in`. The new one asks the
question the other way round: every word on the line must be a block
terminator, so a line with any word the whitelist does not name (a bare
`input` included) reads as another declaration and the comment stays put.
A line with no words at all — `);`, blank, punctuation — passes, which is
what a last port's trailing comment is really followed by, and so does the
end of the file, where there is no line left to claim anything. The doc
comment now states that bias and why only that direction is safe.
- `name` fell out of the predicate, and with it out of `attached_lines` and
`fenced_sections` — the guard no longer needs to know which port it is
guarding, only whether anything follows the comment. Three call sites
simplified; no behaviour rides on the removal.
- Pinned: `a_wrapped_next_declaration_keeps_its_own_leading_comment` (the
QA repro verbatim, plus the assertion that the comment does reach
`result`'s own card) and `a_wrapped_declaration_keeps_the_comment_below_it`
(the same wrapped shape as the *last* declaration still takes it). The
existing `a_comments_below_a_declaration_attach_only_when_no_port_follows_them`
— comment block above `endmodule` — still passes unchanged.
- **PDS-2 — fixed.** `attached_lines` no longer runs a priority chain: the
above walk, the declaration's own lines (which carry the same-line comment
inherently) and the below walk are three independent collections joined in
source order. `has_comment_after` was the chain's only reader and is
deleted. Each guard is exactly as strict as before — the above walk still
stops at the first line that is not comment-only, and the below guard got
*stricter* with PDS-1 — so nothing new can be stolen; what changes is only
that a below-comment nothing else claims is no longer silently dropped
because something was also written above.
- Pinned: `a_declaration_shows_the_comments_above_beside_and_below_it_at_once`
(all three on one body declaration) and
`a_header_port_shows_the_comments_above_and_below_it_at_once`, which is
QA's repro 1 and repro 2 in one header — with the negative half (the same
block *is* left alone when another port follows it) in the same test.
- **PDS-3 — fixed, not documented as a gap.** Checked the binder first, as
the brief asked: `bind_tf_args` declares `task t(a);`'s `a` as a `TfArg` in
the task's own scope, and `input [7:0] a;` at statement position reaches
`bind_port_decl` with that same scope, so `declare` turns it into a
reference to the header symbol — the identical header→body merge a module
port gets, one symbol and not two (verified by probe before changing
anything). So the recording is extended rather than parked: the
`kind == SymbolKind::Port` gate is gone and the inner test is
`symbol.kind == kind`, which is the same condition for a port and now also
holds for an argument. Pinned in `vlog_semantic`
(`an_old_style_task_argument_records_its_body_declaration_too`, including
that an ANSI-style argument still has none) and in hover
(`an_old_style_task_argument_hovers_as_two_sections_too`).
- **PDS-4 — fixed.** `attached_lines`'s line reader strips a trailing `\r`
from every line it composes, so a CRLF file's fenced block is `\n`-joined
like any other. It is done there, at the one place all three collections
(above, declaration, below) pass through, rather than in `cut_to_size`,
which would have had to re-split the joined string. Display text only —
nothing writes to the buffer. QA's pinned test
`a_crlf_multiline_snippet_keeps_interior_carriage_returns` was the
regression test for the old behaviour; it is now
`a_crlf_multiline_snippet_carries_no_carriage_returns`, asserting no `\r`
survives *and* that the lines read as written. (Editing a QA-authored test
rather than deleting it: the finding it pins is the one being closed, and
the same file's `local_text` path goes through the same helper, so it
covers both branches QA named.)
## QA log
**2026-08-28 — QA.** Verified against the owner's own spec ("two sections
… same line, or above it (if no other port on the line above), or below it
(if no other port on the line below)"), and attacked with the shapes named in
the QA brief. Gates green (see change-debounce's QA log for the shared run).
All reproductions used temporary `#[test]`s in `hover.rs`, run once, and
removed after confirming — none are left in the tree, except the one noted
below as a kept, permanent regression test.
- **Finding PDS-1 (high — a wrong comment shown, the one invariant this
feature explicitly promises never to violate).** `another_port_on`
(`hover.rs:355`) — the guard that decides whether a below-comment block
belongs to *this* declaration or the next one — inspects only the single
line immediately following the comment block. When the next port's own
declaration **wraps**, with its direction keyword alone on the first line
and its name on a later line, every word on that first line is in
`is_port_grammar_word`'s list (`hover.rs:368`, which includes bare
`input`/`output`/etc.), so `another_port_on` returns `false` — "no other
port here" — and the comment attaches to the **wrong** declaration.
- Repro:
```systemverilog
module alu (data_in, result);
input [7:0] data_in;
// about result
input
[7:0] result;
endmodule
```
Hovering `data_in` shows a detail section reading
`input [7:0] data_in;\n// about result` — `result`'s own leading comment,
attached to `data_in`'s card. Confirmed live (temporary test asserting
the comment is *not* present failed with exactly this text).
- This is precisely the failure mode `docs/features/port-detail-spans/
README.md`'s own Assumptions section rules out: "a false 'yes' only ever
declines to attach a comment — the direction that cannot lie." Here a
false *no* (failing to recognize `result`'s declaration as a port) makes
it lie. Left unfixed — not small/unambiguous; the honest fix wants
`another_port_on` (or its caller) to look past a line that is *entirely*
grammar words with no other identifier, to the line(s) after it, which
is a real design change to a predicate three call sites and several
tests depend on.
- **Finding PDS-2 (medium — divergence from the stated spec, not corruption;
the one the QA brief asked to check explicitly).** The owner's rule reads
as three independently-checked sources (same line, above, below). The
implementation instead runs a strict priority chain in `attached_lines`
(`hover.rs:297`): below-comment collection is skipped **entirely** whenever
there is *any* above-comment, or *any* same-line trailing comment
(`hover.rs:313`, `if above.is_empty() && !decl.last()...has_comment_after`)
— even when the below comment is otherwise unclaimed by anything else
(no other port follows it).
- Repro 1 (above blocks below):
```systemverilog
module alu (
// above
data_in
// below
);
input [7:0] data_in;
endmodule
```
Header section shows `// above` + `data_in` only; `// below` is silently
dropped, though nothing else claims it (the next line is `);`).
- Repro 2 (same-line trailing comment blocks below):
```systemverilog
module alu (
data_in // right here
// below
);
input [7:0] data_in;
endmodule
```
Header section shows `data_in // right here` only; `// below` dropped.
- Not unsafe (never shows the wrong comment — just fewer than the literal
spec asks for), so lower severity than PDS-1, but a real, reproducible
divergence. Left unfixed — a design call (should a declaration ever show
*two* attached comments at once?) belongs to the dev/lead, not QA.
- **Finding PDS-3 (low — silent feature-completeness gap, not a bug).**
`bind_port_decl`'s `detail_span`-recording branch is gated on `kind ==
SymbolKind::Port` (`bind.rs:512`), which excludes `SymbolKind::TfArg` —
**old-style (non-ANSI) task/function port declarations**
(`task t(a);\n input a;\n ...\nendtask`) never get a `detail_span`, even
though they are exactly the same two-places-one-symbol shape a module's
non-ANSI port is, and `bind_port_decl` is already reached at statement
position for them (`bind.rs:1030`, `StmtKind::PortDecl`). The feature's own
"Not done" list names only extern method prototypes as the deliberately
parked case; task/function old-style ports are a second, unmentioned one.
Falls back to the single-section card exactly as before this round — no
regression, just an undocumented gap, worth a line in Status/TODO if the
dev wants it.
- **Finding PDS-4 (low/cosmetic — pre-existing, amplified by this round, not
introduced by it).** On a CRLF file, a multi-line fenced snippet embeds a
raw `\r` byte in the *middle* of the code fence for every joined line
except the last (whose trailing `\r` happens to be stripped because
`cut_to_size`'s `trim_end()` only trims the very end of the whole joined
string, not each line). This is pre-existing behavior of
`Positions::whole_lines` / `cut_to_size` — `local_text` already had the
same characteristic for any multi-line `decl_span` before this round — but
comment attachment now makes multi-line snippets routine (any port with a
nearby comment, not just a rare multi-line declaration), so the gap is hit
far more often in practice. Repro: a CRLF split-port module with an
above-comment; the header section's rendered text contains a literal `\r`
between the comment line and the declaration line. Cosmetic only (a stray
control character, not wrong text); not fixed, flagged for whoever touches
`cut_to_size` next.
- **Attack angles checked and clean (no finding):**
- *A port declared twice* — first-writer-wins confirmed: the second body
declaration's comment (`// second (duplicate...)`) never appears; only
the first's (`// first`) does, matching `bind_port_decl`'s documented
policy.
- *ANSI mixed with non-ANSI in one header* — a full ANSI port (`input wire
clk,`) and a split non-ANSI port (`data_in`) in the same header list:
`clk` renders exactly one fenced section, `data_in` exactly two, no
cross-contamination.
- *A comment containing `//` inside a string on the declaration line* —
the whole line is shown verbatim regardless (the attachment logic never
parses the line's meaning, only whether `has_comment_after` sees `//`/
`/*` after the name), so there is no wrong-line risk, only the expected
line reproduced as written.
- *`` `ifdef``/`` `endif`` between the header and the body declaration* —
correctly ignored as neither comment-only nor a stolen declaration; the
detail section is exactly the body decl's own line(s). (Note: a
`` `endif``/`` `ifdef``/`` `define`` line sitting where "no other port"
is required is itself treated as "another port" by `another_port_on`'s
conservative word-matching — a false positive that only *declines* to
attach, so it is safe, just another instance of the documented
conservative-below-the-fold behavior, not a new bug.)
- *An attribute (`(* foo *)`) prefixing the next port's declaration* —
correctly detected as "another port" (the attribute's own words split
out as ordinary non-grammar identifiers), so the comment is not stolen.
- *A block comment `/* … */` spanning multiple lines* — the interior lines
are (by design, and correctly) not recognized as comment-only, so the
walk stops there and nothing is attached from inside the block — safe
(declines rather than guesses), matching the documented limitation.
- **Facts-format bump (2 → 3): verified the drop, not a shifted read.**
Wrote and kept a permanent regression test,
`a_store_from_the_previous_facts_format_is_dropped_not_misread`
(`crates/lucisv_server/src/index_cache.rs`, next to the existing
`a_store_from_another_version_is_dropped_whole_and_replaced` and
`a_store_from_the_previous_store_format_is_dropped_whole_and_replaced`,
which cover a `VERSION` mismatch and a `CACHE_FORMAT` mismatch but, before
this, never a `FACTS_FORMAT`-only mismatch). It writes a store whose header
says `FACTS_FORMAT` `2` with today's `CACHE_FORMAT` and `VERSION`
otherwise unchanged, opens it, and asserts `facts_for` returns `None` (the
whole store is unread, not field-shifted) and that the first write since
replaces it under today's header, readable afterward. Passes. This closes
a real test gap the round left — the design (the format number lives in
the header line `IndexCache::open` compares byte-for-byte,
`index_cache.rs:103`) was sound but untested for this exact axis.
- **A3 tie-break: confirmed correct**, both via the shipped
`looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
(passes) and by re-deriving it: `by_name` is built with a **stable** sort
(`Vec::sort_by`, `lib.rs`), so symbols sharing a name keep declaration
order, and `symbols_named`'s two `partition_point` binary searches over
that name-sorted table can only reorder within a name if the sort were
unstable — it is not.
- **`nav::definition` / hover agreement:** confirmed the detail location is
filtered by `!span.is_empty()` (`nav.rs`) exactly as documented, and that a
detail-less symbol (ANSI port, ordinary declaration) still returns exactly
one location, unchanged from before this round.
## Review
**2026-08-28 — lead.** Accepted after one fix round. Gates re-run
independently: fmt clean, clippy silent, `cargo test --workspace` green
(2 396 passing at the time of review), `cargo test -p vlog_formatter` green.
`detail_span` is the right adaptation of the "detail range" idea to this
model: the non-ANSI merge already produced one symbol, so the only thing
missing was *where the declaration is completed*, and recording that as an
optional second span leaves every complete-where-named declaration
untouched. Hover and go-to-definition read the same field, which keeps
`topo.md`'s one-matcher rule intact.
Two things in this feature deserved the scrutiny they got.
**The facts-format bump.** The first implementation added two numbers per
declaration record without moving `FACTS_FORMAT`, on the argument that a
short record fails `done()` and is dropped. That argument only holds for the
*last* declaration in a record; every earlier one would have been read
field-shifted by two, which is a persisted cache handing back wrong spans —
the exact shape invariant 4 exists to catch, in the same family as the
macro-items corruption. Bumping 2→3 is correct and QA's added regression test
(`index_cache.rs`, a store from the previous format is dropped, not misread)
closes a gap no existing test covered, since nothing varied `FACTS_FORMAT`
alone.
**The comment attachment.** This began as scope creep — round 1's plan
explicitly deferred doc comments on hover — and then turned out to be
precisely what the user asked for, so it stays. But it is a *textual*
heuristic running over disk text on the cross-file path, and QA's PDS-1 found
it lying: `another_port_on` was a keyword blacklist, so a wrapped declaration
whose first line is bare `input` looked like an empty line and the next
port's comment attached to the previous port's card. Replacing the blacklist
with a closer whitelist (`only_a_closer_on`) inverts the bias in the one
direction that is safe — an unrecognised line now declines to attach rather
than mis-attaching — and the doc comment states that bias as the contract.
That is the correct resolution; a predicate over source text that guesses
must fail closed.
PDS-2 was a genuine divergence from the user's stated rule and is fixed by
making the three comment sources independent rather than a priority chain.
PDS-3 was worth chasing rather than parking: the binder does perform the same
header/body merge for `TfArg`, so old-style task and function arguments now
get detail spans too, and the gap is closed rather than documented. PDS-4's
CRLF strip is display-only and does not touch the buffer.
The dev renamed and inverted a QA-authored test, and flagged it. Correct call
and correctly surfaced: the behaviour that test pinned *was* the finding.
+443 -15
View File
@@ -50,16 +50,28 @@ not by 64 × 256.
`parse_unary`), one nested generate `if` costs 2 (`parse_item` +
`parse_gen_if`), one `.b` or one `+` costs 1 link. The limits are a
stack-safety budget, not a style rule.
- **8 MiB of stack is available.** That is the default main-thread stack on
macOS and Linux, and `lucisv` parses on the main thread. Anything that parses
on a *spawned* thread must give it a comparable stack — the default 2 MiB
is not enough to reach the limit in an unoptimized build (see Handshakes;
the tests here spawn 16 MiB threads for exactly this reason).
- ~~**8 MiB of stack is available.**~~ **Retired 2026-08-28 — it is now
enforced, not assumed.** This used to say "8 MiB is the default main-thread
stack on macOS and Linux, and `lucisv` parses on the main thread". Both
halves were hazards: the default is not 8 MiB everywhere (`ulimit -s` in a
container, 1 MiB on Windows), and "parses on the main thread" stopped being
true the moment anything spawned. `MAX_NESTING_DEPTH` bounds how *many*
levels run, not what one costs, so the guard only converts an overflow into
an error on a stack big enough to reach level 64. That size is now a
constant — `vlog_parser::PARSE_STACK_SIZE` — and every thread that can
reach a parse is spawned with it, including the two `main`s. See "The stack
the limit needs" and the parse-site table in Handshakes.
- **Unoptimized builds are the worst case.** Debug stack frames in this
parser are large (`parse_keyword_stmt` alone is a ~50 KiB frame at
`opt-level=0`, because rustc gives every match arm's temporaries their own
slot and does not merge them). The limit is picked for debug builds, so
release builds have an order of magnitude more headroom.
- **Frame sizes drift upward, so the stack constant carries margin, not a
fit.** The same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB on
2026-08-28 (rustc 1.97.1) without a line of the parser changing. Nothing in
the build pins a compiler version, and the failure mode is an abort rather
than a diagnostic, so `PARSE_STACK_SIZE` is set at ~2.7× the measured worst
case instead of just above it.
- **Rejecting an over-deep file is acceptable behavior.** The file is left
untouched with a diagnostic and exit 2, exactly like any other parse error.
No real RTL is expected anywhere near the limit; machine-generated
@@ -75,9 +87,16 @@ not by 64 × 256.
```
MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs)
MAX_CHAIN_LENGTH = 256
PARSE_STACK_SIZE = 16 MiB
```
Going one past either produces an ordinary parse error:
The first two bound the input. The third bounds nothing — it is what the
first two *cost*, and it is the size every thread that can reach a parse is
spawned with. The three only work together: a depth limit on a stack too
small to reach it converts nothing, because the overflow (an abort, with no
`Result` to return) happens first.
Going one past either limit produces an ordinary parse error:
```
error: rtl/deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk")
@@ -117,9 +136,12 @@ trips the limit (bisected the same way, minimum surviving thread stack):
| nested `{...}` / `(...)` | 983–1047 KiB | 103 KiB |
| `? :` chains, stacked `~` | 135–423 KiB | — |
So the worst case is **~3.9 MiB in a debug build, ~0.5 MiB in release**,
against an 8 MiB main-thread stack: 2× headroom in the profile with the fat
frames, 16× in the profile users actually run.
So the worst case *as measured in 2026-08* is **~3.9 MiB in a debug build,
~0.5 MiB in release**. Both the number and the stack it was compared against
have since been superseded — see "The stack the limit needs" below, which
re-measures it at ~5.9 MiB over a wider family sweep and replaces "the 8 MiB
main-thread stack" with a stated constant. The table is kept because it is
what 64 was chosen from; the choice still holds under the new numbers.
Why not larger: 128 would need ~7.9 MiB in a debug build — i.e. the CLI
integration tests, which run the *debug* binary, would still overflow before
@@ -168,6 +190,62 @@ fits). Charging chain links against `MAX_NESTING_DEPTH` instead would have
capped those at ~60 terms and rejected real code; that is why chains get
their own, larger budget rather than sharing the nesting one.
### The stack the limit needs — re-measured 2026-08-28
Same method as above (subprocess per trial, bisect the smallest thread stack
that survives), but over the *whole* consumer pipeline this time —
`tokenize` → `parse_tolerant` → `analyze` → `FileFacts`, i.e. what the
language server runs, alongside `format_source`. Two things changed since the
2026-08 numbers: the sweep now covers block families the first round did not
(`case`, `fork`, `foreach`, `while`, `for`, nested modules), and the compiler
moved (rustc 1.97.1).
Peak stack on input sized to *trip* the limit — the global worst case, since
tripping it walks one level further than any legal input can:
| family | debug | release |
|---|---|---|
| nested `case` (any flavour: `casez`, `unique`, `inside`) | **6023 KiB** | **823 KiB** |
| nested `case` + `begin` per level | 5847 KiB | 775 KiB |
| `else if` chains | 5751 KiB | 807 KiB |
| nested `if … begin` | 5735 KiB | 775 KiB |
| nested `begin`, `fork`/`join`, labelled `begin : b` | 5591 KiB | 711 KiB |
| `foreach` / `do … while` | 5447 KiB | 679 KiB |
| `while` / `repeat` / `wait` / `assert … else` | 5367 KiB | 663 KiB |
| generate `for` | 3879 KiB | 583 KiB |
| generate `if` | 1895 KiB | 343 KiB |
| nested `(...)` | 1623 KiB | 183 KiB |
| `@(posedge clk)` chains | 1255 KiB | — |
| nested `module` … `endmodule` | 103 KiB | 23 KiB |
So **~5.9 MiB debug, ~0.8 MiB release**, and ~94 KiB per gated level in a
debug build rather than the ~62 KiB measured in 2026-08. Nested `module` is
cheap because item frames are small; `case` is the ceiling because
`parse_keyword_stmt` carries the fattest frame in the grammar and a `case`
spends two of them per source level (the `case` itself, then the arm's
statement).
Three things the same sweep settles:
- **The peak is entirely in the parser.** `analyze` and `FileFacts` measured
byte-identical to `parse_tolerant` alone in every family, and `analyze` run
*by itself* on a max-legal tree (parsed and dropped on a separate large
thread) needs **71 KiB** — ~1.2 KiB per level. It does not need a bound of
its own; it is two orders of magnitude under the walk that produced the
tree. Same for the tolerant recovery: strict and tolerant parses of the
same limit-tripping input bisect to the same byte.
- **Chains still do not move the worst case.** A 256-link chain alone peaks
at 2487 KiB debug (~9 KiB per link); the same chain inside 58 nested `case`
measures 5895 KiB — identical to that nesting without any chain, because
the two peak in different phases. The additive-composition argument above
is unchanged.
- **16 MiB is the constant, and it is margin rather than a fit.** 8 MiB —
what the CLI's pool used and what a stock main thread happens to have —
is 1.33× the debug worst case, and the last two years of this number moving
(3.9 → 5.9 MiB, no parser change) say that is not enough room. 16 MiB is
2.7×, costs address space rather than memory (thread stacks are committed a
page at a time), and is the size the feature's tests already spawned.
## Where the counters sit
`Parser::enter()` / `Parser::leave()` bracket each gated function; `enter`
@@ -286,17 +364,41 @@ not inflate depth — the output of a max-depth file re-parses inside
expression it has already built — the `Box::new(previous)` shape — must
charge `link()`, or it reopens exactly the hole QA found. Loops that push
into a `Vec` widen the tree instead and need nothing.
- **Request to TODO.md §3's parallel-file-processing item (rayon):** rayon
worker threads default to 2 MiB of stack, which is *not* enough to reach
the depth limit in a debug build (~3.9 MiB needed). Whoever lands
parallelism must set `ThreadPoolBuilder::stack_size(8 * 1024 * 1024)` or
larger, otherwise this feature's guarantee silently regresses to a crash.
Same applies to any future LSP server thread that parses.
- **Promised to every consumer: `vlog_parser::PARSE_STACK_SIZE`.** The depth
limit converts an overflow into a diagnostic *only* on a stack of at least
this size. It is a `pub const` next to the two limits, so no consumer picks
a number of its own and none can drift from the measurement. The rule is
one line: **any thread that can reach `tokenize`/`parse`/`analyze` is
spawned with `stack_size(PARSE_STACK_SIZE)`** — including the thread a
`main` hands its work to, because a process's main stack is set by the OS
and `ulimit`, not by us.
- **Request to TODO.md §6's error-tolerant parsing mode:** recovery must not
reset `depth` while unwinding — it is decremented by `leave()` on the way
out of every gated frame, including error paths, and a sync-and-continue
recovery has to resume from the frame it recovered in.
### Every parse site and the stack it runs on
Audited 2026-08-28 by reading every `thread::spawn` / `thread::Builder` /
`ThreadPoolBuilder` / `par_iter` in `crates/` outside `#[cfg(test)]`. This
table is the enforcement: a new row without a stated stack is the bug.
| site | thread | stack |
|---|---|---|
| `lucisv/src/main.rs` — the whole run (`run_stdin`, `run_files`, `run_check`) | spawned `"lucisv"` | `PARSE_STACK_SIZE` |
| `lucisv/src/main.rs::build_pool` — rayon global pool, used by `run_files`' and `lint.rs`' `par_iter` | rayon workers | `PARSE_STACK_SIZE` |
| `lucisv_server/src/main.rs` — the LSP message loop, which analyses every buffer | spawned `"lucisv-main"` | `PARSE_STACK_SIZE` |
| `lucisv_server/src/server.rs::queue` — forwards `Message`s off the rendezvous channel | spawned `"lucisv-queue"` | default; **never parses** (moves messages, touches no server state) |
| `lsp-server`'s `Connection::stdio()` reader/writer | inside the dependency | default; **never parses** (JSON framing only) |
| both `main` threads | OS-given | irrelevant by construction — they only parse arguments and the LSP handshake, then hand off |
Two sites were the actual hole this round closed. The rayon pool was already
sized (`8 * 1024 * 1024`, from the older ~3.9 MiB measurement, now 1.33× a
re-measured worst case and re-pointed at the constant); the two `main`
threads were not sized at all, which is what "8 MiB of stack is available"
assumed away. `lucisv -` and `lucisv check -` format on the calling thread
and never reach the pool at all, so the CLI's spawn is not redundant with it.
## Status / TODO
- [x] Depth counter (`Parser::depth`) + `enter`/`leave` guard pair.
@@ -334,6 +436,34 @@ From QA round 1 (2026-08-19):
one).
- [x] TODO.md §1 recursion-depth item re-checked after the fix.
Round 3 — the stack the limit needs (2026-08-28, from a QA finding on
`vlog_semantic::FileFacts::of`):
- [x] Diagnosis verified by measurement, not by reading: the overflow is in
the parser's own descent, at level ~30 of an in-budget 64, on a 2 MiB
thread. `analyze`, `FileFacts` and the tolerant recovery add nothing to
the peak.
- [x] Worst case re-measured over every nesting family, debug and release,
through both the LSP pipeline and `format_source`: ~5.9 MiB / ~0.8 MiB,
~94 KiB per gated level in debug. New table above.
- [x] `analyze`'s own walk measured on a max-legal tree (71 KiB, ~1.2 KiB per
level) — no second bound needed, and no second limit constant added.
- [x] `PARSE_STACK_SIZE` (16 MiB) added next to the two limits, `pub`, with
the measured rationale and the margin argument.
- [x] Every production parse site audited and given that stack: the CLI's run
thread, the rayon pool, the language server's message loop. Table in
Handshakes; the two threads that do not parse are named there too.
- [x] `MAX_NESTING_DEPTH` left at 64 — the stack fits the limit, not the
other way round.
- [x] Regression tests on controlled stacks: the reported repro through
`FileFacts::of`, a 14-shape block sweep, at-limit parses for the two
fattest families, and the stdin path through the real binary.
- [x] Existing 16 MiB test threads re-pointed at the constant (`parse_deep`,
`format_deep`), so a shrunk guarantee fails the suite.
- [x] Batch/`catch_unwind` behaviour re-checked end-to-end after the change.
- [x] `cargo test --workspace` (2425), `cargo clippy --all-targets`,
`cargo fmt --check` all clean.
## Work log
### 2026-08-19 — dev agent
@@ -468,6 +598,104 @@ Files touched: `crates/vlog_parser/src/parser.rs`,
grew a second pathological file). `cargo clippy --all-targets` silent.
`cargo fmt --check` clean. Same files touched as the first round.
### 2026-08-28 — dev agent, the stack the limit needs
- **Reproduced first, diagnosed second.** Built a scratchpad probe crate
(path-dependencies on the real crates, never inside the repo) that runs one
shape, one depth, one phase on a thread of a chosen size, as a
*subprocess*, so a stack overflow — which aborts and cannot be caught — is
just a non-zero exit to bisect on. The reported input (500 nested `begin`
through `FileFacts::of`) dies on a 2 MiB thread exactly as reported.
- **The lead's reading is confirmed, and sharper than "64 levels is too
much".** Splitting the pipeline into phases, the minimum surviving stack is
*byte-identical* for `parse_tolerant` alone, `parse_tolerant` + `analyze`,
and the full `FileFacts::of`, in all 25 shapes measured — so the peak is
the parser's own descent, and neither `analyze` nor the record-building
adds a frame above it. Strict and tolerant parses of the same input also
bisect to the same byte, so recovery adds nothing either. At ~94 KiB per
gated level the overflow lands around level 30 of an in-budget 64: the
limiter never gets to fire. Nothing was missing a counter.
- **`analyze` measured on its own** (parse and drop the tree on a separate
256 MiB thread, analyse on the thread being bisected) to make sure the
identical numbers were not masking: **71 KiB** on a max-legal tree, ~1.2 KiB
per level. Two orders of magnitude under the parse. So no second bound and,
per the brief, no second limit constant.
- **Swept 25 shapes rather than the reported one**, because the reported one
is not the worst: nested `case` (6023 KiB debug) beats nested `begin`
(5591 KiB), and neither was in the 2026-08 table. Also measured
`casez`/`unique`/`inside` flavours, `case`+`begin` per level, `fork`/`join`,
labelled blocks, `foreach`, `while`, `for`, `repeat`, `wait`, `do … while`,
`assert … else`, `@(posedge)` chains, generate `if`/`for`, nested modules
and nested tasks. Full table above. The old ~3.9 MiB figure is now ~5.9 MiB
on rustc 1.97.1 without a parser change, which is the argument for margin
rather than a fit.
- **`PARSE_STACK_SIZE = 16 MiB`, and one constant for everything.** 8 MiB —
what the rayon pool already used, and what a stock main thread happens to
have — is 1.33× the debug worst case; 16 MiB is 2.7×, costs address space
rather than resident memory, and is the number the feature's own tests were
already spawning. Putting it in `vlog_parser` beside `MAX_NESTING_DEPTH` is
what stops it drifting: the tests now spell the constant instead of
`16 * 1024 * 1024`, so cutting the guarantee below what the limit needs
fails the suite rather than the user.
- **Audited every parse site** (`thread::spawn`, `thread::Builder`,
`ThreadPoolBuilder`, `par_iter` across `crates/`, excluding
`#[cfg(test)]`); table in Handshakes. The rayon pool was the only one that
had a stated stack. The two `main` threads had none — that is what "8 MiB
of stack is available" was assuming, and it is not true on Windows, under a
tuned `ulimit -s`, or for anyone who later moves work onto a thread. Both
`main`s now hand their work to a thread sized by the constant.
- **The CLI's spawn is not redundant with the pool.** `docs/features/
parallel-files` established (with a probe, and re-verified by QA) that
rayon's `par_iter` called from outside the pool *blocks* the caller instead
of running jobs on it. But `lucisv -` and `lucisv check -` never build a
pool at all: they format the buffer on the calling thread. That path had no
stated stack until this change, and it is the one the new CLI test covers.
- **Deliberately not done: lowering `MAX_NESTING_DEPTH`.** Per the brief, and
because it would change which real files parse. The stack fits the limit.
- **Deliberately not done: shrinking the parser's frames.** The 2026-08 round
measured that experiment (extracting one `match` arm moved
`parse_keyword_stmt` 50,528 → 47,872 B) and rejected it; nothing has
changed that calculus, and this round's fix does not need it.
- **Tests, all on controlled stacks so they cannot be flaky across
environments** — `vlog_semantic/tests/deep_nesting.rs` is new
(`five_hundred_nested_blocks_are_indexed_not_aborted` — the reported repro,
which now indexes module `m` with the unparsable body recovered;
`no_block_shape_can_abort_the_parse_stack` — 14 shapes at 400 levels
including nested modules, tasks, functions, fork/join, generate blocks and
else-if chains; `nesting_just_under_the_limit_still_yields_its_facts`).
`vlog_parser` gained `deep_nesting_errors_for_every_block_form` and
`the_fattest_block_forms_still_parse_at_the_limit`; `lucisv` gained
`a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash`.
- **Sabotage-verified the new tests the way QA does**: set
`PARSE_STACK_SIZE` to 2 MiB, rebuilt, and `cargo test -p vlog_semantic
--test deep_nesting` died with `SIGABRT` / "fatal runtime error: stack
overflow" instead of failing an assertion — i.e. the tests are pinned to
the constant, not merely passing beside it. Restored and re-ran green.
- **Re-checked the batch/`catch_unwind` claims** end-to-end with the real
debug binary on a 4-file directory (`good`, 500 nested `begin`, 400 nested
`case`, `good`): `2 files reformatted, 2 files failed to format`, exit 2,
both deep files left untouched, no abort. Also drove the real
`lucisv-server` over stdio with the 500-level buffer: `initialize`,
`didOpen`, `publishDiagnostics`, a `documentSymbol` answer naming module
`m`, clean `shutdown`/`exit` 0.
- **Touched two files outside this feature, both because they now contradict
the code:** `docs/features/parallel-files/README.md`'s "8 MiB of worker
stack is enough" assumption and its recursion-limit handshake bullet, and
the same number in TODO.md §3's parallel-file item. Only the living
contract sentences — that feature's work log and QA log are history and
were left alone.
**Results:** `cargo test --workspace` **2425 passed, 0 failed** (up 8: +2
`vlog_parser` unit, +3 `vlog_semantic` `deep_nesting`, +1 `lucisv` CLI, and
two pre-existing helpers re-pointed at the constant). `cargo clippy
--all-targets` silent. `cargo fmt --check` clean. Files touched:
`crates/vlog_parser/src/parser.rs`, `crates/vlog_parser/src/lib.rs`,
`crates/lucisv/src/main.rs`, `crates/lucisv_server/src/main.rs`,
`crates/lucisv_server/src/server.rs` (one doc comment),
`crates/vlog_formatter/tests/deep_nesting.rs`, `crates/lucisv/tests/cli.rs`,
`crates/vlog_semantic/tests/deep_nesting.rs` (new),
`docs/features/parallel-files/README.md`, `TODO.md`, this README.
## QA log
### 2026-08-19 — QA agent
@@ -884,8 +1112,208 @@ No new BLOCKING finding. No code changes made this round (the one finding
is a documentation number, not something I judged a "small unambiguous
fix" worth touching without the dev confirming their construction).
### 2026-08-28 — QA agent, the stack the limit needs
**Tooling results (verbatim):** `cargo fmt --check`: clean, exit 0.
`cargo clippy --all-targets`: silent, no warnings. `cargo test --workspace`:
every binary green, 0 failed across the run (`vlog_parser` lib 1204 passed/23
ignored, `vlog_semantic` 82 + 62 + 3 new `deep_nesting`, `vlog_formatter` 4
`deep_nesting`, `lucisv` 217 + the new stdin test, `lucisv_server` 190 + 20 +
114 + others, doc-tests all 0/0 except `vlog_linter`'s 1/1) — matches the
dev's "2425 passed, 0 failed" claim (one transient doctest failure on a first
run, `vlog_linter`'s, traced to a stale rlib left by my own concurrent
`git stash`/rebuild during the ulimit test below, not a real regression —
reran `cargo test -p vlog_linter --doc` clean on its own and the next full
`cargo test --workspace` was clean too).
**Independent audit of every thread/pool/par_iter outside `#[cfg(test)]`
(charter item 1) — matches the dev's table exactly, no missed site.**
`grep -rn "thread::spawn\|thread::Builder\|ThreadPoolBuilder\|par_iter\|\.spawn("
crates --include="*.rs"` and traced every hit:
- `lucisv/src/main.rs`'s own spawn (the "lucisv" thread) and `build_pool`
(rayon global pool): both `PARSE_STACK_SIZE`, as claimed.
- `lucisv/src/lint.rs:48`'s `jobs.par_iter()` (the `check` subcommand,
charter's "vlog_linter/vlog_refactor entry points from the CLI pool"):
confirmed it runs on the *same* rayon global pool `build_pool` sizes —
`run_check` calls `gather(opts).and_then(|jobs| build_pool(opts).map(...))`
before `lint::check_files`, same as `run_files`. `check`'s stdin path
(`lint::check_stdin`) never touches the pool at all; it runs on `run_check`
called from `run()`, which is the body of the spawned "lucisv" thread — so
it inherits `PARSE_STACK_SIZE` the same way `run_stdin` does. Not a missed
site; the dev's table entry ("the whole run") already covers it, just not
spelled out by name.
- `lucisv_server/src/main.rs`'s spawn and `server.rs::queue`'s forwarder:
match the table.
- `lucisv_server/src/index_cache.rs:921,1194` and `state.rs:3374` (a
`qa_attack_…` test spawning at a deliberate 64 MiB, with a comment citing a
*different*, pre-existing recursion ceiling filed in `index-scope`'s own
2026-08-28 QA log) — all three are inside `#[cfg(test)] mod tests`
(checked with `grep -n "#\[cfg(test)\]"` in each file), so they are
correctly outside the dev's stated audit scope ("outside `#[cfg(test)]`")
and outside production risk. Tried to find a production path to them
anyway (workspace-scan-on-`initialize`, watched-file rescans) — found none;
`index_cache`'s writers only run inside its own test module.
- `lsp-server` 0.10.0's own threads (`stdio.rs`): read the vendored source at
`~/.cargo/registry/src/…/lsp-server-0.10.0/src/stdio.rs` — reader and
writer threads only frame/deframe `Message` (JSON-RPC header parsing via
`usize::parse`, unrelated to `vlog_parser`), no `vlog_parser` symbol
anywhere in the crate. Confirms charter item 2's second half directly from
the dependency's source, not by inference.
- `server.rs::queue` (charter item 2's first half): read `queue()` and
`run()` in full. The forwarder thread's closure captures only
`source`/`sender`, does `source.recv()` → `sender.send()` → break on
`is_shutdown`/`Err`, touches no field of `Server`; `run()` and
`process_batch` are the only things that call `self.request`/
`self.notification` (which reach analysis), and they execute on the
thread `Server::run` was called on, i.e. the spawned `"lucisv-main"`
thread. The module doc at `server.rs:1` ("one burst in, one response per
request, on one thread") holds; `didChangeWatchedFiles` and every other
notification dispatch through `Server::notification` (`server.rs:1249`),
called only from `process_batch`, same thread.
No un-gated production parse-reachable spawn found. Dev's table is accurate
and complete.
**Charter item 3 (library-consumer footgun) — real gap found, fixed
directly as a small unambiguous doc fix.** The README's Handshakes section
states the contract plainly ("any thread that can reach
`tokenize`/`parse`/`analyze` is spawned with `stack_size(PARSE_STACK_SIZE)`"),
but that is an internal project document, not rustdoc — a consumer of
`vlog_parser`/`vlog_semantic`/`vlog_formatter` as a library reads the public
items' own doc comments, and none of them said anything: `vlog_parser::parse`
(`parser.rs:271`), `parse_tolerant` (`parser.rs:283`), `vlog_semantic::
FileFacts::of` (`workspace.rs:741`), `vlog_formatter::format_source`
(`format.rs:80`) and `format_range` (`format.rs:101`) — the five public
entry points that actually recurse over caller-supplied input — carried no
stack-size mention at all. Confirmed by reading each doc comment before this
fix; `tokenize` (`lexer.rs:731`) checked too and correctly excluded — it is
loop-based with no recursion on nesting, so it carries no such requirement.
Added a one- to three-line note to each of the five, referencing
`PARSE_STACK_SIZE` and (except `parse`/`parse_tolerant`, which are right next
to the constant) `docs/features/recursion-limit/README.md`. Files touched:
`crates/vlog_parser/src/parser.rs`, `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_formatter/src/format.rs`. Re-ran `cargo fmt --check` and
`cargo clippy --all-targets` after — both still clean.
**Charter item 4 (sabotage re-verify), on a scratchpad copy, never the
repo under review.**
- `PARSE_STACK_SIZE` 16 MiB → 2 MiB, rebuilt: `cargo test -p vlog_semantic
--test deep_nesting`, `cargo test -p vlog_formatter --test deep_nesting`
and `cargo test -p vlog_parser --lib` (which builds `parse_deep` on the
same constant) **all SIGABRT** ("stack overflow, aborting", signal 6) —
every deep-nesting test suite genuinely depends on the constant rather
than merely running beside it. Restored to 16 MiB and reran: all three
green again (`vlog_semantic`: 3/3, `vlog_formatter`: 4/4, `vlog_parser`
lib: full suite).
- `MAX_NESTING_DEPTH` 64 → 128, `PARSE_STACK_SIZE` left at 16 MiB (the
"double the limit, keep the stack" margin check): `vlog_semantic`'s
`deep_nesting` (3/3), `vlog_formatter`'s `deep_nesting` (4/4) and
`vlog_parser`'s `nesting_just_below_the_limit_parses`,
`chain_just_below_the_limit_parses`, `the_fattest_block_forms_still_
parse_at_the_limit` and `deep_nesting_errors_for_every_block_form` all
**passed** — including `the_fattest_block_forms_still_parse_at_the_limit`,
which now parses 122-deep `fork`/`case` nesting (`MAX_NESTING_DEPTH - 6`)
on the same 16 MiB stack that only had to reach 58 before. The 2.7×
margin is real, not illusory: it survives doubling the depth the tests
actually walk. Reverted `MAX_NESTING_DEPTH` to 64. Verified afterward that
the working tree's `parser.rs` shows only the intended diff (`grep -n
"MAX_NESTING_DEPTH: u32\|PARSE_STACK_SIZE: usize"` → `64` and
`16 * 1024 * 1024`, matching what `git status` shows for the round under
review).
**Charter item 5 (binary end-to-end) — both scenarios behave as claimed,
and the pre-fix binary was rebuilt to confirm the deviation is load-bearing,
not cosmetic.**
- Directory run: a temp dir with `good.sv` and a 500-nested-`begin` file
through `./target/debug/lucisv .`: `error: ./deep500.sv: parse error:
64:1: nesting too deep (limit 64) (found "begin")` /
`1 file left unchanged, 1 file failed to format`, exit 2. `good.sv`
untouched (it was already formatted), `deep500.sv`'s first 60 bytes
confirmed byte-identical to the input. No abort.
- `ulimit -s 1024; lucisv - < deep500.sv` (1 MiB main-thread stack) on the
**fixed** binary: `error: <stdin>: parse error: 64:1: nesting too deep
(limit 64) (found "begin")`, exit 2, no crash.
- To confirm this isn't true regardless of the fix (i.e. that the moved-main
deviation actually matters, not just the depth counter): stashed the
round's diff (`git stash`, working tree confirmed clean via `git status`),
rebuilt `lucisv`, and ran the identical `ulimit -s 1024` command against
the **pre-fix** binary: `thread 'main' (…) has overflowed its stack /
fatal runtime error: stack overflow, aborting`, exit 134 (SIGABRT) — same
input, same shell, only the binary differs. Popped the stash (`git stash
pop`, confirmed all twelve modified files and the new test file were back)
and rebuilt the fixed binary; reran the same command to reconfirm exit 2.
This is the one experiment in this round that actually falsifies "the
depth counter alone was always going to be enough" — it was not, on a
shell with a small `ulimit -s`, until `main` stopped running on the OS-given
stack.
**Charter item 5, LSP half — independently reproduced via a standalone LSP
client (not the dev's own manual verification, not the checked-in `e2e.rs`
suite, which has no test for this exact repro).** Wrote a small Python
script (framed JSON-RPC over the real `lucisv-server` binary's stdio) that
sends `initialize` → `initialized` → `didOpen` (the 500-nested-`begin` file)
→ `documentSymbol` → `shutdown` → `exit`. Result: `publishDiagnostics` with
`"nesting too deep (limit 64) (found \"begin\")"` at line 63, a second
diagnostic for the resulting `endmodule` mismatch, `documentSymbol` still
answers with module `m` (`range` spanning the whole 564-line file), clean
`shutdown` (`id: 99, result: null`) and process exit code 0. No crash, no
hang, matches the dev's manual claim independently.
**Charter item 6 (idempotency/corruption) — holds.** On the fixed binary:
a 58-nested-`begin` file (one under the dev's stated 59/60 with-statement
boundary — chosen so the *statement* inside costs its extra levels too, same
construction the boundary table uses) formats once, then formats again from
its own output: `diff` reports the two outputs identical, i.e.
`format(format(x)) == format(x)`. The 500-nested-`begin` file piped through
`lucisv -`: stdout is exactly 0 bytes (no partial output), stderr carries
the one-line diagnostic, exit 2 — the "verified-correct output or the input
unchanged with an error, never partial" invariant holds for the rejection
path on the CLI's own thread, consistent with the directory-run and
`vlog_semantic` test evidence that the tolerant/LSP path never produces a
corrupted tree either (recovery yields an `ItemKind::Error` leaf, not
partial/wrong facts).
**Verdict: SHIP.** No blocking or medium finding. One low finding (the
library-consumer stack-size contract living only in an internal README, not
in any public item's rustdoc) fixed directly per CLAUDE.md's "small
unambiguous fix" allowance — five doc comments, no behavior change, gates
re-confirmed clean after. The round's own claims all independently
reproduced: the audit table is complete, the forwarder and `lsp-server`
threads are confirmed parse-free by reading their code (not just trusting
the comment), the stack-size guarantee is real under sabotage in both
directions (shrinking it breaks the tests it should break; doubling the
depth limit under the existing stack does not), and both the CLI and LSP
binaries handle the original repro gracefully end-to-end, including the one
scenario (`ulimit -s 1024`) where the pre-fix binary provably still crashes.
## Review
**2026-08-28 — lead, stack-budget round.** Reviewed after QA's SHIP;
gates re-run independently (fmt clean, clippy silent, 2425 workspace
tests green). The round did the right thing with the diagnosis: nothing
was missing a counter — the 2026-08 feature's own "8 MiB is available"
Assumption was the unenforced hole, and its measured basis had silently
drifted (~62→~94 KiB per level under rustc 1.97, worst family now
nested `case`, never measured in the original round). Turning the
assumption into one code-enforced constant (`PARSE_STACK_SIZE`, 16 MiB,
2.7× over the re-measured worst case) applied at every parse-reaching
spawn site is the boring fix the situation wanted; the dev's deviation
of moving both binaries' work off the main thread is load-bearing, not
cosmetic — QA proved the pre-fix binary aborts under `ulimit -s 1024`
where the fixed one emits a diagnostic, and the win32 target's 1 MiB
default main stack made this a real shipped-binary risk, not just a
test-thread artifact. QA's independent spawn-site audit matched the
dev's table exactly, the sabotage runs prove the tests exercise the
guarantee (2 MiB → SIGABRT) and the margin survives doubling the depth
limit, and its doc fix — the caller-side stack contract on every public
parse entry point's rustdoc — closes the library-consumer footgun the
lead's charter flagged. Invariant 1 spot-checks (no partial output on
rejection, idempotent round-trip at depth) held. Accepted; committed by
the lead.
**2026-08-19 — lead. Verdict: accepted and committed after one rejection
and a verified rework.**
+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
+525 -1
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
@@ -116,10 +122,69 @@ standard capability both VS Code's built-in client and Neovim's `vim.lsp`
consume on their own once it is advertised; no extension change was needed
and none was made.
**Requested of other modules**: none.
**Requested of other modules (2026-08-28) — DELIVERED 2026-08-28** by the
index-scope round; see `docs/features/index-scope/README.md`, work log
"a rescan stops re-parsing what is already analyzed". An open buffer's index
facts and completion words now come from the analysis it already holds
(`FileFacts::from_analysis`, `words_of_tokens`), on the whole-rebuild path and
on `update_one`'s: **~228 ms → ~23 ms** on this feature's own probe. The request
as it was written:
**Requested of other modules (2026-08-28):** a scope-widening `didOpen`
re-parses every open buffer. `Workspace::collect_sources`
(`crates/lucisv_server/src/state.rs`) clones each open document's text into the
list the index is rebuilt from, so a rescan triggered by opening some *other*
file pays a full lex-and-parse of every buffer the user has open — measured at
**210 ms of a 223 ms rescan** for one 1.4 MB `top.sv`, against 13 ms for the
same 401-file scope with that buffer closed. Every open buffer already holds a
finished parse and `Semantics`; `FileFacts::of` re-does both from the text.
This is `index-scope` / `state.rs` territory, not this feature's, and the
2026-08-28 brief said measure it and stop — so it is written here rather than
changed. The obvious shape (an `IndexBuilder::add_facts` path fed from the
buffer's existing analysis instead of its text) is a real option and a separate
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:
a **spelled-name prefilter** and a **hoisted `file_id`** in
`indexed_references`'s open-document overlay loop, and **walker-batched**
span conversion in the two in-file fallbacks. Release probes:
**3.20 ms → 110 µs** from the use site, **3.18 ms → 110 µs** from the
declaration (29×); the in-file fallback for a signal used 10 001 times,
**1.76 ms → 1.18 ms**, and `documentHighlight` on it **1.54 ms → 917 µs**.
No answer changes — the equivalence test against
`vlog_refactor::find_references` and the whole nav suite are untouched
and green.
- [x] **Not this feature's to fix, measured and filed (2026-08-28) — fixed
elsewhere the same day:** the owner-reported *asymmetry* is not in
`references` at all — both directions cost the same, before and after.
What is expensive is the `didOpen` that jumping into another folder's
file triggers: **220 ms**, of which **210 ms** is re-parsing the open big
buffer during the scope-widening rescan. See the work log and
Handshakes. Landed by `index-scope` on 2026-08-28 — the open buffer's
facts and words now come from its own finished analysis — and this
feature's `qa_didopen_latency_when_a_new_folder_widens_the_scope` probe
reads **~228 ms → ~23 ms**, with its closed-buffer floor unmoved at
~12 ms. The probe now also prints the buffer's own share of a rescan,
before and after, on every run.
- [x] **Indexed navigation performance (2026-08-27):** persist each file's
externally reachable reference facts beside its declarations, merge them
into declaration-to-occurrence postings in `WorkspaceIndex`, and route
@@ -165,6 +230,195 @@ and none was made.
## 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`
toward a module as "still very slow", and the same request from the module's
*declaration* toward its uses as fast. Both run the same
`indexed_references`, so the asymmetry was unexplained. Measured first.
**The fixture.** Two `#[ignore]`d probes in `nav.rs`'s own test module, beside
the `qa_indexed_references_latency_over_a_large_workspace` probe that has been
there since 2026-08-27, and taken with `perf::mean` (now `pub(crate)`) so every
number in this repo is timed the same way. `generated_top(10_000, 4)` is a
40 000-line, 1 374 KB module of ordinary RTL blocks — a wire, an assign, a
register and its update — carrying **70 024 references**, four instantiations
of a small `sub`, and one local `acc` used by every block so the file also has
a *local* name with 10 001 occurrences. Both files are open documents; the
index is built over the directory.
```text
cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1
```
Machine: the one `docs/perf/README.md` records — Apple M1 Max, macOS 27.0,
`--release`. Means of 20 runs (5 for the rescan rows).
| what | before | after |
|---|---|---|
| `references` from the **use site** in `top.sv`, `includeDeclaration` | **3.20 ms** | **110 µs** |
| `references` from the **declaration** in `sub.sv`, same | **3.18 ms** | **110 µs** |
| `definition` from the use site | 1.21 µs | 1.13 µs |
| `references` on a local wire used 3× (the in-file fallback) | 1.49 µs | 1.20 µs |
| `references` on a local wire used 10 001× | **1.76 ms** | **1.18 ms** |
| `documentHighlight` on that same wire | **1.54 ms** | **917 µs** |
**Hypothesis 1 is convicted, and it is symmetric.** The open-document overlay
loop was the whole 3.2 ms: for every one of the 70 024 references in the open
buffer it ran either `indexed_def_for_symbol` — a `file_id` binary search whose
comparisons are whole-path `cmp`s, plus a `units`/`member` `BTreeMap` lookup,
plus a scope-and-owner chase — or a `doc.external` hash lookup, to discard all
but five of them. It cost that whichever end the cursor was on, which is the
first thing the measurement says: **the two directions are within 1 % of each
other, before and after.** The owner's asymmetry is not in `references`.
**Hypothesis 2 registers, but only for a common local name.** The in-file
fallback and `documentHighlight` convert their spans one at a time with
`positions.range`, which re-measures a line per span. On three occurrences that
is 1.5 µs and invisible; on 10 001 it is 1.76 ms. Both now batch-convert with
`positions.walker()` over the already-sorted span list, exactly as `locations`
has done for the cross-file answer since this feature shipped — 1.5× and 1.7×.
The rest of those two figures is collecting, sorting and allocating 10 001
spans, which is the answer's own size and not something to shave here.
**Hypothesis 3 is where the felt latency actually is** — measured, and
deliberately not redesigned this round (see Handshakes). With the same 1.4 MB
buffer open and 401 files in scope:
| `didOpen` | cost |
|---|---|
| a file the folder scope **already covers** | **8.4 µs** |
| a file in a **new folder** (`didOpen` + the rescan `server.rs` then runs) | **220 ms** |
| — the rescan alone | 223 ms |
| — the same rescan with the big buffer **closed** | **13 ms** |
So the scope-widening rescan is 223 ms, and **210 ms of it is the open big
buffer**: `Workspace::collect_sources` clones every open document's text into
the source list and the index re-parses it, at full lex-and-parse cost, on a
rescan that was triggered by an entirely different file. That is the shape that
matches the owner's report: F12 or a references result *from* `top.sv` opens the
module's file, and when that file lives in a folder the folder scope had not
reached, the `didOpen` widens the scope and pays a whole rescan. The reverse
direction — standing on the declaration and listing its uses — opens nothing
new and pays nothing. Filed as a Handshake request against `index-scope` /
`state.rs`; no scope code was touched.
**The prefilter, and why it changes no answer.** The new first line of the
overlay loop is `if reference.name != target.name { continue }`. It is sound
because *a `Def` in this index determines the name it is filed under*, and both
sides of the old comparison are filed under a name the code already has in
hand:
- Every indexed `Def` is pushed into `units[name]` or `members[unit][name]`
under its own declaration's `name`, and both `facts_of` and `collect_members`
skip any declaration whose `name_span` is empty. A non-empty byte range in
one file is one identifier, spelling one name — so two different keys cannot
hold one `Def` value, and `target.def`'s key is `target.name` in both
`indexed_target` arms (the `Local` arm looks the def up *by* `symbol.name`
and stores that as `name`; the `External` arm stores the cursor reference's
own `name`, which is the only key `follow_one` looks a def up under).
- A reference that would have matched is filed under `reference.name`. In the
Local arm, a `Resolution::Resolved` comes from `lookup_local(name)` (or an
end label the binder checked spells the declaration's name), so
`symbol.name == reference.name`, and `indexed_def_in_file` looks up
`units[symbol.name]` / `members[owner][symbol.name]`. In the External arm,
`resolve_external` calls `follow_one(index, reference.name, path)`, which
only ever reads `units[reference.name]` or `member(unit, reference.name)`.
So `def == target.def` implies `reference.name == target.name`, and skipping
the name-mismatched references skips only work whose answer was `false`.
**The `Ambiguous` refusal survives it**, by the same step: the candidates in
`ExternalTarget::Ambiguous(defs)` all come out of the bucket keyed by
`reference.name`, so `defs.contains(&target.def)` can only be true for a
reference spelling `target.name` — which the prefilter always lets through. The
`name_span.is_empty()` guard was deliberately *not* hoisted into the prefilter
for the same reason: an ambiguous use aborts the whole collection whether or not
it has a span, and moving that check earlier would have been a real behaviour
change.
**The hoist.** `indexed_def_for_symbol` is now two functions: the public one
(unchanged signature, still `hover.rs`'s) resolves the document's `FileId` and
calls `indexed_def_in_file`, which takes it as an argument. The overlay loop
takes the `file_id` once per open buffer instead of once per reference.
**What is left at 110 µs** is the loop itself: 70 024 string comparisons plus
the iteration. Making that sublinear means a name-keyed reference side table in
`Semantics` — the shape `symbols_named` already has for declarations — which is
a `vlog_semantic` change this round's brief put out of scope. Not needed at
110 µs; worth naming as the next lever if a file ten times this size shows up.
**Tests added** (permanent, all three green before and after the change, which
is the point — the prefilter must change cost and not answers):
- `a_same_named_port_in_another_open_buffer_is_a_different_symbol` — two
modules declare a port `clk`, all three files open; each port's references
are its own. The prefilter's risk case, from both sides.
- `two_packages_declaring_one_name_keep_their_references_apart` — the same
attack through the member table: `p::WIDTH` and `q::WIDTH` used on adjacent
lines of one open file, asked from the declaration and from the use.
- `every_in_file_occurrence_is_converted_against_its_own_line` — 41
occurrences over 40 lines each carrying a multi-byte and an astral character;
every reported range is checked to point at the name, and
`documentHighlight`'s ranges are asserted equal to `references`'. A walker
handed spans out of order would answer stale columns here.
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
zero warnings; `cargo test --workspace` **2 406 passed, 0 failed** (3 ignored
probes in `nav.rs`, one of them pre-existing). Files edited:
`crates/lucisv_server/src/nav.rs` and one `pub(crate)` on `perf::mean`. No new
dependencies, no `unsafe`, no `unwrap`/`expect` outside `#[cfg(test)]`, no new
`#[allow]`. `TODO.md` untouched — this round closes no backlog item; M7 is
already checked. Did not `git commit`/`git push`.
### 2026-08-27 — indexed navigation performance
- Began replacing the per-request `Workspace::sources()` +
@@ -270,6 +524,158 @@ Files added: `crates/vlog_refactor/src/references.rs`,
## QA log
### 2026-08-28 — QA agent, references-latency round
Adversarial charter: try to make the new spelled-name prefilter (`nav.rs:248`,
`indexed_references`) **change an answer**. Slower-but-right was already true;
only a changed answer is a defect this round.
#### Soundness of the prefilter — traced by construction, not just trusted
Read the dev's write-up's claim against the actual code that makes it true,
rather than the prose alone:
- `Def` (`crates/vlog_semantic/src/workspace.rs:33`) derives `PartialEq` over
`(file, name_span, kind, detail_span)` — it carries no name at all. Its
identity is "this declaration, right here," so `def == target.def` can only
be decided by the site it points at, never by a spelling.
- Every `Decl` is filed under exactly one key, its own declared name:
`self.units.entry(decl.name.clone())...push(decl.def(file))`
(`workspace.rs:529`) and `self.members.entry(unit.clone())...entry(decl.name.clone())...push(decl.def(file))`
(`workspace.rs:535-540`). `decl.name` traces back to `Symbol.name`
(`Decl::of`, `workspace.rs:654`), and `Symbol.name`/the scope's `names` map
key are the same `name.to_string()` written in one `declare` call
(`bind.rs:141` and `bind.rs:151`) — so a `Def` cannot be filed under a name
it wasn't declared with, and cannot be filed under two names.
- `Scope::lookup_local` (`model.rs:215`) is a plain `HashMap<String,
SymbolId>` `get` — no case-folding, no normalization. Every
`Resolution::Resolved(id)` in `resolve.rs` comes from `lookup_local(&p.name)`
(or `Target::Declaration(id)`, an end label the binder already matched to
its opener's name). `Reference.name` is `p.name.clone()` at the exact
construction site (`lib.rs:78-79`). So a **locally** resolved reference's
`.name` is *definitionally* `symbol.name` — the prefilter reads the same
field the binder used to decide the match, not a second, potentially
divergent, source of truth.
- The **external** arm is the same shape one level up: `resolve_external`
(`workspace.rs:1097`) always calls `follow_paths(index, &reference.name,
paths)`, and `follow_one` (`workspace.rs:1132`) always queries
`index.units(name)` or `index.member(unit, name)` with that same `name` —
`path` only picks *which* table, never the key. So both `Resolved(def)` and
`Ambiguous(defs)` for a reference are always drawn from the bucket keyed by
that reference's own `.name`, which makes the dev's ambiguity-survives
argument mechanical rather than incidental: `defs.contains(&target.def)`
can only be true when `defs` came from the `target.name` bucket, which only
happens when `reference.name == target.name` — exactly what the prefilter
already let through.
No escaped-identifier or case-folding attack survives this: the lexer
(`crates/vlog_parser/src/lexer.rs:304-318`) keeps an escaped identifier's
leading backslash in the token text (`\sub` and `sub` are different strings
at the token level already), and nothing between the lexer and
`Scope::names` ever folds case or strips it — so whatever the binder already
does or doesn't unify, the prefilter reads the identical field the binder
matched on. There is no code path where `reference.name` and the spelling the
binder used to resolve it can diverge, so there is no daylight for the
prefilter to exploit. Traced, not fuzzed — I did not find a construction
worth writing as a failing-if-regressed test beyond what's below, because the
invariant is enforced by there being exactly one string in play, not by a
check that could later be weakened unnoticed.
**Verdict on the prefilter: sound, no answer-changing case found.**
#### Attempts to break it anyway
- **Port connection vs. declared name, member-table variant.** Extended the
attack beyond the dev's own two tests (`a_same_named_port_in_another_open_buffer_is_a_different_symbol`,
`two_packages_declaring_one_name_keep_their_references_apart`) with a name
that is a **unit in one file and a member in another** — `module W` and
`package p; localparam W = 4;` — plus a **live unsaved edit** to the file
using both (a second instantiation added post-open, never saved). Added as
`indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member`
(`nav.rs:662`), asserted equal to `vlog_refactor::find_references` on
`ws.sources()` (which itself overlays the unsaved edit) in both directions.
Passed first try — no answer conflation between the `units` and `members`
buckets, and the unsaved instantiation is correctly counted.
- **Walker ordering/multi-byte/astral attack** on the two newly-batched
conversion sites (`in_file_references` and `document_highlights`, now both
walker-based per `nav.rs:347` and `nav.rs:374`). The dev's own
`every_in_file_occurrence_is_converted_against_its_own_line` already covers
this shape well (41 occurrences over 40 lines, each preceded by a
multi-byte and an astral character, every reported range checked against
the actual byte); I did not find a shape it misses. The walker itself
(`crates/lucisv_server/src/convert.rs`, `PositionWalker`) is pre-existing,
general-purpose infrastructure (`locations()` has used it since the
2026-08-27 round) with its own dedicated tests for out-of-order offsets,
ping-ponging between far-apart lines, and an empty document
(`the_walker_agrees_with_the_per_call_converter_on_every_shape`,
`a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position`,
`a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly`,
`a_walker_over_an_empty_document_answers_the_one_position_there_is`, all in
`convert.rs`) — so the only new risk this round is whether
`in_file_references`/`document_highlights` feed it spans in order, and they
do: both consume `occurrences()`, which sorts by `span.start`
(`nav.rs:413`) before the walker ever sees them. No out-of-order feed
exists on either path.
- **Ambiguous-abort still aborts.** Re-ran
`a_name_declared_in_two_files_degrades_references_to_the_in_file_answer`
(already in the suite, unmodified by the dev this round) and traced the
`Ambiguous(defs) if defs.contains(&target.def) => return None` arm
(`nav.rs:258-260`) by hand against the bucket argument above: an ambiguous
external use can only carry `target.def` in its candidate set when it
spells `target.name`, which is exactly when the prefilter lets it reach
this arm. Confirmed by construction, not just by the still-green test.
- **Equivalence, existing test.** `indexed_references_equal_the_refactor_walk_they_replace`
(`nav.rs:648`, pre-dating this round) still passes unmodified.
#### Measurements reproduced (release, `--release`, this machine)
```
cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1
```
| what | work log | reproduced here |
|---|---|---|
| references, use site | 110 µs | 109.8 µs |
| references, declaration | 110 µs | 108.9 µs |
| definition, use site | 1.13 µs | 0.82 µs |
| in-file, wire used 3× | 1.20 µs | 1.12 µs |
| in-file, wire used 10 001× | 1.18 ms | 1.17 ms |
| documentHighlight, same wire | 917 µs | 916 µs |
| didOpen, scope already covers | 8.4 µs | 7.3 µs |
| didOpen, new folder (+ rescan) | 220 ms | 214.6 ms |
| rescan alone | 223 ms | 217.7 ms |
| rescan, big buffer closed | 13 ms | 12.5 ms |
All within the charter's 2-3× tolerance (most within 5%) — no contradiction
of the work log's order-of-magnitude claims. The pre-existing
`qa_indexed_references_latency_over_a_large_workspace` probe (2026-08-27,
untouched by this round) also still ran clean: 0.068 ms/request vs. 31.35 ms
for the old walk on this machine, consistent with that round's own numbers.
#### Gates
- `cargo fmt --all -- --check` — clean.
- `cargo clippy --all-targets --all-features` — clean, zero warnings (forced
re-check by `touch`ing the changed files first, not a cache hit).
- `cargo test --workspace` — **2 406 passed, 0 failed** before my addition,
matching the work log's count exactly; **2 407** after adding the one
permanent equivalence test above. 24 ignored across the workspace (3 in
`nav.rs`, one of those pre-existing, matching the work log).
**All gates: pass, claims confirmed.**
#### Verdict
**SHIP.** No corruption, no answer change, no crash found under the
adversarial charter. The prefilter's soundness holds by construction (one
string, read by both the binder and the prefilter, never normalized or
duplicated anywhere in between), not merely by the tests passing. One
permanent regression test added
(`indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member`,
`nav.rs:662`) for the nastier unit/member name-collision case with a live
unsaved edit, requested by the round's brief; no other findings warranted a
fix or a new test. Review section left untouched.
### 2026-08-24 — QA agent
#### Gates
@@ -520,8 +926,126 @@ 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
written and their before-numbers recorded ahead of any fix, and they
convicted the overlay loop (H1) while acquitting `references` of the
owner-reported asymmetry — which the didOpen numbers (H3) explain
instead, correctly filed as a Handshake request rather than fixed
cross-scope. The prefilter comment in `indexed_references` points at
the soundness argument, QA traced that argument to the code
(single-key filing, no name normalization anywhere between lexer and
lookup), and the unit-vs-member equivalence test QA added is the
sharpest same-spelling case the design admits. The empty-span check
deliberately left unhoisted — so a spanless ambiguous use still aborts
— is the kind of detail that separates a fast loop from a subtly
different one; noted with approval. Accepted; the scope-widening
rescan follow-up (210 ms of re-parsing open buffers) is the next
round.
**2026-08-27 — lead, indexed-navigation performance round (external dev:
codex).** Reviewed the full diff line-by-line and ran all three gates
independently (fmt clean, clippy silent, 1155 server tests + workspace
+606
View File
@@ -0,0 +1,606 @@
# scan-interleave
## Goal
`Server::new` ran the whole startup scan before `run()`'s message loop took its
first message, so everything a client sent the instant the handshake was done
sat in the OS pipe until the scan was over: **780 ms cold store / 287 ms warm**
over a 200-file workspace, against 26–64 µs for the same hover once the scan
had finished (filed as "suspect 2" in
`docs/features/hover-line-index/README.md`, and the larger half of the owner's
"hover is really slow on first try"). This round takes the scan apart into
per-file steps and drains the message queue between them, so a scan long enough
for a person to notice answers questions while it runs. The first hover of a
session now comes back in **15.5 ms cold / 12.8 ms warm** on the same fixture —
a 50× and 22× improvement — and the scan's own total is unchanged inside
run-to-run noise.
## Assumptions
- **An answer given mid-scan reads the index as of that moment.** It is
scope-relative in *time* exactly the way every answer is already
scope-relative in *space* (`crates/lucisv_server/README.md`): a declaration in
a file the scan has not reached yet is a declaration this server does not know
about yet, and it says so by answering nothing rather than by making the
client wait. Which files that means depends on how far the scan got, so a
mid-scan answer is genuinely **not reproducible** — which is why the rule
below narrows the cases it can happen in to the one where it is worth it.
- **Only a scan nobody asked for answers mid-way.** The message loop has always
promised that everything queued *ahead* of a request is applied before that
request is answered. A `didOpen` that widened the scope, a `didSave`, a
changed setting or an added workspace folder ask for a rescan, and "applied"
for those means the rescan has **run** — one message at a time, the server
would have finished it before ever taking the request. So requests that arrive
during a rescan wait for it, and only the *startup* scan — which nothing was
queued ahead of — answers from a half-built index. See `Server::must_wait`.
- **And only a scan long enough to be worth it.** A scan of at most
`INTERLEAVE_ABOVE` (64) files is over in a few milliseconds and runs exactly as
it always did, one shot, no drains: trading a complete answer for those
milliseconds would be a bad bargain. A count rather than a clock, because a
rule about elapsed time makes what a server answers depend on how loaded the
machine is — which is a property neither a test suite nor a bug report can
work with.
- **The scan indexes the text each file had when its work list was taken.** A
`didOpen` or a `didChange` answered mid-scan changes the *buffer* and not the
index — exactly as it does when it lands a millisecond after the scan
finished, because neither notification touches the index (a save is what
does). So a message answered in the middle of a scan cannot move that scan's
result.
- **A record written through is a record kept.** A scan a `shutdown` interrupts
leaves every file it had already parsed in the persistent store, because the
store is appended to per file (`docs/features/index-persistence/README.md`).
That was already true of a scan a `kill` interrupted; it is now reachable
through the protocol as well.
## Handshakes
### `vlog_semantic` — `WorkspaceIndex::absorb`
```rust
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
/// many files at once — and for **one** merge rather than one each.
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]);
// generic in what rides beside the path, so an owning caller gets the same order
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)>;
```
`absorb` keeps the same promise `update_facts` does — what comes out is the
index a full `build` over the records it now holds would have produced — and for
the same structural reason: the records stay path-sorted and one file to a path,
and `merge` is then the loop `IndexBuilder::finish` runs over the same list. It
exists because **a merge is a pass over every record the index holds**, which is
measured below and is the difference between a linear scan and a quadratic one.
`index_order`'s lifetime parameter became a type parameter. Every existing
caller passes `&str` and is unchanged; the scan passes `String`, because it owns
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 */ }
impl Scan {
pub fn skipped(&self) -> usize;
pub fn cached(&self) -> usize;
pub fn total(&self) -> usize;
pub fn index_next(&mut self, path: &Path) -> bool;
}
impl Workspace {
pub fn adopt_roots(&mut self, roots: Vec<PathBuf>);
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Scan;
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool;
pub fn publish_scan(&mut self, scan: &mut Scan);
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String>;
}
```
**A value rather than a loop, because a callback cannot be handed the workspace
it is called from.** `rebuild_index_with` held `&mut self` for the whole scan,
so its watcher callback could reach the connection (a disjoint field) but never
the workspace — and answering a message needs exactly that. Splitting the loop
puts the scan's state somewhere the server can own it, and `rebuild_index_with`
is now literally
```rust
let mut scan = self.begin_scan(watch);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
```
so "one shot" and "interleaved" are not two scans that have to be kept in step:
they are this loop with and without a drain in it. That is what makes the
fingerprint equivalence structural rather than tested-and-hoped.
`skipped`/`cached` moved from `IndexWatch` to `Scan`: they are facts about the
scan, and `IndexWatch` is now purely the thing that speaks protocol.
`open_roots_with` and `rebuild_index_with` are `#[cfg(test)]` now — the server
drives the three calls itself, and every test that just wants an index still
calls the one-shot form.
### `lucisv_server::candidates`, `::includes` — the batch forms
```rust
impl Candidates {
pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec<String>)>);
}
impl IncludeGraph {
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]);
}
```
Both are the batch form of the incremental update each already had
(`update_words`, `update_file`), doing the whole-table half once for the batch
instead of once per file. **All three tables are published together, never one
of them**: an index that had seen a scanned file while a completion or an
include link could not would make "the workspace as far as it has been scanned"
three different things at once.
`candidates::words_in` became `pub(crate)`, because a scan lexes each file's
completion words as it reaches it rather than in one pass at the end. That moves
work rather than adding it — `Candidates::build` at the end of the scan now
finds every file's words already in hand and lexes nothing — and it is what
keeps the *tail* of a scan from being an unbroken block longer than one file.
### `docs/features/hover-line-index` — suspect 2, **DELIVERED**
That round measured the wait, filed it as a request to "whoever owns the message
loop next" and named the probe. This is that round; the probe is flipped and
renamed (`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`)
and its before-numbers are the ones in the table below.
## Measured
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
`--release`, `#[ignore]`d probes, `--test-threads=1`. Taken 2026-08-28, before
and after, in the same session.
### The merge cost, measured before the design was chosen
`perf::publishing_a_half_built_index_mid_scan`, files of 1 000 lines:
| workspace | one file's parse | one whole merge | one `update_facts` | per-file feeding would cost | against parsing |
|---|---:|---:|---:|---:|---:|
| 50 files | 2.35 ms | 0.73 ms | 0.66 ms | 32.8 ms | 117.6 ms |
| 200 files | 2.32 ms | 3.35 ms | 3.15 ms | **630.7 ms** | 464.4 ms |
| 800 files | 2.23 ms | 15.90 ms | 14.66 ms | **11.73 s** | 1.78 s |
**So: not per file.** A merge is linear in the whole workspace, so feeding the
live index one file at a time is quadratic — at 200 files it would have *more
than doubled* the scan, and at 800 files multiplied it by seven. The decision
the numbers make is **deferred**: records are staged as they are taken and
folded in with one `absorb` per *drain*, and a drain only happens when the queue
is not empty. A scan nobody is waiting on therefore pays nothing beyond one
`try_recv` per file, and a scan somebody is waiting on pays 3.35 ms per burst at
200 files — one and a half files' worth of parse.
### The latency the round is about
`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`, 200 files
of 1 000 lines with a filelist, over the wire against the real binary:
| the first hover of a session | before | after |
|---|---:|---:|
| issued the moment `initialized` was sent, cold store | 780 ms | **15.5 ms** |
| — warm store | 287 ms | **12.8 ms** |
| the same hover once the scan is done | 64 / 61 µs | 191 / 151 µs |
Two honest caveats on that table. The "after" figures move with how busy the
machine is — a second run minutes later, with the corpus suite running beside
it, reported 19.8 ms and 14.0 ms — so read them as *tens of milliseconds
against hundreds*, which is the claim, and not as three significant figures.
And the last row is the same answer either way, measured differently now: the
"after" run waits for the progress bar to come down before asking, which is
what makes it a *post*-scan measurement rather than a race with the scan. Both
are microseconds and neither is what the round moved.
### What the scan's total cost
`state::tests::qa_perf_cold_warm_and_half_warm_scans`, the 860-file corpus,
before and after on the same machine minutes apart:
| | before | after |
|---|---:|---:|
| no cache | 321.5 ms | 322.0 ms |
| cold, filling the store | 351.3 ms | 353.4 ms |
| warm, every file from the store | 187.0 ms | 188.6 ms |
| the store | 2 380 790 B | 2 380 790 B |
**+0.2 % / +0.6 % / +0.9 %**, which is well under the "a few percent" this
round was allowed — and inside the run-to-run band, which is worth stating with
a number of its own: the same "after" measurement taken again on a busier
machine reported 357 / 375 / 201 ms, so the pair above is only meaningful
*because* it was taken minutes apart in one session on one tree. Nothing was added to the
per-file path; the completion word lex moved into it from the tail, and the
index is folded in with the same number of merges a one-shot scan always did
(one) when nothing is waiting.
### The floor under a mid-scan answer
`perf::what_a_scan_does_before_its_first_file`, 200 files of 1 000 lines:
| | quiet machine | busy machine |
|---|---:|---:|
| before the first file (resolve the scope, read every file, open the store) | 6.9 ms | 9.8 ms |
| one file | 4.0 ms | 5.7 ms |
| the other 199 | 682 ms | 723 ms |
| finishing (last merge, completion tables, include graph, overlays) | 10.7 ms | 10.9 ms |
So the 15.5 ms above is the first two rows plus the handshake and the message's
own travel, and it is **not** the "single digit ms" the brief hoped for. The
first row is one block no drain can break up, and reading the files lazily is
what would break it up — filed as a deliberate not-done below with this number
attached.
## Status / TODO
- [x] Measure the merge cost before choosing a rhythm; per-file feeding
rejected on the numbers above, deferred-and-batched chosen.
- [x] `WorkspaceIndex::absorb`, with the fresh-build equivalence tested three
ways (a batch of every shape, one batch against the same records in
pieces, and an empty batch).
- [x] `Scan` + `begin_scan`/`scan_step`/`publish_scan`/`finish_scan`, with
`rebuild_index_with` rewritten as the loop over them.
- [x] The server drives the scan and drains the queue between files; the
queue moved onto `Server` so a scan and `run` share it.
- [x] Order preserved: `Server::must_wait` holds a request (and everything
behind it) that is queued behind a rescan, and `run` answers what was
held before it takes anything newer — keeping its place among messages
the rescan itself held, and carrying its `$/cancelRequest` with it.
- [x] Coalescing: a rescan asked for mid-scan is a flag, and
`scan_until_settled` is a loop — never a scan inside a scan.
- [x] Shutdown mid-scan stops the scan where it stands and `run` returns
without taking another message.
- [x] The completion tables and the include graph are published with the
index, so a mid-scan answer is one generation and not three.
- [x] A file opened mid-scan is indexed next (`Scan::index_next`).
- [x] The startup scan republishes and refreshes lenses when a buffer was
opened during it — a debt that did not exist before this round.
- [x] The e2e probe flipped and renamed; the before-numbers kept above.
- [x] `cargo fmt` / `cargo clippy --all-targets --workspace` / `cargo test
--workspace` / `node editors/vscode/smoke.js`.
- [ ] **Not done, deliberately: the files are still read eagerly.** The 6.9 ms
before the first file is mostly 200 `read_to_string`s. Reading each file
in `scan_step` instead would take the mid-scan floor to single digits,
and it costs a work list of `Option<String>` and a decision about what a
file that turns out to be unreadable does to the progress bar's `total`
(today such a file never joins the work list at all, because the read
that fails happens before the list is taken). Worth doing; not worth
guessing at inside a round that is already changing when answers happen.
- [ ] **Not done, deliberately: a scan of a few very large files still
blocks.** `INTERLEAVE_ABOVE` counts files, and 20 netlist-shaped files
can take a second. A second rule on elapsed time would catch it and would
make what the server answers depend on machine load; the honest fix is a
cost estimate from the sizes the cap already reads (`oversize` does a
`metadata` call per walked file), which is a design, not a patch.
- [ ] **Not done, deliberately: a rescan still makes requests wait.** The
brief named later rescans as blocking the loop the same way, and they
still block *requests* — notifications, cancels and responses are
processed throughout. Answering a request from a half-updated index would
break the order contract the loop has always kept, and no measurement
says a rescan is where the pain is: the owner's report is about the first
request of a session.
## Work log
### 2026-08-28 — dev
**Measured the merge first, and the number chose the design.** The brief left
per-file / chunked / deferred open and asked for numbers. `update_facts` on an
already-held file is 3.15 ms at 200 files and 14.7 ms at 800, because
`merge_references` re-resolves every reference in the workspace; one per file is
630 ms and 11.7 s of pure merging. The rhythm that survives is **stage per
file, fold in per drain, and drain only when something is waiting** — which
makes the cost of interleaving zero for a scan nobody is waiting on and one
merge per burst for a scan somebody is. There is no chunk size to tune, which
is the nicest property of it: the client's own traffic sets the rhythm.
**The scan had to become a value before it could be interrupted.** The
blocker was borrowing, not design: `rebuild_index_with(&mut self)` holds the
workspace for the whole scan, and a message answered from inside it needs that
same workspace. `Scan` owns the work list and the staged records, so
`scan_step(&mut self, scan: &mut Scan)` borrows two separate things and the
server can put whatever it likes between two calls. `rebuild_index_with` is now
three lines over the same three methods, which is what makes "the interleaved
scan is the one-shot scan with a drain in it" a fact about the code rather than
a claim in a document.
**The hard part was not latency, it was the order contract.** The first
working version answered requests mid-scan unconditionally, and sixteen e2e
tests began failing *intermittently* — which is the real finding, not the
failures. Those sessions pipeline a whole conversation into the pipe
(`initialize`, `initialized`, a `didOpen` that widens the scope, three
requests, `shutdown`), so whether a request saw a finished index depended on
whether the forwarder thread got scheduled before the scan ended. Three
decisions came out of that:
1. **`must_wait`.** A request queued behind a message that asked for a rescan
waits for that rescan, because that is what one message at a time would have
done, and once one request is waiting every later one waits too. Held
messages keep their arrival order and are answered by `run` before it takes
anything newer. `shutdown` waits with them: a request sent before a shutdown
is a request the client is still owed an answer to.
2. **Only the startup scan answers mid-way.** A scan a *message* asked for has
that message queued ahead of everything else, so nothing arriving during it
may be answered from a half-updated index. The startup scan has nothing
queued ahead of it, and it is the one the owner's report is about.
3. **`INTERLEAVE_ABOVE`.** Even the startup scan should not trade a complete
answer for milliseconds. Sixty-four files is the line: below it the scan runs
exactly as it always did, which is also why the whole existing suite passes
unmodified — every fixture in it is a handful of files. A count and not a
clock, so that what the server answers never depends on how busy the machine
was.
**All three tables, or none.** After `must_wait` there were still failures
where a macro hover and an include link came back empty mid-scan: the index was
being published but `Candidates` and `IncludeGraph` were still built whole at
the end. Publishing one of three tables makes "as far as the scan has got" mean
three different things at once, so both grew a batch `absorb` and all three are
folded in together. The include graph's known-file table is relearned from the
scan's **whole work list** rather than the files it has reached, because which
files *exist* is settled the moment the scope is resolved and only the edges are
discovered file by file.
**Coalescing: finish, then rescan again — not abort and restart.** A message
answered mid-scan sets `rescan_wanted`; `scan_until_settled` is a loop that
scans again while the flag is set, and `reindex`/`reindex_one` set the flag
instead of running when `scanning`. Finishing was chosen over aborting because
it needs no way to unwind a half-published index and cannot loop forever: the
follow-up scan reads the persistent store for every file the abandoned one had
already parsed. Each scan keeps its own progress token, which is what a client
showing a bar expects of two scans. `reindex_one` returns `true` when it defers,
because its caller's fallback is "rebuild the whole thing right now", which is
precisely what must not happen.
**Two debts this round created and paid.** A buffer can now be *opened* during
the startup scan, so `Server::started` owes what `reindex` has always owed at
the end of a scan — a code-lens refresh, a generation bump and a republish —
and pays it when any buffer is open (which is nothing at all for a session
whose client did not get a `didOpen` in edgeways). And `reindex_one` can no
longer patch one file mid-scan without the scan overwriting it with older bytes
a moment later, so it defers too.
**A test seam, named as one.** `Server::started` grew a `queued: Vec<Message>`
parameter — what the client had already sent when the server was built, put
straight onto the queue the startup scan drains. `Server::new` passes an empty
one. The alternative was for the test to send on the client end and race the
forwarder thread for it, which made the first version of
`a_request_the_client_had_already_sent_is_answered_during_the_startup_scan`
pass alone and fail under a loaded suite. A coin-toss test is worse than no
test.
**Files touched.** `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/{server.rs,state.rs,candidates.rs,includes.rs,perf.rs}`,
`crates/lucisv_server/tests/e2e.rs`, this README,
`docs/features/hover-line-index/README.md`, `docs/perf/README.md`, `TODO.md`.
No new dependency, no `unsafe`, no `#[allow]`, no version bump, no commits.
Single-threaded throughout: the only thread this round touches is the message
forwarder, which existed already and still only moves messages.
**Tests added** (14).
| test | where | pins |
|---|---|---|
| `absorbing_a_batch_gives_the_index_a_whole_build_would_have` | `vlog_semantic/tests/workspace.rs` | the house witness for the new entry point: a file replaced, two added (one sorting first, so every id moves), one dropped |
| `absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index` | same | what makes a publish free of consequence — how records are grouped into batches cannot reach the result |
| `absorbing_nothing_changes_nothing` | same | the empty publish and the empty finish |
| `publishing_between_every_file_leaves_what_a_one_shot_scan_leaves` | `lucisv_server/src/state.rs` | the round's central invariant, over index **and** completion tables **and** include graph, publishing after every single file |
| `a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope` | same | a publish only folds records *in*, so the removal a rescan owes has to survive every publish before it |
| `a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes` | same | fingerprint equality with a `didChange` injected mid-scan |
| `a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell` | same | `Scan::index_next` moves it, does not move it twice, refuses a file not waiting — and the finished index is byte-identical |
| `a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven` | same | progress and log continuity: interleaving adds drains between events, never events |
| `a_request_the_client_had_already_sent_is_answered_during_the_startup_scan` | `lucisv_server/src/server.rs` | the point of the round, over the real dispatch: the response goes out before the bar comes down |
| `a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself` | same | the other side of `INTERLEAVE_ABOVE` |
| `a_request_queued_behind_a_rescan_waits_for_that_rescan` | same | the order contract: the request sees the index the push asked for, not the one it was sent into |
| `a_held_request_keeps_its_place_and_takes_its_cancel_with_it` | same | the two corners holding creates: a burst's own request stays in front of one the scan it started held later, and a cancel consumed on the way in goes back with what it cancels |
| `a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan` | same | three settings pushes inside one scan cost one more scan, two bars, two tokens, no nesting |
| `a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands` | same | the bar never comes down, the index is short, `run` returns at once |
Two `#[ignore]`d probes added
(`perf::publishing_a_half_built_index_mid_scan`,
`perf::what_a_scan_does_before_its_first_file`); one existing probe flipped and
renamed (`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` →
`..._is_answered_during_it`), which is the before/after pair this README's
latency table is read from.
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` silent. `cargo test --workspace` green, 0 failed:
`lucisv_server`'s unit tests **1 225 passed / 26 ignored** (+11 tests, +2
`#[ignore]`d probes), its `e2e` suite **56 passed / 2 ignored** (unmodified
except the flipped probe), `vlog_semantic`'s `workspace` suite **70 passed**
(+3). `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
## QA log
### 2026-08-28 — QA
Read `CLAUDE.md`, the dev brief, and this README's Handshakes/Work log before
attacking. Traced `process_batch`'s held-message splice, `must_wait`,
`scan_until_settled`/`scan_once`/`answer_what_is_waiting`, `Scan`, and
`WorkspaceIndex::absorb` line by line against the charter's five attack
classes, then exercised the parts a trace alone couldn't settle. Two real
findings, both narrow; one confirmed-correct-but-untested behavior now pinned;
gates and numbers reproduced.
**Finding 1 (low, doc-contract) — `WorkspaceIndex::absorb` does not dedupe a
duplicate path in one batch the way `WorkspaceIndex::build` does.**
`crates/vlog_semantic/src/workspace.rs:472-489` (`absorb`). `build` goes
through `index_order`, which keeps the *first* of a duplicate path
(`Vec::dedup_by`'s contract, `crates/vlog_semantic/src/workspace.rs:1034`).
`absorb`'s own loop walks `records` left to right and overwrites on a
`binary_search` hit, keeping the *last*. `absorb`'s doc comment claims "what
comes out is the index a full build over the records it now holds would have
produced" — that equivalence does not hold for a batch with a duplicate path.
Not reachable through the scan that actually feeds `absorb` today: `Scan::work`
is built from `index_order` before the scan starts, so it can never contain two
entries for the same path, and `scan_step` therefore never stages a duplicate.
But `absorb` is `pub` on `WorkspaceIndex`, its doc comment states the
equivalence unconditionally, and a future caller (or a future change to how
`Scan::work` is assembled) could reintroduce the gap silently. Repro and
permanent regression test added and passing:
`crates/vlog_semantic/tests/workspace.rs`,
`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`
— builds `[("a.sv", module first_shape), ("a.sv", package second_shape)]` both
ways and asserts the fingerprints differ, then pins which one `absorb` actually
keeps (the last). Not fixed here — whether `absorb` should match `build`'s
first-wins or the doc comment should be narrowed to describe last-wins is a
design call, not a QA fix. Verified harmless in production as things stand
today, precisely because the scan can't construct the input that trips it.
**Finding 2 (very low, stale doc comment) — `refresh_code_lenses`'s doc comment
contradicts what this round now does.**
`crates/lucisv_server/src/server.rs:1979-1984`: "Nothing is sent at startup
either: no buffer is open there, so there are no lenses to invalidate." That
was true before this round; `Server::started` now calls exactly this method at
the end of construction whenever a `didOpen` answered mid-scan left a buffer
open (`crates/lucisv_server/src/server.rs:347-354`), and the new test below
confirms it fires. The comment should say client-refresh-capable + a buffer
open, no longer "never at startup." Not fixed here per QA's remit not to edit
outside the change's own tests, but it is a one-line fix the dev should make in
the same file the round already touched.
**Verified correct, previously untested — the two-publish behavior for a file
opened mid-startup-scan.** Traced through `Server::started`'s new "pay the
`reindex` debt" block and found it produces *two* `publishDiagnostics` for the
file a mid-scan `didOpen` opens: one from `didOpen`'s own always-existing
handler (against the half-built index, mid-scan — correct, not new), and one
from the debt-payment block after the bar comes down (against the finished
index — the new behavior). That is correct, not a duplicate-publish bug, but
it was unverified by any test in the round's own "Tests added" table. Added
`crates/lucisv_server/src/server.rs`,
`a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once`:
asserts exactly two publishes for the opened file, the first before the `end`
progress event and the second after it, and exactly one `workspace/codeLens/refresh`
(also after `end`, implicitly, since it can only fire once open_uris is
non-empty at the end of construction). Passes.
**Also added, no bug found — `INTERLEAVE_ABOVE` exact-boundary test.** The
charter asked for the 64/65 edge explicitly; the round's own tests exercise
`INTERLEAVE_ABOVE + 6` and `4`, neither of which pins the `>` vs `>=` choice in
`scan_once`. Added
`crates/lucisv_server/src/server.rs`,
`interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after`: a
scan of exactly 64 files answers nothing mid-construction (one-shot), a scan of
65 answers before the bar comes down (interleaved). Passes as written — no
off-by-one found, now locked in.
**Attacks traced and found sound, not turned into new tests (existing coverage
or structurally excluded):**
- *Order-contract, cancel-through-a-wait*: traced `process_batch`'s
`consumed_cancels` splice by hand against
`a_held_request_keeps_its_place_and_takes_its_cancel_with_it`
(`crates/lucisv_server/src/server.rs:2985`-ish) with a constructed batch
where a cancel's target is answered *before* the wait point is reached — the
stale cancel does get re-queued into `held`, but `cancelled_in` re-filters by
the ids actually present in the replayed batch, so it is inert on replay,
never mis-cancels an unrelated request. Not a bug; not worth a dedicated
test since it changes nothing observable.
- *Gone-file races during a scan that also answers mid-way*: `finish_scan`
defers the `gone` computation to one `absorb` call at the very end, so a
file leaving scope is not removed from the live index until the scan
finishes. This only matters if a mid-scan answer could see a file that
should already be gone — and every scan capable of having `gone` files
non-empty is a *rescan* (`answering_a_rescan = true`), which `must_wait`
already blocks from answering anything mid-way. The startup scan (the only
one that answers mid-way) always starts from an empty index, so it can never
have a `gone` file. Structural, not incidental — traced through
`scan_until_settled`'s `asked_for` threading, not tested further.
- *Include graph's `known` set includes not-yet-scanned files mid-scan*:
intentional per the Handshakes section ("which files exist is settled the
moment the scope is resolved"); this can make an `` `include `` targeting an
unscanned file resolve to a path with no edges of its own yet, which is the
same "not there yet" story the index already tells for symbols. Not a
divergence from the round's own stated contract.
- *Shutdown delivered twice (queue-injection copy + forwarder-relayed copy) in
`a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands`*: the test
deliberately sends the same logical `shutdown` through two paths and says so
in its own comment ("whichever of the two ... the scan stops here"). Traced
the `forward`/`handle_shutdown` interaction and confirmed the real `exit`
notification can never be stolen by the forwarder (it stops at the first
shutdown it relays and never reads again), so the raciness is a test-harness
artifact for reaching the scenario at all, not a client-facing bug. Ran the
test 20x in a loop (`cargo test ... -- --test-threads=1`, repeated) with no
flake.
**Gates.** `cargo fmt --all -- --check` clean (after formatting the one test I
added that needed it). `cargo clippy --all-targets --workspace` silent.
`cargo test --workspace` run 3x after all QA additions: **0 failures each run,
2457 total passed each run**, identical every time. One transient failure seen
*before* the final 3-run check
(`large::tests::references_on_one_giant_line_locate_their_hits_in_linear_time`,
a pre-existing wall-clock perf gate unrelated to any file this round touches)
under self-inflicted contention (I had a background `cargo test` and a 3-run
loop racing on the same machine at once); reproduced clean on both master
(pre-round, 3/3) and this round's tree (3/3) once run without that
contention — not a regression, not flagged further.
`node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
**Numbers reproduced**, same machine, `--release`, `--test-threads=1`:
- `e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`: 16.1 ms
cold / 14.0 ms warm (README claims 15.5 / 12.8, and says a rerun elsewhere
saw 19.8 / 14.0 — this sits inside that band).
- `perf::publishing_a_half_built_index_mid_scan`, all three sizes including
800 (not skipped — it ran in 5.4s, not slow): 200-file whole merge 3.85 ms
(claimed 3.35 ms), 800-file per-file-feeding-would-cost 12.9 s (claimed
11.7 s) against 2.06 s of parsing (claimed 1.78 s) — same shape, same
conclusion (deferred-batched, not per-file), numbers within normal
machine-to-machine variance.
- `state::tests::qa_perf_cold_warm_and_half_warm_scans`: no-cache 347 ms /
cold 387 ms / warm 203 ms (claimed 322/353/189) — store size **exactly**
2 380 790 bytes, matching the README bit for bit, which is the number that
actually matters (deterministic index size, unaffected by machine noise).
**Verdict: SHIP.** No masked-corruption, no order-contract violation, no
non-settling loop found across five attack classes and direct code tracing.
Two findings filed above are both low severity, both narrow (one is
structurally unreachable through the round's own code paths today, the other
is a one-line stale comment), and neither touches the hard invariants
(never-corrupt, idempotent, comments-preserved) or the round's own claimed
equivalences in the paths actually exercised. Three regression tests added,
all passing, all documenting real (if narrow) findings or previously-untested
correct behavior — none required a design change.
## Review
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
independently (fmt clean, clippy silent, 2457 workspace tests green,
QA ran the suite ×3 with identical results). This was the riskiest
round of the wave — interleaving is where order contracts go to die —
and the two rules that survived the dev's own 16-test intermittent
failure (`must_wait`, so only the startup scan answers mid-way; and
`INTERLEAVE_ABOVE` as a count, not a clock) are the reason the whole
existing suite passes unmodified and deterministic. The measure-first
discipline paid again: per-file merging looked obvious and would have
been quadratic (11.7 s over 800 files); one absorb per non-empty-queue
drain costs the idle scan a `try_recv` per file and nothing else. The
structural fingerprint argument — one-shot and interleaved are
literally the same three-line loop over `Scan` — is the strongest
equivalence guarantee of the wave. First hover of a session:
780 → 15.5 ms cold, 287 → 12.8 ms warm, scan totals inside noise; the
remaining 6.9 ms of eager pre-scan reads is measured and filed, not
hidden. QA's two low findings were the lead's to settle and are fixed
in this commit: `absorb`'s doc now states the distinct-paths
precondition and why last-wins is the right update semantic (behavior
unchanged — the one production caller feeds deduped work, and QA's
divergence test pins the edge), and `refresh_code_lenses`' comment
caught up with `started`. The double-publish for a buffer opened
mid-scan (half-built answer, then finished answer) is correct by the
scope-relative-in-time doctrine and now pinned. Accepted; committed by
the lead.
+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.)_
+37 -1
View File
@@ -41,10 +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
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 }
@@ -275,6 +289,15 @@ unchanged by where the span comes from. Nothing here needs revisiting when
order in every returned slice, regardless of iteration order.
- `Def.name_span` is a non-empty byte range in `Def.file` that slices back to
exactly the name that was looked up (asserted over the whole corpus).
- `Def.lines` (2026-08-28, `docs/features/hover-line-index/README.md`) is the
1-based line each of those spans falls on, read off the same text the span
was read from, in the same pass. It is what lets a consumer print
`file:line` for an indexed declaration with no file access at all. **A line
is not text**: the index still keeps no file contents, exactly as it keeps
no contents for the spans it has always held. The field is a struct rather
than a bare number so richer per-declaration position data extends it by
gaining a field — members are `Decl`s like units are, so a module's ports
already carry their own lines here.
- `resolve_external` does not mutate `Semantics` and holds no borrow of the
index in its result.
@@ -424,6 +447,19 @@ and more than half of all external candidates answered on clean files.
## Work log
**2026-08-28 — declaration lines** (`docs/features/hover-line-index/README.md`).
`Def` and the per-file `Decl` gained `lines: DeclLines { name, detail }`, the
1-based source lines of `name_span` and of `detail_span`, computed in
`facts_from_analysis` from a `LineIndex` over the file being indexed.
`FileFacts::from_analysis` takes that index as a parameter (its one real caller
already holds one); `FileFacts::of` builds its own. The record format grew two
fields per declaration and `FACTS_FORMAT` went **3 → 4**.
`WorkspaceIndex::fingerprint`'s `sym` line carries the lines, so the
incremental-equals-fresh witness covers them — every existing equivalence test
stayed green unmodified. Cost, measured over the corpus: the whole scan is
unchanged inside its noise (one `LineIndex::new` per parsed file, under 1 % of
that file's parse) and the persistent store grows 68 KB over 860 files, 2.9 %.
**2026-08-27 — indexed navigation.** `FileFacts` gained compact local and
external reference records and its persisted format moved to version 2.
`WorkspaceIndex` resolves them into reverse postings after declaration tables
+1049
View File
File diff suppressed because it is too large. Load diff
+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
+92
View File
@@ -5,6 +5,98 @@ 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.
- **The first hover of a session answers in ~15 ms**, not hundreds —
the server now answers requests while the workspace scan is still
running, with your open file indexed first.
- **Repeat hovers into closed files are ~1 µs.** Declaration line
numbers live in the index (a few KB even for tens of thousands of
modules, ports included), and a closed file's text is read once and
cached, not re-read per hover.
- **One-time index rebuild** on first open after updating — the index
format gained the line numbers.
## 0.13.1 — 2026-08-28
The F12-latency release.
- **Find References with a huge file open is ~30× faster** (3.2 ms →
0.11 ms on a 70 000-reference buffer), and in-file references and
occurrence highlighting on heavily used signals are ~40 % faster.
- **Jumping into a new folder is ~10× faster.** The index rescan that a
scope-widening jump triggers now reuses what your open buffers already
analyzed instead of re-parsing them: ~228 ms → ~23 ms with a 1.4 MB
file open.
- **Pathologically nested files can no longer crash the tools.** ~500
nested `begin`/`end` (or `case`, `fork`, generate…) blocks now produce
an ordinary "nesting too deep" diagnostic on every platform, including
Windows, instead of risking an abort.
## 0.13.0 — 2026-08-28
- **Typing no longer reanalyzes on every keystroke.** The buffer's analysis is
deferred to the first moment anything needs it, so a burst of typing costs
one reanalysis instead of one per key. Half-typed lines stop flashing
squiggles that vanish a keystroke later. In a 10 000-line file a keystroke
now round-trips in 37.6 ms.
- **Old-style ports hover properly.** A port named in the module header and
completed in the body (`input signed [31:0] data_in;`) now shows both
places on one card — the header line and the declaration carrying its
direction, type and width — with the comments that document each of them.
Go-to-definition offers both, body declaration first. Works across files,
and for old-style task and function arguments too.
- **Faster hover and cursor answers.** Hovering into a closed file reads it
once instead of twice, and expand-selection, on-type formatting, completion
and inline templates find the token at your cursor by binary search rather
than by scanning the file. No answer changed.
- The index cache's format changed, so the first session after upgrading
rebuilds it.
## 0.12.1 — 2026-08-27
- **Hover shows the declaration itself.** Hovering a name declared in another
+55 -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.12.1**. 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,55 @@ 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:
- Hover on instantiations and ports is now fast on the *first* try: the
server answers during the startup scan (~15 ms instead of waiting
hundreds), declaration lines live in the index, and closed files are
read once, then cached.
- The index cache format changed: the first open after updating
re-scans once, then persistent caching resumes.
## Release 0.13.1 highlights
Version 0.13.1 is the F12-latency release:
- Find References with a big file open answers in ~0.1 ms where it took
milliseconds, and jumping into a not-yet-indexed folder costs ~23 ms
where it took ~228 ms — the rescan reuses what open buffers already
analyzed.
- Deeply nested files produce a "nesting too deep" diagnostic instead of
ever crashing the server or CLI, on every platform.
## Release 0.13.0 highlights
Version 0.13.0 is the responsiveness release. Typing no longer reanalyzes the
buffer on every keystroke — the analysis is deferred to the first moment
anything needs it, so a burst of typing costs one reanalysis instead of one
per key, and half-typed lines stop flashing squiggles that vanish a moment
later. Cursor-position answers — expand selection, on-type formatting,
completion, inline templates — binary-search for the token under your cursor
instead of scanning the file.
Hover also learned old-style ports: a port named in the module header and
completed in the body (`input signed [31:0] data_in;`) shows both places on
one card, with the comments that document each of them.
## Release 0.12.1 highlights
Version 0.12.1 makes hover answer the question directly: a cross-file name
+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.12.1",
"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
+672
View File
@@ -0,0 +1,672 @@
# topo.md — the dependency topology of lucisv
**Purpose.** This document is the map an agent reads before touching anything:
which modules depend on which, which features consume which, and where the
two graphs meet. It exists to make parallel multi-agent development safe —
every edge below is an interface somebody can break, and every *absent* edge
is a place two agents can work at the same time without talking.
Sources of truth this document is derived from (and defers to on conflict):
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); 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:**
| notation | meaning |
|---|---|
| `A ──▶ B` | **A depends solely on B.** A consumes B's published interface; B was not changed for A and does not know A exists. Breaking B's interface breaks A; breaking A costs B nothing. |
| `A ◀──▶ B` | **Handshake.** A negotiated, two-sided contract: B changed something *for* A (or both sides pin one wire shape / file format / naming convention), and the contract is written down in one or both READMEs. Either side moving unilaterally breaks the other. |
| `A ─▶ B` | **Not a dependency** — a one-way note whose `kind` column says what it is: `sequencing` (corpus files handed from one bucket to the next), `standing promise` (A imposes a rule on B and its successors), `open request`, or `depends (consumed by)` — the last reads **B depends on A**. |
| *(absent)* | The two are independent. Independent pairs are **not listed** — their absence is the claim. |
A handshake that was **requested but not yet delivered** is an *open
handshake*; those are collected in §2.9 because they are exactly the
coordination points parallel agents must not both grab.
---
## 1. Module dependency graph
"Module" here means: the eight workspace crates, the two editor trees, and
the script layer (`tools/`, `scripts/`, CI). Intra-crate structure that
matters for parallel work is in §1.3.
### 1.1 Crate-level graph
```mermaid
graph TD
subgraph foundations [foundation crates — depend on nothing]
P[vlog_parser]
C[lucisv_core]
end
F[vlog_formatter] --> P
S[vlog_semantic] --> P
L[vlog_linter] --> P
L --> S
R[vlog_refactor] --> P
R --> S
CLI[lucisv &#40;CLI&#41;] --> C
CLI --> P
CLI --> F
CLI --> L
SRV[lucisv_server] --> C
SRV --> P
SRV --> S
SRV --> R
SRV --> F
SRV --> L
L -.dev-dep &#40;fix harness&#41;.-> F
VSC[editors/vscode] -.spawn contract.-> SRV
VSC -.KEYWORDS grammar lock.-> P
NVIM[editors/nvim &#40;docs&#41;] -.spawn contract.-> SRV
TOOLS[tools/ release scripts] -.builds/packages.-> CLI
TOOLS -.builds/packages.-> SRV
TOOLS -.builds/packages.-> VSC
CI[Gitea Actions] --> TOOLS
CORPUS[scripts/ + tools/corpus_*] -.exit codes, msg prefixes.-> CLI
```
*(The diagram shows direction only; §1.2 is authoritative on `depends` vs
`handshake` for each edge.)*
External dependencies (all exactly pinned in the workspace `Cargo.toml`):
`rayon` (CLI only, sanctioned by TODO §3), `lsp-server` + `lsp-types` +
`serde`/`serde_json` (server only, sanctioned by TODO §6). Those are the only
**direct** external dependencies; everything the workspace itself writes is
std (they pull in ~20 transitive crates — see `Cargo.lock` — which is what an
audit counts, not what an agent can call). `lsp-types` carries
`features = ["proposed"]` for LSP 3.18 `inlineCompletion` (inline-templates).
### 1.2 Crate edges, documented
Every edge is directional; "consumes" lists the load-bearing surface, i.e.
what a change on the pointed-to side must not silently break.
| edge | kind | contract |
|---|---|---|
| `vlog_formatter ──▶ vlog_parser` | depends | `parse(tokens, source)` / `parse_source`, the whole AST, `tokenize` (re-used by `verify.rs` to re-lex both sides of the safety net), trivia attachment (`Meta::{leading,trailing,before_sep,attrs}` — comments are never dropped), `RawText.col` (the dedent column for verbatim re-indent), spans. The formatter is the AST's primary consumer: **every new `ItemKind`/`StmtKind`/`ExprKind` variant costs an arm in `format.rs`** (its matches are exhaustive). |
| `vlog_semantic ──▶ vlog_parser` | depends | The AST read-only, `parse_source_tolerant`/`parse_tolerant` (never fails; `Error` nodes are opaque leaves), the **name-span contract** `src[name_span] == name` on every declaring node, `token::is_keyword`, `defines::collect_defines`/`DefineTable`, `TextRange`. `bind.rs`'s `ItemKind`/`ExprKind`/`DimKind` matches are exhaustive — new variants cost an arm here too. |
| `vlog_linter ──▶ vlog_parser` | depends | `ParsedSource::parse` = `tokenize` + `parse_tolerant` (one-parse bundle), `LineIndex`, `TextRange`, AST shapes walked by `visit.rs` (which ends in `_ => {}`, so new variants usually cost nothing here), token facts for text rules (a macro use is one `Ident` token; a directive is one `Directive` token). |
| `vlog_linter ──▶ vlog_semantic` | depends | `analyze`, `Semantics::{symbols, references, references_of}` for the three semantic rules (`unused-signal`, `undriven-net`, `multiply-driven`). Lazy: a run with no semantic rule enabled never calls `analyze`. Justified in `vlog_linter/Cargo.toml`; adds no external code (`vlog_semantic` is `vlog_parser` + std). |
| `vlog_linter ──▶ vlog_formatter` **(dev-only)** | depends (tests) | The `.lint` fix harness asserts a lint fix never produces text `format_source` refuses. **The library dependency list is still `vlog_parser` + `vlog_semantic` + std** — `cargo tree -p vlog_linter -e normal` is the pinned check. Do not promote this to a normal dep; the fence filter deliberately lives in the front ends instead (see shared-fence-filter, §2.4). |
| `vlog_refactor ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant` + diagnostics, `LineIndex`, `TextRange`, the port/instantiation/module AST shapes, `token::is_keyword` (new-name validity), `defines` via the index. Every edit span originates in a parsed node — no textual search-and-replace. |
| `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). |
| `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 | `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), 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 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. |
| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `release.sh --cross`, `audit_artifacts.sh`, `prune_release_assets.sh`, `release_notes.sh`, `publish_release.sh` — so every release step runs by hand too; its only inline logic is the tag-vs-`lucisv --version` check. `ci.yml` is plain `cargo fmt`/`clippy`/`test` plus `scripts/corpus_gate.sh` (which reaches `tools/corpus_fetch.sh` on a cache miss). Tag `vX.Y.Z` must equal the workspace version; release notes come from `CHANGELOG.md`'s `## <version> — <date>` headings via `release_notes.sh`. |
| `scripts/score.sh + tools/corpus_check.sh ──▶ lucisv` | depends | The frozen 0/1/2 exit-code contract, plus a **textual** dependency on the message prefixes `parse error:` / `lex error:` / `verification failed:` (a standing fragile coupling — rewording those means telling corpus-check; see §2.9). |
**Deliberately absent crate edges** (independence you can rely on):
- `lucisv` (CLI) does **not** depend on `vlog_semantic` or `vlog_refactor` —
the CLI formats and lints; semantic lints reach it only *through*
`vlog_linter`, and refactoring is server-only today.
- `vlog_refactor` does **not** depend on `vlog_formatter` — refactored output
is edited source, not reformatted source (refactor README, by design).
- Among `vlog_formatter`, `vlog_semantic`, `vlog_refactor`, `vlog_linter`
there are exactly two build-time inter-crate edges — `vlog_linter →
vlog_semantic` and `vlog_refactor → vlog_semantic` — plus `vlog_linter →
vlog_formatter` as a **dev-dependency only**. All four depend on
`vlog_parser`. `vlog_formatter` is the isolated one: nothing in this group
depends on it at build time and it depends on none of them. Formatter work
and semantic work are parallel-safe except where both touch
`vlog_parser::ast`.
- `lucisv_core` depends on nothing and nothing in it knows about Verilog —
it is "which files, with what settings".
- `vlog_parser` depends on nothing. It is also the **highest-contention
module in the workspace**: six crates depend on it, five consume the AST
(the CLI takes only `LineIndex`/`TextRange`), and two of those match it
exhaustively — `vlog_formatter/src/format.rs` and `vlog_semantic/src/bind.rs`
— with `vlog_parser`'s own `tests/spans.rs` as a third exhaustive walker.
`vlog_linter`, `vlog_refactor` and `lucisv_server` walk it with catch-all
arms. See §3.3.
### 1.3 Intra-crate structure (what matters for parallel work)
**`vlog_parser`** — `lexer.rs` → `token.rs` (tokens + trivia attachment);
`parser.rs` (recursive descent, strict + tolerant entry points over one
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. `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);
`verify.rs` (the runtime safety net: token equivalence + convergence —
CLAUDE.md invariant #4 territory, see §3.3); `fence.rs` (format-off regions +
`protected_regions`, consumed by both front ends); `range.rs` (`--lines`);
`align.rs` (alignment inference). `format_source` = parse → format → verify;
an error means emit nothing.
**`vlog_semantic`** — `bind.rs` (AST → scopes/symbols/references) →
`model.rs`; `resolve.rs` (the lexical walk; misses become
`ExternalCandidate`/`InheritedCandidate` carrying candidate paths);
`scan.rs` (residual text-scanning for the one span the parser doesn't carry —
`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`,
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).
**`lucisv_core`** — `config.rs` (`lucisv.toml` parsing + `Discovery`, the
upward search with its per-instance cache), `walk.rs` (`collect_files`,
`EXTENSIONS`, `.gitignore`/`--exclude` filtering), `filelist.rs` (the `.f`
reader: files, `+incdir+`, defines, warnings), `cache.rs` (the format cache +
`content_hash` — the one FNV-1a the server's index cache also reuses). Knows
nothing of Verilog; depends on nothing; owns two open handshakes (§2.9-1,
§2.9-8).
**`vlog_linter`** — `registry.rs` (`Rule` trait, `all_rules`/`default_rules`/
`select_rules`), `rules/` (one file per rule; names are **stable API** — they
appear in users' waivers), `context.rs` (`LintContext<'a>`, `ParsedSource`,
lazy `semantics()`), `visit.rs` (the item/statement walk), `waiver.rs`,
`violation.rs` (+ `Fix`, `Applicability`), `signals.rs` (the shared signal
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`; 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
startup — **keep it that way**, cli-polish → parallel-files handshake),
`args.rs`, `diff.rs`, `lint.rs` (the `check` subcommand; owns the CLI-side
fence filter).
**`lucisv_server`** — layered, 40 files (`includes.rs` is the one file that
spans two layers — the include graph *and* the `documentLink` handler;
`perf.rs` is `#[cfg(test)]`-only and is not a layer — see
`docs/perf/README.md`):
| layer | files | role |
|---|---|---|
| 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), `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
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.
```mermaid
graph LR
subgraph FMT [formatter foundations]
direction TB
safety[safety-net] --- cmts[comment rounds] --- fences[format-fences] --- rangef[range-formatting]
end
subgraph GRAM [parser grammar / corpus]
direction TB
corpus[corpus-check] --- pspans[spans / name-spans] --- macro[macro-items] --- classes --- rest[...12 more buckets]
end
subgraph CLIL [CLI lane]
direction TB
polish[cli-polish] --- cfg[config-discovery] --- par[parallel-files] --- cache[format-cache]
end
subgraph LINT [linter lane]
direction TB
lcore[linter-core] --- lr2[lint-rules-2] --- slint[semantic-lints]
end
subgraph SEM [semantics & index]
direction TB
vsem[vlog-semantic] --- widx[workspace-index] --- incr[incremental-index] --- persist[index-persistence]
end
subgraph REF [refactor lane]
direction TB
flist[filelist M1] --- ren[refactor-rename M2] --- prt[refactor-ports M3] --- inst[refactor-instantiate M4]
end
subgraph LSP [LSP server lane]
direction TB
srv[lucisv-server] --- caps[~30 capability features]
end
subgraph PKG [packaging & release]
direction TB
epack[editor-packaging] --- pvsix[editor-platform-vsix] --- cirel[ci-release]
end
GRAM --> FMT
corpus -. measures .-> GRAM
LINT --> FMT
SEM --> GRAM
SEM --> CLIL
REF --> SEM
LSP --> SEM
LSP --> REF
LSP --> FMT
LSP --> LINT
LSP --> CLIL
CLIL --> FMT
PKG --> LSP
PKG --> CLIL
PKG --> GRAM
```
### 2.1 Formatter foundations
| edge | kind | contract |
|---|---|---|
| `case-tables ──▶ safety-net` | depends | The case harness consumes `format_source`'s post-safety-net `Err` — cases that used to produce wrong output now report `format failed:`. |
| `formatter-bug-fixes ◀──▶ safety-net` | handshake | safety-net *filed* the request (comments need positions to re-indent); formatter-bug-fixes *delivered* it: `Comment { line, col }`, `Token::trailing: Option<Comment>`, `RawText { text, col }`. |
| `formatter-bug-fixes ──▶ case-tables` | depends | Fixes the five bugs case-tables found and parked; each `#SKIP` case became a live regression case. |
| `format-fences ──▶ spans` | depends | The first consumer of byte spans: a fenced region is a source slice by span. Also added `Doc::Verbatim` (leaf; emitted only right after a line break). |
| `comments-round ◀──▶ format-fences` | handshake | fences requested a span on `Meta.trailing`; comments-round delivered `Option<Comment>`. Same-line fences remain deliberately inert (matcher unchanged) — documented on both sides. |
| `comments-round-2 ──▶ comments-round` | depends | Closes the bracket-position comment shapes round 1 parked; same machinery, four new `Vec<Comment>` slots. |
| `corpus-bugs ──▶ corpus-check` | depends | Fixes exactly the four root causes A–D the corpus check catalogued; measured back to 0 verification errors. |
| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. |
| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. |
| `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 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. |
Standing discipline for every feature in this lane (and any feature touching
the formatter): **`verify.rs` widening is guilty until proven innocent**
(CLAUDE.md #4). The only widening ever shipped is macro-items'
backtick-`Ident` arm in `normalize` — the normalization that produced
lucisv's one real corruption (2026-08-19, shipped without attack tests). Its
repair, `trim_lines_outside_strings`, is a *narrowing*, and it shipped with
the rejection tests the widening lacked. Every other round states
"`verify.rs` untouched" and adds *rejection/attack tests anyway*. Treat that
as the template.
### 2.2 Parser grammar / corpus lane
`corpus-check` is the measuring instrument for the whole lane: it defines
the buckets, and each grammar feature empties one and *advances* files into
the next — a sequencing chain, not a code dependency. The lane's members:
the sixteen bucket features (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) plus the parser-infrastructure features
(spans, name-spans, error-recovery, lexer-cleanup, define-table, and
recursion-limit, whose edges sit in §2.1). Code edges:
| edge | kind | contract |
|---|---|---|
| every grammar feature `──▶ corpus-check` | depends | The bucket scores and first-blocker histograms are how each round chose its target and measured its result. |
| `classes ◀──▶ vlog_parser::parse` | handshake | `parse(tokens)` became `parse(tokens, source)` — verbatim capture needs source in strict mode; every caller updated in the same change. |
| `assertions ──▶ classes` | depends | Reuses `verbatim_since`/`skip_balanced` (the constraint/covergroup capture) unchanged; adds `StmtKind::Verbatim`. |
| `directive-split ──▶ assertions / classes` | depends | Fifth producer of `ItemKind::Verbatim`; reuses the capture and `Fmt::raw_text` unchanged. |
| `item-misc ──▶ macro-items` | depends | Extends `at_macro_item` (spaced argument lists, `` `error``/`` `warning``); same verbatim contract, `RawText.col` still load-bearing. |
| `classes ─▶ macro-items` | refined in place | classes added the one-line `#(`-lookahead refinement to `at_macro_item` (the `` `uvm_component_new`` + parameterized-declaration idiom) — documented in classes' Handshakes, safety property unchanged. |
| `dynamic-types ─▶ ast::Dim` consumers | non-additive change | `Dim` became `{ kind: DimKind, span }` — the lane's **only** vector-element/shape change in history; every consumer was found by grep and updated (`Fmt::dim`, `bind_dims`, the spans walker). The precedent §3.3's "prefer additive fields" rule exists to avoid repeating. |
| `mop-up-2 ──▶ macro-items / dv-statements` | depends | Delivers the macro-followed-by-symbol fix dv-statements filed against macro-items, plus `new obj` (the expressions request from dv-statements) and base-only numbers. |
| `directives-in-instances ──▶ directives-in-lists` | depends | Reuses `ListDirective` and `take_list_directives` verbatim; same additive-fields shape chosen for the same blast-radius reason. |
| `dpi-export ─▶ dv-statements` | sequencing | Handed `csr_utils_pkg.sv` on (its next blocker was a `foreach`, a dv-statements shape). Typical of many one-way "your bucket now" notes across this lane. |
| `interfaces ─▶ expressions-2` | sequencing | Two files advanced to `->` implication and drive strengths; expressions-2 emptied that bucket. |
| `classes ◀──▶ class-semantics` | handshake | classes shipped with the honest gap "no name inside a class body is indexed"; class-semantics closed it (see §2.5). |
| `classes ─▶ format-fences` | open request | `fence::scan_nested` has no `Class` arm, so a fence inside a class body is inert **for the formatter** (the `protected_regions` line-scan backstop still protects `--fix`). Filed, not fixed — §2.9. |
| `ansi-first-port ◀──▶ type-definition` | handshake | type-definition filed the "first port with no direction doesn't parse" request; ansi-first-port delivered it (parser + one `bind_data_type` arm + one `type_span` tweak), and type-definition's tests flipped. |
| `lexer-cleanup ──▶ error-recovery / lint-rules-2` (QA logs) | depends | Fixes three lexer gaps: `@(* )` (TODO §1) plus the BOM and non-ASCII-honesty findings those two QA rounds filed; adds `ParsedSource::lex_error()` so `lucisv check` stops silently passing unlexable files. |
| `error-recovery ─▶ lucisv-server / linter-core` | depends (downstream) | `parse_source_tolerant` is the entry point the whole LSP and the linter stand on; the strict/tolerant split (shared grammar, no second parser) is the contract. |
| `name-spans ◀──▶ vlog-semantic` | handshake | vlog-semantic filed request 1 (spans on ~15 declaring nodes); name-spans delivered it, shrinking `scan.rs` to the `DataType` case (still open — §2.9). |
| `spans ─▶ everything positional` | depends | Byte ranges + `LineIndex` are the prerequisite named by TODO §6 for the LSP effort and by fences/range formatting. |
Also uniform in this lane: each new AST variant lists its exhaustive-match
blast radius (formatter arm, `bind.rs` arm, `spans.rs` arm) — that checklist
**is** the interface cost of touching `ast.rs`, and §3.3 restates it as a
rule. `vlog_linter`'s `visit.rs` is catch-all **for compilation only**: a new
variant that *contains items or statements* still needs an arm there, or no
AST lint rule ever descends into it (dv-statements added two such arms;
classes' missing one was a filed coverage gap, closed by lint-rules-2).
### 2.3 CLI lane
A clean promise chain — each feature consumed the previous one's written
promise:
| edge | kind | contract |
|---|---|---|
| `config-discovery ──▶ cli-polish` | depends | Consumed `Options.stdin_filename` exactly as promised (discovery anchor only) and `Options.exclude` as the CLI layer config patterns append to. |
| `parallel-files ◀──▶ cli-polish` | handshake | cli-polish flagged its hook-swapping `catch_panic` as single-thread-only; parallel-files replaced it with one startup hook + thread-local flag. **Anyone editing `catch_panic` must keep it that way.** |
| `parallel-files ──▶ config-discovery` | depends | Consumed the promise that config resolution happens up front in `gather`, producing the exact `Vec<(PathBuf, Config)>` work list a `par_iter` wants. |
| `format-cache ──▶ parallel-files` | depends | Consumed the promise that `process_file` is the per-file unit of work and `Outcome` the place a `Cached` bucket goes. |
| `format-cache ──▶ config-discovery` | depends | Consumed the cache-key promise: key includes resolved per-file settings (values, not config-file identity). |
| `format-cache ─▶ every output-changing feature` | standing promise | **Any change to formatter output must bump the workspace version** or warm caches keep stale verdicts. Same discipline as ruff/black. |
| `cli-filelist ──▶ filelist` | depends | Reuses `lucisv_core::filelist::read` unchanged (M1 explicitly parked the `-f` flag for this round); drops `incdirs`/`defines` as meaningless to a non-preprocessing formatter. |
| `cli-polish / linter-core ─▶ corpus-check, CI users` | standing promise | The 0/1/2 exit-code contract is frozen; new modes map onto it, never extend it. |
| `lucisv-core-lift ◀──▶ lucisv-server` | handshake | Delivered the server's two filed requests (config discovery + ignore-aware walk) by lifting `config.rs`/`walk.rs` into `lucisv_core` unchanged; CLI behavior byte-identical. |
### 2.4 Linter lane
| edge | kind | contract |
|---|---|---|
| `linter-core ──▶ error-recovery` | depends | Lints the tolerant tree so unparseable files are still linted for what is visible. |
| `linter-core ──▶ format-fences` | depends | CLI `--fix` reads `fence` (already `pub`) to stay out of fenced regions — one answer to "what is fenced", not two (later formalized by shared-fence-filter). |
| `lint-harness ──▶ linter-core` | depends | Consumes only the public API; the `.lint` case format + "marker naming a dead rule fails the suite" is the enforcement of rule-name stability on the test side. |
| `lint-harness ──▶ safety-net` (via dev-dep) | depends | Every fix's output must be something `format_source` accepts. |
| `lint-rules-2 ◀──▶ classes` | handshake | Closes the classes handshake: `visit.rs` now walks class bodies, so the four AST rules see class members. |
| `semantic-lints ──▶ vlog-semantic` | depends | The three symbol-table rules; new (justified) crate dep `vlog_linter → vlog_semantic`; lazy analysis; the lead's pre-authorization to modify `vlog_semantic` went **unused** (recorded so it is not read as taken). |
| `semantic-lints ──▶ one-parse` | depends | Reaches the server and CLI through the existing one-parse path (`LintContext::semantics()` / `with_semantics`). |
| `server-lint ──▶ linter-core` | depends | Protocol wiring only; relies on the three written promises (stable names, no panics/writes, sorted findings). |
| `server-lint ◀──▶ shared-fence-filter, one-parse` | handshake | Both of server-lint's filed requests were delivered by those rounds (fence-safe quick fixes; lint-from-Document). |
### 2.5 Semantics & index lane
| edge | kind | contract |
|---|---|---|
| `vlog-semantic ──▶ error-recovery, spans` | depends | Tolerant trees as input; span conventions throughout. |
| `workspace-index ──▶ vlog-semantic` | depends | Finishes `ExternalCandidate`s against what every file declares; the `paths` spelling contract is the coupling — if `bind.rs`/`resolve.rs` change a path's spelling, `workspace.rs::follow_one` changes with it. |
| `workspace-index ──▶ define-table` | depends | Each file's `` `define`` table is an index column (`find_define`). |
| `class-semantics ◀──▶ classes` | handshake | Delivers the filed gap; adds `SymbolKind::Class`, `ScopeKind::Class`, `InheritedCandidate` — with the two named compile-fix arms in `lucisv_server` (`tokens.rs`, `symbols.rs`). |
| `class-semantics ──▶ name-spans` | depends | Built on the delivered span fields; keeps `src[name_span] == name` corpus-asserted. |
| `overlay-promotion ◀──▶ type-definition` | handshake | Delivers type-definition's request 1: a **type-position** miss carries the bare name as its last candidate path (both miss spellings), so the overlay answers interfaces and package-less classes; type-definition then deleted its `indexed_type` fallback. Value-position misses unchanged — that asymmetry is the contract. |
| `type-hierarchy ──▶ overlay-promotion` | depends | The whole cross-file half is overlay-promotion being consumed at the `extends` offset. |
| `incremental-index ◀──▶ code-lens, hierarchy, type-hierarchy` | handshake | Delivers the jointly-filed edge tables: `instantiations_of` / `subclasses_of` recorded at build time; `callers_of_each` and `subtypes` became lookups (92 ms→0.26 ms, 82 ms→0.71 ms). Census policy carried over by construction: the walks (`instantiations.rs`, `classes.rs`) were **lifted into `vlog_semantic`**, not copied. |
| `incremental-index ──▶ indexing-ux` | depends | Amends the event story: a one-file update reports no events (one parse is not a scan); invariant: `update_file` yields byte-for-byte the index a full rebuild would (`fingerprint` is the witness; `update_one_checked` the test form). |
| `index-scope ◀──▶ indexing-ux` | handshake | Closes indexing-ux's QA finding by making `IndexBuilder` order-insensitive (sort/dedup in `finish`); `index_order` survives for the progress denominator. |
| `index-scope ──▶ filelist` | depends | Rung 1 (a filelist defines the scope exactly) is untouched; rungs 2/3 of the scope ladder were re-written (folder-scoped, open-file-first) — the ladder itself is the contract, documented in both READMEs. |
| `index-persistence ──▶ incremental-index` | depends | `update_one` writes its record through via `WorkspaceIndex::facts_for` (no double parse). |
| `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)
`refactor` is the umbrella plan; M1–M4 are its milestones plus two follow-ups.
| edge | kind | contract |
|---|---|---|
| `filelist (M1) ──▶ refactor` | depends | The scope story: a `.f` filelist is the project file; parser in `lucisv_core` (so the CLI later reuses it — it did, cli-filelist), scope ladder in the server. |
| `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
`lucisv-server` is the trunk; everything below extends it. Edges to
engine-lane features are listed above; this table is the server-internal web.
| edge | kind | contract |
|---|---|---|
| `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. 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. |
| `inline-templates ──▶ completion-templates, editor-scopes` | depends | Same skeletons as ghost text (LSP 3.18 `inlineCompletion`, `lsp-types` `proposed` feature); relative-indent contract — the client finishes the whitespace; round 2 dropped its `layout_at` consumption (re-privatized). |
| `hover/define ──▶ define-table`; `macro-expansion ──▶ define-table + hover` | depends | See the §2.5 handshake; `expand.rs` is deliberately workspace-blind (two strings + a `Define`). |
| `include-nav ──▶ filelist` | depends | First consumer of `incdirs`; the include graph (build/resolve/reachable, one `scan` shared by links, definition and the graph) plus hover's reachability overlay — `find_define`'s contract explicitly unchanged. |
| `file-operations ──▶ include-nav, file-watching` | depends | `resolve_as_if` added so willRename asks the *one* resolution engine about a future filesystem; reuses `watch::watched` + `SOURCE_GLOB` as the one scope predicate. |
| `file-watching ──▶ filelist / lucisv-core-lift` | depends | `SOURCE_GLOB` pinned to `walk::EXTENSIONS` by test; watches the filelist itself; re-registers on filelist change. |
| `folders-and-config ──▶ editor-settings` | depends | Adds the pull door (`workspace/configuration`) wrapped back into the push shape so there is exactly one settings parser; `Pending` generalizes apply-edit's `applying` map. |
| `editor-settings ◀──▶ lucisv-core-lift` | handshake | The four-rung precedence ladder (lucisv.toml > `lucisv.*` settings > tab size > defaults), per key — the reason the ladder can exist is the lifted `Discovery`. `will-save-wait-until` reuses the ladder minus rung 3. |
| `incremental-sync ◀──▶ pull-diagnostics` | handshake | One `didChange` = one `set_document` = one generation bump, however many ranges — pinned by test; the generation **is** the pull model's `resultId`. `semantic-tokens-delta` promises the inverse: token requests never bump it. **Amended 2026-08-28 by change-debounce**: one *flush* is one `set_document`, one bump and one publish per dirty buffer — however many ranges *and* however many notifications it coalesced. |
| `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. |
### 2.8 Packaging & release lane
| edge | kind | contract |
|---|---|---|
| `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). |
| `editor-platform-vsix ◀──▶ editor-marketplace-page` | handshake | The marketplace rewrite must keep the seven-package install table and the two bundled-binary layout sentences (re-applied additively during the concurrent rounds). |
| `ci-release ──▶ release-prep / editor-platform-vsix` | depends | Workflow = one-liners over `tools/`; consumes the exact seven `.vsix` names (`prune_release_assets.sh` checks each), the `CHANGELOG.md` heading convention, tag == workspace version. |
| `release-prep ──▶ editor-packaging` | depends | `release.sh` runs `smoke.js` as its gate; closed the missing-`LICENSE` item editor-packaging filed. Version lives in exactly four files — a promise to everyone. |
| `editor-marketplace-page ──▶ lucisv-server` (docs) | depends | The Details page mirrors the shipped capability table in the server's README; drifts if that table does. |
### 2.9 Open handshakes (filed, not yet delivered — claim before working)
These are the known coordination points. An agent picking one up should
update the filing README(s) and this file.
| # | request | filed by | owner it waits on |
|---|---|---|---|
| 1 | `lucisv_core::path::normalize` — one `.`/`..` folding instead of three private copies (`filelist::Reader::normalize`, `config::Discovery::absolute`, `includes::normalize`, the last now `pub`) | include-nav; restated by file-operations | lucisv_core |
| 2 | A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive | vlog-semantic (item 2); restated by class-semantics | vlog_parser |
| 3 | `fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off) | classes | vlog_formatter (fence.rs) |
| 4 | A `lint` key in `lucisv.toml` (`[lint.<rule>]` config; selected-rules list) with CLI>config precedence | linter-core; restated by lint-rules-2, semantic-lints, server-lint | config-discovery / lucisv_core |
| 5 | `lucisv check --rules-doc` printing `rules_markdown()` | lint-rules-2 | crates/lucisv |
| 6 | Workspace-wide "does any file mention this name" query — the precondition for the semantic lints defaulting on (cross-file hierarchical use is their one false-positive mode) | semantic-lints | vlog_semantic (index) |
| 7 | `SymbolKind::Interface` (interfaces currently indexed as `Module`; modport/clocking names unbound) | interfaces | vlog_semantic (+ mechanical arms in server `symbols.rs`/`hover.rs`) |
| 8 | Symlink-cycle detection in the shared walk (both front ends exposed; wants its own round — it changes CLI behavior) | lucisv-core-lift | lucisv_core |
| 9 | Chasing `InheritedCandidate` through the member tables (in-file and cross-file) + hover for `extends` — *partially advanced*: overlay-promotion made `resolve_external` answer an `InheritedCandidate` from its paths; the member-table chase and the hover remain absent | class-semantics | vlog_semantic |
| ~~10~~ | ~~`Fmt::raw_text`'s string-crossing path emits a `Doc::Text` carrying newlines~~ — **delivered 2026-08-26 (`53f2269`)**: both `raw_text` and the parameterized-type `#( … )` now emit `Doc::Inline`, whose printer arm resumes measuring from the text's own last line. directive-split's README (QA round 3 note) still documents it as open and should be struck there too | directive-split QA | ~~vlog_formatter~~ done |
| 11 | Corpus scripts match `parse error:` / `lex error:` / `verification failed:` textually; a structured `--output-format json` for format mode would remove it | corpus-check | crates/lucisv |
| 12 | `vlog_refactor::rename::Scope::build` re-derives sort-and-dedup by hand; could call `index_order` | indexing-ux | vlog_refactor |
| 13 | Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap | types-decls | vlog_semantic |
| 14 | A `program` node with `name_span`/`end_label_span` (today it lands in `Error`/verbatim), which would let linked-editing serve it with one arm | linked-editing | vlog_parser |
| 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.1 Feature → primary-home matrix
Where a feature's code chiefly lives (its README remains the authority on
exact file scope). Cross-module touches are recorded per-feature in §2 and in
each feature README's Handshakes; this matrix names only the primary home.
Grammar-lane features (*italicized*) routinely add exhaustive-match arms in
other crates — see §3.3's `ast.rs` row — though not always a formatter arm:
directive-split and ansi-first-port shipped with `vlog_formatter/src`
untouched, reusing existing arms.
| module | features whose home it is |
|---|---|
| `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` 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 (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/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
```mermaid
graph TD
subgraph parser [vlog_parser]
gram[grammar-lane features] --- pinfra[spans / name-spans / recursion-limit / error-recovery / define-table]
end
subgraph fmt [vlog_formatter]
net[safety-net verify.rs] --- fmtf[fences / range / alignment / comment rounds]
end
subgraph sem [vlog_semantic]
core[vlog-semantic] --- idx[workspace-index + incremental / persistence / scope / ux]
end
subgraph lint [vlog_linter]
lc[linter-core + rules + harness + semantic-lints]
end
subgraph refac [vlog_refactor]
ms[M2 rename / M3 ports / M4 instantiate / references]
end
subgraph corelib [lucisv_core]
cw[config + walk + filelist + cache]
end
subgraph cli [lucisv CLI]
clif[cli lane features]
end
subgraph srv [lucisv_server]
caps[capability features &#40;~30&#41;]
end
subgraph ed [editors/vscode + tools/CI]
pkg[packaging lane]
end
gram --> fmt
fmt --> parser
sem --> parser
lint --> parser
lint --> sem
refac --> parser
refac --> sem
srv --> parser
cli --> parser
cli --> corelib
cli --> fmt
cli --> lint
srv --> corelib
srv --> sem
srv --> refac
srv --> fmt
srv --> lint
pkg --> srv
pkg --> cli
```
Reading it feature-side: a grammar feature is by default a
**parser+formatter pair** (new AST + its layout, plus minimal arms in
`bind.rs`/`spans.rs`) — though one that reuses an existing arm ships with the
formatter untouched (directive-split, ansi-first-port); an index feature is a
**vlog_semantic + lucisv_server pair** (the data structure and the
events/settings around it); a capability feature is usually **server-only
plus one manifest line** (one handler module + `main.rs` capability + often a
`settings.rs` field, which then owes an `editors/vscode/package.json`
`contributes.configuration` entry — the choke point whose mismatches are
silent); a packaging feature is **editors/tools-only, save for the two pins
it owns in Rust** (editor-packaging's `tests/grammar.rs`, release-prep's
`--version` shape). Those shapes are the default that makes the lanes
parallel-safe — not an invariant; say in your scope which arms you actually
owe.
### 3.3 Choke points — files where features meet
These are the highest-contention interfaces. When two agents' scopes both
name one of these, they are not parallel — serialize or split the file's
ownership explicitly.
| choke point | owner (feature) | consumers | the rule |
|---|---|---|---|
| `vlog_parser/src/ast.rs` | the grammar lane collectively | formatter, semantic, linter, refactor, server, `tests/spans.rs` | A new variant costs, at minimum: a `format.rs` arm, a `bind.rs` arm, a `spans.rs` arm. `visit.rs` is catch-all for compilation only — a variant containing items/statements still needs an arm there or AST lint rules never see inside it. Prefer **additive fields / parallel vectors** over changing vector element types — that is why `ListDirective` sits beside the lists instead of inside them (two rounds chose it independently for blast-radius reasons). |
| `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/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, 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, 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). |
### 3.4 Working rules distilled for parallel agents
1. **Pick lanes, not files.** The eight lanes in §2 are the intended
parallelism. Two features in one lane usually share a choke point (§3.3);
check before spawning both.
2. **A grammar feature is a pair by default** (parser + formatter arms +
minimal `bind.rs`/`spans.rs` arms) — unless it reuses an existing arm, as
the verbatim producers and ansi-first-port did. Say which arms you owe in
the feature scope up front; the compile-fix arms in other crates are
legitimate and should be listed in Handshakes, per the established
pattern.
3. **`cargo fmt` per package** (`-p a -p b`), never `--all`, while another
agent is live — this rule already saved two concurrent rounds
(directives-in-lists, dynamic-types).
4. **Cross-module wants are filed, not done.** Write the request in your
README's Handshakes, add it to §2.9 here, and stop — the lead routes it.
Delivered requests get struck through in the filing README with a pointer
(the ~~strikethrough~~ + "Delivered by X" convention is established).
5. **Wire shapes and names are pinned by tests, so change them by test**:
scopePairs JSON, the systemverilog fence tag, the seven `.vsix` names,
the grammar/KEYWORDS lock, rule names, exit codes, message prefixes
(§2.9-11 until structured output lands).
6. **Anything touching formatter output**: attack tests for any
verify-adjacent machinery, and a version bump or the format cache serves
stale verdicts (§2.3).
---
*Maintenance: this file is derived documentation. When a feature round adds,
delivers, or supersedes a handshake, update the relevant table (§2.9
especially) in the same round, the way TODO.md checkboxes are kept current.*