Compare commits

...
11 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 e70d979e51 Release 0.12.0 — the indexed-navigation release
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m58s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:39:02 -07:00
lucioandClaude Fable 5 b2d778eb8d Indexed references: postings replace the per-request refactor walk
textDocument/references now reads declaration-to-occurrence postings
merged in WorkspaceIndex from compact per-file reference facts, with
open buffers overlaying live semantics — 0.062 ms/request over 820
files vs 21.7 ms for the old Workspace::sources() walk (~350x). The
walk stays as rename's engine and the equivalence oracle in tests.
FACTS_FORMAT 1->2 discards v1 caches whole. Cursor lookups
(symbol_at/reference_at/token_at) and macro-define lookup move to
binary-searched sorted tables; include definition inspects only the
cursor's line. Ambiguity refusals preserved throughout.

External dev: codex. Lead-reviewed, gates re-run, probe reproduced.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:36:01 -07:00
lucioandClaude Fable 5 27fc216df3 Marketplace page: absolute changelog link — vsce cannot resolve relative
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m37s
vsce package validates README links and auto-resolves relative ones
only for GitHub/GitLab repositories; the Gitea remote is neither, so
the relative CHANGELOG.md link failed the v0.11.0 release build.
Absolute git.luci.ooo URL instead, the same convention the page's
images already use (the Marketplace's own Changelog tab is unaffected
— it reads the file directly). Reported by the owner from the failed
workflow log.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 19:46:49 -07:00
lucioandClaude Fable 5 4665641e42 Release 0.11.0 — the large-workarea release
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Failing after 4m12s
Version bump (workspace + extension), the root CHANGELOG section
covering the six rounds (folder scope, incremental index + edge
tables, persistent cache, large-file mode, size cap + counting bar +
output log), the extension changelog's Unreleased flipped to 0.11.0,
and the Marketplace page's release-time pass: the Large workspaces
section drops its coming-soon framing, the stale Workspace
intelligence rows now describe the shipped scope model and counting
bar, and 0.11.0 highlights join the page. The scope-default behavior
change and its one-line migration are called out in the CHANGELOG.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 19:17:31 -07:00
lucioandClaude Fable 5 bc606dd6bd Large-file fast path: 100 MB netlists open in 40 ms
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 21s
Owner-requested round, the last of the large-workarea wave. Above
lucisv.largeFile.threshold (4 MiB default, 0 disables) a buffer opens
as a line index and nothing else — no lex, no parse, no semantics, and
its path removed from the index sources so nothing describes it by
stale disk bytes. Viewport highlighting lexes only the requested
window (snap to a line boundary, budget-bounded backward comment scan,
imperfection documented); semanticTokens/full answers the spec's
cancellation errors because the shipped VS Code binary marks tokens
complete on ANY non-error answer and never asks for ranges again —
settled by reading the bundle, verified independently by QA, pinned
with the client-library citations. Same-file definition/references
shipped on measurement (worst 37 ms vs the 150 ms budget); every
other handler answers as the empty file by construction; formatting
alone says why aloud. Two client facts recorded: VS Code never syncs
files over 50 MB, and above 20 MB our viewport tokens are the only
color.

QA rejected the first cut on the round's true shape — thousands of
tokens on one long line went quadratic through per-call UTF-16
conversion (7.86 s to color one 269 KB line). The fix adds a monotonic
PositionWalker to convert.rs (restart-on-backwards proven load-bearing
by the out-of-order tail-comment shape), adopted at three sites for
546x/759x on the probes — and it fixed ordinary files' semantic
tokens too (2.06 s to 232 ms on a one-line buffer), a cost the normal
path had always paid. Probes are now normally-running gates with 4.5x
margins, walker-vs-per-call equivalence swept over gnarly fixtures
and adversarial ping-pong.

51 tests added across both rounds (dev 43+5, QA 6+3, minus overlaps),
2 ignored probes. Completes the owner's large-workarea requests.

docs/features/large-file-mode/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 18:58:17 -07:00
lucioandClaude Fable 5 5e98b1a669 Marketplace page: the large-workarea wave documented, changelog added
ci / checks (push) Successful in 43s
ci / corpus (push) Successful in 21s
Owner-requested docs round, scoped to editors/vscode. The README's
settings table gains the seven new keys (index.scope/scopeDepth/
maxFileSize/logFiles/persist/cachePath, largeFile.threshold) with
their honest notes — scope-relative answers and the one-line
migration, the cap's open-buffer exemption, viewport-only highlighting
above the threshold — plus the formatOnSave tab-size caveat, and a new
'Large workspaces' section marked as coming in the next release
(nothing claims the wave as shipped; the 0.10.2 highlights and feature
tables stand as released). New editors/vscode/CHANGELOG.md gives the
Marketplace its Changelog tab: an Unreleased section for the wave and
condensed extension-user entries for every release 0.2.0 through
0.10.2, derived from the root changelog. Every setting name verified
against package.json; every claim traced to a feature README (the
claim-by-claim table is in the dev report); the two perf claims
qualified with their build profile by lead review.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 17:47:55 -07:00
lucioandClaude Fable 5 2e258df9a7 vlog_parser: the defines round-trip pieces the cache commit left behind
ci / checks (push) Successful in 41s
ci / corpus (push) Successful in 20s
DefineTable::from_entries and the PartialEq/Eq derives on
Define/DefineTable belong to the index-persistence round (e4b1f55) —
its facts.rs references from_entries — but the lead's explicit-path
staging missed the vlog_parser crate, so e4b1f55 does not build on a
clean checkout. Caught by the next round's dev noticing an uncommitted
change it did not make. The working tree was always green, which is
why every gate passed locally; the remote CI on e4b1f55 is the run
this fixes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 17:25:19 -07:00
lucioandClaude Fable 5 e4b1f55c12 Persistent index cache: a half-indexed workarea resumes where it stopped
ci / checks (push) Failing after 8s
ci / corpus (push) Failing after 5s
Owner-requested round. Every parsed file's FileFacts record is written
through to an index-cache store (append per file, atomic compaction at
scan end — a crash loses at most the file in flight), keyed by a
content hash that is the whole key: no mtime fast path, by measured
argument (6 ms of a 181 ms warm scan, and unsound against save-time
write-through). On reopen, hits skip parsing and the resume is
visible — cached: vs indexing: log lines, the bar counting through
hits, and an end message saying how many came from cache. Warm rescan
322 to 179 ms release, 1.5 s to 0.76 s debug; 910 KB store for the
860-file corpus. Location: lucisv.index.cachePath > the extension's
context.storageUri via initializationOptions (the one extension.js
change) > the OS cache dir keyed by workspace identity > nowhere;
lucisv.index.persist (default on) gates both directions immediately.

The cache is a performance artifact, never a correctness input, and
after the fix round that promise is total against everything but
intentional forgery — which the threat model now formally excludes
(same-user disk; a keyed MAC would be theater): a per-record checksum
drops every corrupt-but-parseable line (poisoned and reforged shapes
both pinned so the checksum is never mistaken for a MAC), first-writer
initialization is a create_new claim with structural 100/100 survival,
and a torn multi-byte tail costs exactly the torn record (0 of 583
offsets lose more). Old-format stores discard wholesale. Load==fresh
fingerprint equality swept over the corpus.

45 tests added across the main and fix rounds (dev 33+2, QA 9+3, one
QA test-construction bug self-caught), 2 ignored probes.

docs/features/index-persistence/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 16:33:52 -07:00
lucioandClaude Fable 5 5e4aa7bd6f Incremental indexing + the edge tables: one file changed, one file merged
Owner-requested round. WorkspaceIndex::update_file/remove_file replace
one file's contribution without reading or parsing anything else;
Server::reindex_one takes the fast path for a didSave of one held file
or a one-file watcher event (33 ms vs 1.5 s on the corpus, 45x), with
everything else — settings, scope, filelist, multi-file events —
keeping the full rebuild, pinned by a trigger-table test. FileIds stay
sorted positions by deliberate deviation: renumbering through the one
merge both finish and update_file end in makes build(W) byte-identical
to build(W minus F).update_file(F) — fingerprint equality, attacked by
QA across long interleaved sequences, disambiguation flips, define
shadowing and the ghost hunt (the affected-keys union reads old and
new records both). The per-file FileFacts the index retains are the
documented memory cost (~1.4 MB on the corpus).

The two oldest filed Handshakes land: instantiation and inheritance
edge tables, built by the byte-for-byte moved census walks, turn
codeLens counts (92 ms to 0.26 ms), incomingCalls and typeHierarchy
subtypes into lookups — census policies pinned unchanged at both the
consumers and now the source. Counts are as of the index, not of
unsaved keystrokes: the freshness delta is documented and pinned from
both sides. Saves no longer raise a progress bar; generation and lens
refresh still ride. Round 18's three inherited scope obligations are
pinned permanent.

36 tests added (dev 27 + QA 9). Left open, filed: wholesale republish,
Candidates re-derivation cost, incremental removal vs include
re-resolution.

docs/features/incremental-index/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 14:35:27 -07:00
lucioandClaude Fable 5 7266b13702 Index scope: open-file-first, folder-scoped by default
Owner-requested round. The scope ladder: a filelist still defines the
whole project and outranks everything; lucisv.index.scope=workspace
restores the walk-the-roots behavior (the same function, not an
equal-output one — pinned); the new default walks only the union of
folders a buffer has been opened from, each raised
lucisv.index.scopeDepth ancestor levels (default 0), clamped at the
deepest containing root. Opening a file outside the scope widens it
and reindexes through the existing progress/generation machinery;
scope grows only along the open axis within a session. Cross-file
answers are scope-relative and the docs say so loudly, with the
one-line migration in the setting description.

The round also closes indexing-ux QA's MEDIUM builder footgun:
IndexBuilder::finish now sorts and dedups before assigning FileIds, so
no insertion order can reach the result — pinned by a permanent
three-order fingerprint test — which makes feeding open files first
provably a progress nicety. 151 existing tests swept mechanically
(QA sampled 40+ sites: constructor swaps only); lead fixed the one
vacuous tail QA found plus two premise/comment hygiene items.

19 tests added. Known deltas documented: a root's .gitignore does not
reach a walk starting below it (filed against lucisv_core); rootless
depth-0 keeps its flat read; startup index is empty until the first
didOpen.

docs/features/index-scope/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 13:12:27 -07:00
lucioandClaude Fable 5 8c8cfc538e Indexing UX for large workareas: size cap, counting bar, output log
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 21s
Owner-requested round. lucisv.index.maxFileSize (default 1 MiB, 0
disables, junk values fall back to the default — misparse must never
un-cap) skips walked files at one fs::metadata call before any read;
open buffers are always served uncapped, a cap change rescans like
exclude does, and the cap reads consistently through every sources()
consumer — documented per consumer, with the write-path warning gap
(a rename silently leaving a capped file stale) filed as a follow-up.

The indexing bar now counts: $/progress reports '137/860 path' with a
monotonic percentage over the post-exclude post-cap denominator,
throttled to ≤1000 reports per rescan with the last file always
reporting. Enabled by vlog_semantic's new IndexBuilder (add_file/
finish) with build() redefined as the loop over the newly-exported
index_order — the FileId ordering rule is now a call, not a comment.
QA proved both production callers order correctly; hardening the
builder against out-of-order future callers is round 18's acceptance
test. lucisv.index.logFiles (default on) streams 'indexing: path' and
cap-skip lines to the editor's Output panel at LOG level; the skip
count survives in the end message when logging is off. Measured
overhead ≈2.6% on the 860-file corpus; 0 corpus files exceed 1 MiB
and the default-capped index is pinned identical to uncapped.

21 tests added + QA's attack set + the lead's human_size boundary fix
('1024.0 KiB' can no longer be printed for a byte short of a MiB).

docs/features/indexing-ux/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 11:56:30 -07:00
57 changed files with 15832 additions and 695 deletions

No files matched your search

+82
View File
@@ -4,6 +4,88 @@ 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.12.0 — 2026-08-27
The indexed-navigation release: find-all-references stops paying a
project scan per request.
### References become a lookup
Each indexed file now persists compact reference facts — same-file uses
of its exported declarations, plus unresolved cross-file candidates —
and the workspace index resolves them once into
declaration-to-occurrence postings. `textDocument/references` reads
that posting list and overlays every open buffer's live analysis, so
unsaved additions, deletions and moved declarations stay visible with
no request-time scan: **0.06 ms per request over an 820-file workspace
where the old walk cost 22 ms (~350×)**. The old walk remains rename's
engine and is pinned equal to the indexed answer by test; ambiguity
still degrades to the in-file answer exactly as before.
### Cursor lookups stop sweeping
Declaration, reference and macro-token lookups under the cursor —
hover, definition, references entry points — binary-search sorted
position tables instead of scanning every symbol in the buffer, and
`` `include`` definition inspects only the cursor's line.
### One-time cache rebuild
The persisted facts format moved to version 2 for the new reference
records. An existing index cache from 0.11.0 is discarded whole on
first open and rebuilt — one re-scan, never a misread record.
## 0.11.0 — 2026-08-27
The large-workarea release: a project too big to scan is now a project
lucisv keeps up with. Six owner-requested rounds, one dev/QA/review
cycle each.
### Indexing starts where you are
`lucisv.index.scope` defaults to `folder`: the index covers the folders
your open files live in — raised `lucisv.index.scopeDepth` ancestor
levels — and widens as you open more. Cross-file answers are
scope-relative until the scope reaches a folder; a filelist still
defines the whole project, and `"workspace"` restores the previous
walk exactly (the same code path, not an equal-output one). **This is
a behavior change for workspace users without a filelist** — the
migration is that one setting.
### One file changed, one file merged
A save re-indexes only the saved file — 33 ms where the corpus rescan
cost 1.5 s — through an index whose incremental histories are
byte-identical to fresh builds. Instantiation counts, incoming calls
and subtype answers now come from edge tables built at index time
(code lens 92 ms → 0.26 ms), so they read as of the index rather than
of unsaved keystrokes.
### The index survives a restart
Per-file index records persist under the editor's workarea storage
(`lucisv.index.persist`, on by default), keyed by content hash: a
crashed or closed session resumes where it stopped, cached files fly
through the progress bar, and the end message says how many came from
cache. The cache is a performance artifact with a per-record checksum
— a damaged entry costs a re-parse, never an answer.
### Netlists open instantly
Above `lucisv.largeFile.threshold` (4 MiB) a buffer skips the pipeline
entirely: a 104 MB netlist opens in 40 ms, viewport syntax
highlighting answers in a quarter of a millisecond, and same-file
definition/references run as bounded text scans. Most other features
deliberately answer nothing there. Fixing this path's long-line
behavior also made ordinary files' semantic tokens up to 9× faster.
### The scan explains itself
The indexing bar counts `n/total` through the files; the output
channel logs each file as indexed, cached, or skipped;
`lucisv.index.maxFileSize` (1 MiB default) keeps generated files out
of the index, with skips counted in the closing message.
## 0.10.2 — 2026-08-27
The works-anywhere release: a seventh extension package that carries
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.10.2"
version = "0.12.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.10.2"
version = "0.12.0"
[[package]]
name = "lucisv_server"
version = "0.10.2"
version = "0.12.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.10.2"
version = "0.12.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.10.2"
version = "0.12.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.10.2"
version = "0.12.0"
[[package]]
name = "vlog_refactor"
version = "0.10.2"
version = "0.12.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.10.2"
version = "0.12.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.10.2"
version = "0.12.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+51 -5
View File
@@ -491,7 +491,12 @@ later:
typedef names → (file, span) across all workspace files, so header
imports (`import pkg::*;`) and instantiations resolve to definitions
in other files. Start as a full-scan-on-startup index (Verilog
codebases are small); incrementality comes with salsa later.
codebases are small); ~~incrementality comes with salsa later~~ — one file
at a time since 2026-08-27, without salsa
(`docs/features/incremental-index/README.md`); and ~~re-scanned from zero on
every startup~~ — what a scan learns persists since 2026-08-27, so a reopened
workspace indexes from records rather than parses and an interrupted scan
resumes (`docs/features/index-persistence/README.md`).
→ `vlog_semantic::WorkspaceIndex::build(files) `+
`resolve_external(&Semantics, &WorkspaceIndex) -> ExternalResolutions`,
a two-layer design: the index is a full scan (860 corpus files in 0.7 s),
@@ -558,6 +563,16 @@ later:
- [ ] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa;
don't take that dependency until hover/definition across files exists.
Per-file recompute is fine at Verilog file sizes.
**Partly answered without salsa, 2026-08-27**
(`docs/features/incremental-index/README.md`): `WorkspaceIndex::update_file`
replaces one file's contribution and provably gives the index a whole build
would have, so a save costs 33 ms instead of 1.5 s over the corpus. No query
graph and no dependency tracking — the salsa question is still open, and is
still deferred. **A second piece answered without salsa, 2026-08-27**
(`docs/features/index-persistence/README.md`): every file's `FileFacts` are
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.
- [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
@@ -591,7 +606,10 @@ section only tracks the milestones.
- [x] **M1 `filelist`** — EDA `.f` filelist defines the index scope
(`-f` nesting, `+incdir+`/`+define+` recorded, env vars); fallback:
workspace walk, then current file's directory when rootless.
~~workspace walk, then current file's directory when rootless~~
**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`.**
- [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.
@@ -750,6 +768,29 @@ and are not gaps.
— the rescan is one opaque call — and the `end` names the indexed
file count, read off the index's own file list. The bar covers the
scan, ending before the scope warnings and the republishes.
→ **Superseded in part, 2026-08-27**: the rescan is no longer opaque.
`docs/features/indexing-ux/README.md` adds
`vlog_semantic::IndexBuilder`/`index_order`, so the bar now carries
`n/total file.sv` and a counted percentage (throttled to at most
1000 reports per rescan), a per-file `window/logMessage` under
`lucisv.index.logFiles`, and a 1 MiB default walk-file size cap under
`lucisv.index.maxFileSize` whose skips the `end` message counts.
→ **Extended again, 2026-08-27**
(`docs/features/index-persistence/README.md`): a file restored from the
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.
→ **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
that *is* open. Over it, a buffer is line-indexed and nothing else — 41 ms
for 100 MB — coloured a viewport at a time by `semanticTokens/range`,
answered `null`/empty everywhere else, and left out of the index entirely
(the one exception to "an open buffer is never capped"). It logs
`large-file fast path: <path> (<bytes> bytes)` once per buffer.
Everything else above — the capability gate, the token scheme, the
create's ignored answer, the ordering against the republish — is
unchanged.
- [x] **`$/cancelRequest`** — the loop handles requests sequentially
and ignores cancellation; at minimum answer already-cancelled queued
requests with `RequestCancelled`.
@@ -835,7 +876,10 @@ and are not gaps.
the progress bar comes down, gated on
`workspace.codeLens.refreshSupport`. One request recorded there: an
instantiation-edge table in `WorkspaceIndex` would make both this and
`callHierarchy/incomingCalls` a lookup instead of a workspace walk.
`callHierarchy/incomingCalls` a lookup instead of a workspace walk —
**delivered 2026-08-27, `docs/features/incremental-index/README.md`**:
`instantiations_of` is the table, the walk is gone, and a whole file's
lenses went 92 ms → 0.26 ms over the corpus.
- [x] **On-type formatting** — conspicuous absence for a
formatter-first server; candidate trigger: newline (indent the new
line per block nesting), `;` (reformat the finished statement).
@@ -883,10 +927,12 @@ and are not gaps.
bare name of a parameterized `base #(8)`. A base the workspace does
not index (every UVM chain top) yields no item rather than a guess.
`subtypes` is `hierarchy::callers_of_each`'s census in another key —
one `sources()` pass, substring prefilter, deterministic sort — at
~~one `sources()` pass, substring prefilter, deterministic sort — at
55 ms over the 860-file corpus, 53 ms of it file I/O; the
inheritance-edge table that would make it a lookup is filed beside the
instantiation-edge table §9c's code-lens item already recorded. Two
instantiation-edge table §9c's code-lens item already recorded.~~
**Both tables shipped 2026-08-27** (`docs/features/incremental-index/README.md`):
`subclasses_of` makes `subtypes` a lookup, 55 ms → 0.71 ms. Two
gaps recorded there: `lsp-types` 0.97 has no `typeHierarchyProvider`
field, so the capability is inserted into the serialized `initialize`
result by hand, and `vlog_parser` rejects `interface class`, so
+152 -25
View File
@@ -20,8 +20,8 @@
//! See `docs/features/completion-core/README.md`.
use std::cmp::Ordering;
use std::collections::HashSet;
use std::path::PathBuf;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_parser::token::TokenKind;
@@ -55,6 +55,14 @@ pub struct Candidates {
units: Vec<Candidate>,
macros: Vec<Macro>,
words: Vec<String>,
/// How many in-scope files contain each word. What makes it possible to
/// take one file's words back without re-lexing every other file
/// ([`Candidates::update_file`]): a word is dropped from `words` exactly
/// when the last file holding it stops holding it.
word_files: HashMap<String, usize>,
/// Each file's distinct words, so the count above can be decremented for
/// the version of the file being replaced.
per_file: HashMap<PathBuf, Vec<String>>,
}
impl Candidates {
@@ -64,7 +72,70 @@ impl Candidates {
/// 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 {
Candidates { units: units_of(index), macros: macros_of(index), words: words_of(sources) }
let mut out = Candidates {
units: units_of(index),
macros: macros_of(index),
..Candidates::default()
};
for (path, text) in sources {
let words = words_in(text);
for word in &words {
*out.word_files.entry(word.clone()).or_default() += 1;
}
if !words.is_empty() {
out.per_file.insert(path.clone(), words);
}
}
out.words = out.word_files.keys().cloned().collect();
sort_by_name(&mut out.words, |w| w.as_str());
out
}
/// Replace one file's contribution — the incremental form of
/// [`Candidates::build`], for a rescan that only one file triggered
/// (`docs/features/incremental-index/README.md`).
///
/// The two index-derived tables are re-derived from the index, which has
/// already been updated and is the only thing they read. The word table is
/// patched: this file's old words are given back and its new ones taken,
/// 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.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.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>) {
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);
}
}
}
for word in &words {
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 !words.is_empty() {
self.per_file.insert(path.to_path_buf(), words);
}
}
/// Index names starting with `prefix`, case-insensitively.
@@ -132,27 +203,24 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
out
}
/// Every identifier the in-scope files' token streams contain.
fn words_of(sources: &[(PathBuf, String)]) -> Vec<String> {
// Deduplicated as it is collected, not afterwards: a workspace holds two
// 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.
/// Every distinct identifier one file's token stream contains.
///
/// Deduplicated as it is collected, not afterwards: a workspace holds two
/// 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> {
// 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() };
let mut seen: HashSet<String> = HashSet::new();
for (_, text) in sources {
// 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 { continue };
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
if !seen.contains(token.text.as_str()) {
seen.insert(token.text.clone());
}
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
if !seen.contains(token.text.as_str()) {
seen.insert(token.text.clone());
}
}
let mut out: Vec<String> = seen.into_iter().collect();
sort_by_name(&mut out, |w| w.as_str());
out
seen.into_iter().collect()
}
/// Whether a token is a word worth offering.
@@ -174,10 +242,13 @@ fn is_word(kind: TokenKind, text: &str) -> bool {
/// Sort by name, case-insensitively first so [`matching`]'s binary search is
/// valid, then exactly so equal names sit next to each other for `dedup`.
fn sort_by_name<T>(items: &mut [T], name: impl for<'b> Fn(&'b T) -> &'b str) {
items.sort_by(|a, b| {
let (a, b) = (name(a), name(b));
lower_cmp(a, b).then_with(|| a.cmp(b))
});
items.sort_by(|a, b| word_cmp(name(a), name(b)));
}
/// The order [`sort_by_name`] puts names in, named so an incremental insert
/// can find the one place a whole sort would have put a word.
fn word_cmp(a: &str, b: &str) -> Ordering {
lower_cmp(a, b).then_with(|| a.cmp(b))
}
/// The entries whose name starts with `prefix`, case-insensitively.
@@ -324,4 +395,60 @@ mod tests {
assert!(names.contains(&"seen"), "{names:?}");
assert!(!names.contains(&"never_seen"), "{names:?}");
}
// ------------------------------------------------------------------
// QA (incremental-index, 2026-08-27): `word_files`'s exact bookkeeping
// ------------------------------------------------------------------
#[test]
fn a_shared_word_dropped_from_one_file_is_still_offered_by_the_other() {
let raw = [
("/rtl/a.sv", "module a;\n logic shared;\nendmodule\n"),
("/rtl/b.sv", "module b;\n logic shared;\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);
assert_eq!(candidates.words("shared").len(), 1, "premise: two files, one word");
let mut current = index.clone();
current.update_file(PathBuf::from("/rtl/a.sv"), "module a;\nendmodule\n");
candidates.update_file(&current, Path::new("/rtl/a.sv"), "module a;\nendmodule\n");
assert_eq!(candidates.words("shared").len(), 1, "b.sv still holds it — not given back");
current.update_file(PathBuf::from("/rtl/b.sv"), "module b;\nendmodule\n");
candidates.update_file(&current, Path::new("/rtl/b.sv"), "module b;\nendmodule\n");
assert!(candidates.words("shared").is_empty(), "and now nothing holds it");
}
#[test]
fn updating_the_same_file_twice_in_a_row_never_double_counts_or_goes_negative() {
// `set_words` decrements the *previous* call's words before counting
// the new ones; the attack is a bug that decrements the same word
// twice (an underflow — `usize` would panic in debug, wrap in
// release) or forgets to re-add a word that survives across the two
// calls.
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 current = index.clone();
let text2 = "module a;\n logic w2;\nendmodule\n";
current.update_file(PathBuf::from("/rtl/a.sv"), text2);
candidates.update_file(&current, Path::new("/rtl/a.sv"), text2);
assert!(candidates.words("w1").is_empty(), "w1 given back");
assert_eq!(candidates.words("w2").len(), 1);
// The same update again, unchanged text.
candidates.update_file(&current, Path::new("/rtl/a.sv"), text2);
assert!(candidates.words("w1").is_empty(), "still gone, not somehow negative-then-absent");
assert_eq!(candidates.words("w2").len(), 1, "still exactly one, not doubled");
// `remove_file`, twice in a row.
candidates.remove_file(&current, Path::new("/rtl/a.sv"));
assert!(candidates.words("w2").is_empty());
candidates.remove_file(&current, Path::new("/rtl/a.sv"));
assert!(candidates.words("w2").is_empty(), "removing an already-removed file is a no-op");
}
}
+3 -3
View File
@@ -948,7 +948,7 @@ endmodule
) -> (Tree, Workspace, Uri, Position) {
let path = tree.write(file, top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
@@ -1683,7 +1683,7 @@ endmodule
filelist: Some("files.f".to_string()),
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
ws.rebuild_index();
@@ -1731,7 +1731,7 @@ endmodule
}
let started = std::time::Instant::now();
let mut ws = Workspace::default();
ws.open_roots(vec![corpus.clone()]);
ws.open_whole_workspace(vec![corpus.clone()]);
let build = started.elapsed();
// A buffer that is not on disk: it overlays the walk, so the corpus is
+228
View File
@@ -35,6 +35,13 @@ impl<'a> Positions<'a> {
Position { line: line - 1, character: utf16_len(slice) }
}
/// A cursor for converting many byte offsets in one non-decreasing sweep,
/// in amortized O(1) each rather than [`position`](Self::position)'s
/// O(offset within its line).
pub fn walker(&self) -> PositionWalker<'_> {
PositionWalker { positions: self, line: 0, line_start: 0, cursor: 0, units: 0 }
}
/// The byte offset of an LSP position, clamped into the document.
pub fn offset(&self, pos: Position) -> u32 {
let Some(line) = self.index.line_range(pos.line.saturating_add(1)) else {
@@ -112,6 +119,62 @@ impl<'a> Positions<'a> {
}
}
/// A monotonic byte-offset → [`Position`] cursor, for a caller that has a
/// whole sequence of offsets to convert and already has them in order.
///
/// [`Positions::position`] measures a line from its start on every call, which
/// is free on ordinary source and quadratic when thousands of tokens sit on
/// **one** very long line — the netlist shape the large-file fast path exists
/// for, where it cost seconds per keystroke. The walker carries the
/// measurement forward instead: one line lookup per call, and each byte of a
/// line counted once however many offsets fall on it.
///
/// **Total, not merely fast.** An offset below the last one is not an error
/// and never panics: the walker restarts at that line's start and re-measures,
/// which is exactly the work [`Positions::position`] would have done. So every
/// answer is that function's answer — by construction, and pinned by
/// `the_walker_agrees_with_the_per_call_converter_on_every_shape`.
pub struct PositionWalker<'a> {
positions: &'a Positions<'a>,
/// The 1-based line the cursor sits on. Zero before the first call, which
/// is a line number no offset has, so the first call always restarts.
line: u32,
/// The byte offset that line starts at.
line_start: u32,
/// How far into the text the cursor has measured, on that line.
cursor: u32,
/// UTF-16 units of `line_start..cursor`, before the `\r` rule below.
units: u32,
}
impl PositionWalker<'_> {
/// The LSP position of a byte offset — [`Positions::position`]'s answer,
/// reached without re-measuring the line for offsets already passed.
pub fn position(&mut self, offset: u32) -> Position {
let offset = self.positions.floor_boundary(offset);
let (line, _) = self.positions.index.line_col(offset);
if line != self.line || offset < self.cursor {
self.line = line;
self.line_start = self.positions.index.line_range(line).map_or(0, |r| r.start);
self.cursor = self.line_start;
self.units = 0;
}
let step = self.positions.text.get(self.cursor as usize..offset as usize).unwrap_or("");
self.units += utf16_len(step);
self.cursor = offset;
// The one `\r` `Positions::position`'s `strip_suffix` would drop: LSP
// line content excludes the whole `\r\n`, and `\r` is one UTF-16 unit.
let carriage = offset > self.line_start
&& self.positions.text.as_bytes().get(offset as usize - 1) == Some(&b'\r');
Position { line: line - 1, character: self.units - u32::from(carriage) }
}
/// The LSP range of a byte range, whose two ends are in order already.
pub fn range(&mut self, span: TextRange) -> Range {
Range { start: self.position(span.start), end: self.position(span.end) }
}
}
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
fn utf16_len(s: &str) -> u32 {
s.chars().map(|c| c.len_utf16() as u32).sum()
@@ -283,6 +346,171 @@ mod tests {
});
}
// ------------------------------------------------------------------
// the monotonic walker
// ------------------------------------------------------------------
/// A fixed-seed linear congruential generator — deterministic randomness
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` and
/// `tokens.rs` use.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
self.0 >> 33
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
}
/// Every shape a byte → position converter has to survive: multi-byte and
/// astral characters, CRLF, empty lines, a last line with no terminator,
/// and a buffer that is one enormous line — the shape the walker exists
/// for.
fn fixtures() -> Vec<String> {
let mut giant = String::from("module m; wire ");
for n in 0..2_000 {
giant.push_str(&format!("a{n},"));
}
giant.push_str("last;\nendmodule\n");
let mut wide_and_wide = String::from("// é ✓ 🎉 ");
for n in 0..500 {
wide_and_wide.push_str(&format!("würe_{n}_✓, "));
}
wide_and_wide.push_str("\r\nendmodule\n");
vec![
String::new(),
"module m;\nendmodule\n".to_string(),
"// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule".to_string(),
"ab\r\ncd\r\n\r\nef\r\n".to_string(),
"\n".repeat(50),
giant,
wide_and_wide,
]
}
#[test]
fn the_walker_agrees_with_the_per_call_converter_on_every_shape() {
let mut rng = Lcg(0x5EEDA11);
for text in fixtures() {
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let len = text.len() as u64;
for trial in 0..20 {
// Two strides, alternating: a crawl of a few bytes at a time
// (many offsets on one line, which is what the walker is for)
// and one that crosses the whole fixture in a few dozen steps.
let stride = if trial % 2 == 0 { 4 } else { (len / 20).max(1) };
let mut offset = rng.below(len + 1) as u32;
let mut walker = positions.walker();
for _ in 0..60 {
assert_eq!(
walker.position(offset),
positions.position(offset),
"{text:?} at {offset}"
);
offset += rng.below(stride * 2) as u32;
}
}
}
}
#[test]
fn the_walker_agrees_at_every_byte_of_a_gnarly_buffer() {
// Ascending one byte at a time walks through the middle of every
// multi-byte character and over both bytes of every `\r\n`.
let text = "// é ✓ 🎉\r\nmodule mü;\n\r\n wire ✓a;\r\nendmodule";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut walker = positions.walker();
for offset in 0..=text.len() as u32 + 2 {
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
}
}
#[test]
fn a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position() {
// Out of order is debug-unreachable for the callers, but the walker
// is total: a backwards offset restarts the measurement rather than
// returning a stale column.
let text = "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut rng = Lcg(0xBACC1);
let mut walker = positions.walker();
for _ in 0..500 {
let offset = rng.below(text.len() as u64 + 4) as u32;
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
}
}
/// QA attack (fix-round re-verification): the walker's restart is a
/// per-line promise, not a per-document one. Two huge lines far apart,
/// hit in alternation — the shape that would expose an accidental
/// document-wide rescan hiding inside the "reset to line start" path.
/// Each call still answers `Positions::position`'s answer exactly, and
/// (checked by hand alongside this test, not asserted here to keep the
/// test itself fast and non-flaky) costs only that one line's length,
/// never the whole document's.
#[test]
fn a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly() {
let mut text = String::new();
text.push_str(&"a".repeat(20_000));
text.push('\n');
text.push_str(&"b".repeat(20_000));
text.push('\n');
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let line1_positions = [0u32, 1, 5_000, 19_999, 20_000];
let line2_start = 20_001u32;
let line2_positions =
[line2_start, line2_start + 1, line2_start + 5_000, line2_start + 19_999];
let mut walker = positions.walker();
for round in 0..50 {
let (a, b) = line1_positions
.iter()
.zip(line2_positions.iter().cycle())
.nth(round % line1_positions.len())
.expect("non-empty");
for &offset in [*a, *b].iter() {
assert_eq!(
walker.position(offset),
positions.position(offset),
"round {round}, offset {offset}"
);
}
}
}
#[test]
fn the_walkers_range_is_the_per_call_range() {
let text = "module m;\r\n wire ✓a, b, c;\nendmodule\n";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut walker = positions.walker();
for span in [
TextRange::new(0, 6),
TextRange::new(9, 11),
TextRange::new(13, 17),
TextRange::new(20, 21),
TextRange::new(30, text.len() as u32),
] {
assert_eq!(walker.range(span), positions.range(span), "{span:?}");
}
}
#[test]
fn a_walker_over_an_empty_document_answers_the_one_position_there_is() {
with("", |p| {
let mut walker = p.walker();
assert_eq!(walker.position(0), pos(0, 0));
assert_eq!(walker.position(99), pos(0, 0));
});
}
#[test]
fn an_empty_document_has_one_position() {
with("", |p| {
+9
View File
@@ -24,6 +24,15 @@ pub const SOURCE: &str = "lucisv";
/// error rather than add an opinion, and they exist at all only when the parse
/// already failed (`pairs::missing_end_diagnostics`).
pub fn all(doc: &Document) -> Vec<Diagnostic> {
// A buffer on the large-file fast path was never parsed, so there is
// nothing to say about it — and both passes below would read its *text*
// (the lint context builds one, the fence filter scans for them), which is
// the whole-file work the fast path exists to skip. The empty list is not
// a silent no-op either: it is what clears the squiggles a buffer that has
// just grown past the threshold left behind.
if doc.large {
return Vec::new();
}
let mut all = diagnostics(doc);
all.extend(crate::pairs::missing_end_diagnostics(doc));
all.extend(crate::lint::diagnostics(doc));
+34 -3
View File
@@ -520,7 +520,7 @@ mod tests {
..Default::default()
});
}
ws.open_roots(vec![self.path.clone()]);
ws.open_whole_workspace(vec![self.path.clone()]);
ws
}
@@ -599,6 +599,37 @@ mod tests {
);
}
/// Renaming a file that is open **on the large-file fast path**
/// (`docs/features/large-file-mode/README.md`). The renamed file's own
/// `` `include``s (it has none here — a netlist would not) are out of
/// `will_rename`'s sweep because `Workspace::sources()` already leaves a
/// fast-path buffer out entirely; what this pins is the other half: an
/// **unrelated** small file's include *of* the large file still resolves
/// and still gets rewritten, because resolution walks the filesystem
/// (`IncludeGraph::resolve`, `Path::is_file`) rather than the source list
/// the fast-path buffer was excluded from.
#[test]
fn renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it() {
let tree = Tree::new("largerename");
let net = tree.write("rtl/net.v", "module net;\nendmodule\n");
let top = tree.write("rtl/top.sv", "`include \"net.v\"\nmodule t;\nendmodule\n");
tree.write("files.f", "rtl/top.sv\nrtl/net.v\n");
let mut ws = tree.workspace();
ws.set_client_settings(crate::settings::ClientSettings {
filelist: Some(tree.path.join("files.f").display().to_string()),
large_file_threshold: 10,
..Default::default()
});
let net_uri = path_to_uri(&net).expect("uri");
// Padded past the 10-byte test threshold, so it opens on the fast path.
ws.set_document(net_uri.clone(), format!("module net;\nendmodule\n{}", " ".repeat(20)));
assert!(ws.document(&net_uri).expect("open").large, "premise: the fast path");
let rewrite = will_rename(&ws, &[tree.rename("rtl/net.v", "rtl/netlist.v")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["netlist.v".to_string()]));
}
#[test]
fn a_cross_directory_rename_re_spells_through_an_incdir() {
let tree = Tree::new("crossdir");
@@ -1055,7 +1086,7 @@ mod tests {
// same read the index rebuild already pays on every save.
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let files = ws.index().files().len();
assert!(files > 500, "the corpus is checked in: got {files}");
let rename = FileRename {
@@ -1401,7 +1432,7 @@ mod tests {
let new = target_dir.join("prim_assert_renamed.sv");
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let rename = FileRename { old_uri: uri_of(&old), new_uri: uri_of(&new) };
let run = || {
+96 -64
View File
@@ -24,8 +24,10 @@ use vlog_parser::ast::Item;
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
use vlog_semantic::SymbolKind as SemanticKind;
use vlog_semantic::instantiations::{self, Decl};
use vlog_semantic::{DeclSite, InstantiationEdge};
use crate::convert::Positions;
use crate::instantiations::{self, Decl, Site};
use crate::state::Workspace;
use crate::uri::{path_to_uri, uri_to_path};
@@ -69,41 +71,49 @@ pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIn
/// Who instantiates each of `names`, answered one list per name in the order
/// asked.
///
/// Every in-scope file is walked, because the workspace index records what a
/// file *declares* and not what it instantiates — there is no edge table to
/// consult. A file whose text contains none of the names is skipped before it
/// is parsed, which is what keeps the walk affordable: an instantiation of
/// `fifo` has to write `fifo`.
/// **A lookup in the workspace index's instantiation-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The census is unchanged — the table is built by the same
/// [`instantiations::sites`] walk this function used to run, at index time
/// (`docs/features/incremental-index/README.md`) — and so is the answer's
/// shape and order. What changed is the cost: only the files that really do
/// instantiate one of the names are read, to turn the recorded byte spans into
/// the protocol's line/character ranges.
///
/// The **batch** is the primitive rather than the single name because
/// [`Workspace::sources`] re-reads every in-scope file: one question per name
/// would re-read the whole workspace once per name, and `lens.rs` asks about
/// every module declared in a buffer at once. A file is parsed once for the
/// whole batch.
/// The **batch** stays the primitive: `lens.rs` asks about every module
/// declared in a buffer at once, and one file that instantiates three of them
/// is read once for the batch rather than once per name.
///
/// An empty name is answered with nothing rather than searched for: nothing
/// this server hands out is nameless, and the prefilter matches every file for
/// one, which would parse the whole workspace to find nothing.
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyIncomingCall>> {
let index = ws.index();
let mut answers: Vec<Vec<CallHierarchyIncomingCall>> =
names.iter().map(|_| Vec::new()).collect();
for (path, text) in ws.sources() {
let wanted: Vec<usize> = names
.iter()
.enumerate()
.filter(|(_, name)| !name.is_empty() && text.contains(**name))
.map(|(index, _)| index)
.collect();
if wanted.is_empty() {
continue;
}
let Some(uri) = path_to_uri(&path) else { continue };
let (tree, _) = parse_source_tolerant(&text);
let sites = instantiations::sites(&tree.items);
// Every file holding an edge for any of the names, once, in path order.
let mut files: Vec<vlog_semantic::FileId> = names
.iter()
.filter(|name| !name.is_empty())
.flat_map(|name| index.instantiations_of(name).iter().map(|edge| edge.file))
.collect();
files.sort();
files.dedup();
for file in files {
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
// The spans were recorded against the text the index was built from;
// this is the text now. The two differ only for a buffer edited since
// the last rebuild, which is the same staleness `item_in_file` has
// always carried.
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for index in wanted {
answers[index].extend(callers_in(&uri, &positions, &sites, names[index]));
for (at, name) in names.iter().enumerate() {
if name.is_empty() {
continue;
}
let edges = index.instantiations_of(name).iter().filter(|edge| edge.file == file);
answers[at].extend(callers_in(&uri, &positions, edges));
}
}
for answer in &mut answers {
@@ -152,31 +162,29 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOu
.collect()
}
/// Every module in one already-parsed file that instantiates `name`, with its
/// sites.
/// One file's edges for one module, as incoming calls: one call per
/// instantiating module, with every site inside it.
///
/// Sites are grouped by the declaration they sit in rather than by adjacency,
/// because a module written inside another can put its own sites between two
/// of the outer module's.
fn callers_in<'a>(
uri: &Uri,
positions: &Positions,
sites: &[Site<'a>],
name: &str,
edges: impl Iterator<Item = &'a InstantiationEdge>,
) -> Vec<CallHierarchyIncomingCall> {
let mut callers: Vec<(Decl<'a>, Vec<TextRange>)> = Vec::new();
for site in sites {
if site.inst.module != name {
continue;
}
// An instantiation at file scope has no calling module to report.
let Some(owner) = site.owner else { continue };
match callers.iter_mut().find(|(decl, _)| decl.span == owner.span) {
Some((_, spans)) => spans.push(site.inst.module_span),
None => callers.push((owner, vec![site.inst.module_span])),
let mut callers: Vec<(&DeclSite, Vec<TextRange>)> = Vec::new();
for edge in edges {
match callers.iter_mut().find(|(owner, _)| owner.span == edge.owner.span) {
Some((_, spans)) => spans.push(edge.site_span),
None => callers.push((&edge.owner, vec![edge.site_span])),
}
}
callers
.into_iter()
.filter_map(|(decl, spans)| {
.filter_map(|(owner, spans)| {
Some(CallHierarchyIncomingCall {
from: item(uri.clone(), positions, decl)?,
from: item_of(uri.clone(), positions, &owner.name, owner.name_span, owner.span)?,
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
})
})
@@ -186,20 +194,28 @@ fn callers_in<'a>(
/// The hierarchy item for one module declaration, positioned against the text
/// it was parsed from.
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<CallHierarchyItem> {
let name_span = decl.module.name_span;
item_of(uri, positions, &decl.module.name, decl.module.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's edge
/// table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<CallHierarchyItem> {
if name_span.is_empty() {
return None;
}
// The protocol requires `selectionRange` inside `range`; a declaration the
// parser could not close is the case where that may not hold, and there
// the name alone is the honest extent.
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
decl.span
} else {
name_span
};
let full =
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(CallHierarchyItem {
name: decl.module.name.clone(),
name: name.to_string(),
kind: SymbolKind::MODULE,
tags: None,
detail: None,
@@ -335,7 +351,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -527,7 +543,7 @@ endmodule
tree.write("files.f", "sub.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
@@ -536,9 +552,15 @@ endmodule
}
#[test]
fn an_unsaved_instantiation_is_a_caller_before_it_is_saved() {
// The sources a walk reads are the open buffers overlaid on disk, so a
// just-typed instantiation counts.
fn an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the
// census reading `Workspace::sources()` on every request, so a
// keystroke in *another* buffer moved the count before anything
// rebuilt. The census is the index's edge table now, and an index is
// only ever as of its last build or update — which does fold every
// open buffer in, so a save (or any other rescan trigger) makes the
// edit count. The rule the test pins is the new one, from both sides.
let (tree, mut ws, uri) = three("unsaved");
let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone();
assert_eq!(incoming(&ws, &root).len(), 2, "premise");
@@ -546,7 +568,14 @@ endmodule
let fresh = tree.path.join("other.sv");
let other_uri = path_to_uri(&fresh).expect("uri");
ws.set_document(other_uri, "module other;\nendmodule\n".to_string());
assert_eq!(incoming(&ws, &root).len(), 1, "the buffer removed its instantiation");
assert_eq!(
incoming(&ws, &root).len(),
2,
"the buffer alone does not move the census — the index has not seen it"
);
// What a save does, and what the incremental path does with it.
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert_eq!(incoming(&ws, &root).len(), 1, "the edit removed its instantiation");
}
// ------------------------------------------------------------------
@@ -935,17 +964,20 @@ endmodule
#[test]
#[ignore]
fn qa_perf_worst_case_common_word_module_name() {
// A single-letter module name is a substring of nearly every file's
// text, so the prefilter admits nearly everything — the worst case
// the prefilter can face. Measures whether that worst case is still
// sane, not a specific number.
// A single-letter module name used to be the worst case there was: it
// is a substring of nearly every file, so the prefilter over
// `Workspace::sources()` admitted nearly everything. There is no
// prefilter and no walk since 2026-08-27 — the census is a lookup in
// the index's edge table, and a name nothing instantiates is an empty
// slice — so this probe is kept for what it now measures: that the
// shape which used to be the worst case is not a case at all.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let item = CallHierarchyItem {
name: "d".to_string(),
kind: SymbolKind::MODULE,
@@ -993,7 +1025,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&declaring).expect("uri");
ws.set_document(uri.clone(), text.clone());
let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7)
+7 -7
View File
@@ -35,7 +35,7 @@ pub fn hover(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Hover> {
/// of the workspace's, because outside the include graph picking one would be
/// a guess.
fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
let token = doc.tokens.iter().find(|t| t.is_macro() && t.span.contains(offset))?;
let token = doc.token_at(offset).filter(|token| token.is_macro())?;
let name = macro_name(token)?;
if let Some(define) = doc.defines.latest(name) {
@@ -399,7 +399,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
@@ -421,7 +421,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
@@ -440,7 +440,7 @@ mod tests {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let top = dir.join("top.sv");
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
@@ -582,7 +582,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
@@ -641,7 +641,7 @@ mod qa_findings {
filelist: Some(dir.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![dir.clone()]);
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());
@@ -695,7 +695,7 @@ mod qa_findings {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
+65 -24
View File
@@ -84,9 +84,9 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
/// Where `` `include``s are looked for, and which file includes which.
///
/// Rebuilt whole on every index rebuild, from the same source list: includes
/// are a handful of lines per file, so there is nothing here worth updating
/// incrementally.
/// Rebuilt whole on every index rebuild, from the same source list — and
/// patched one file at a time when only one file's text moved
/// ([`IncludeGraph::update_file`]).
#[derive(Debug, Default, Clone)]
pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
@@ -104,24 +104,11 @@ pub struct IncludeGraph {
impl IncludeGraph {
/// Scan every in-scope file for its `` `include``s and resolve them.
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
let mut graph = IncludeGraph {
incdirs,
edges: HashMap::new(),
known: sources.iter().map(|(path, _)| path.clone()).collect(),
folded: HashMap::new(),
};
// Built before the edges: `resolve` consults it, and an edge resolved
// against a half-filled table would be keyed inconsistently.
for (path, _) in sources {
let Some(key) = path.to_str().map(str::to_lowercase) else { continue };
graph
.folded
.entry(key)
// A second file with the same folded spelling makes the
// spelling ambiguous, and an ambiguous one decides nothing.
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.clone()));
}
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
// Learned before the edges: `resolve` consults both tables, and an edge
// resolved against a half-filled one would be keyed inconsistently.
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()
@@ -134,6 +121,53 @@ impl IncludeGraph {
graph
}
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
///
/// `known` is the index's file list as it stands *after* the update, which
/// is what the known-file and folded-spelling tables are: cheap to rebuild
/// from a list already in memory, and wrong to leave stale when a file has
/// come or gone.
///
/// 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.
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),
};
}
/// 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);
}
/// Re-derive the known-file set and the folded-spelling table from the
/// index's file list. The same two loops [`IncludeGraph::build`] runs, over
/// paths rather than over `(path, text)` pairs.
fn relearn(&mut self, known: &[PathBuf]) {
self.known = known.iter().cloned().collect();
self.folded.clear();
for path in known {
let Some(key) = path.to_str().map(str::to_lowercase) else { continue };
self.folded
.entry(key)
// A second file with the same folded spelling makes the
// spelling ambiguous, and an ambiguous one decides nothing.
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.clone()));
}
}
/// The `+incdir+` directories an include is looked for in, in filelist
/// order — the search rungs past the including file's own directory.
pub fn incdirs(&self) -> &[PathBuf] {
@@ -298,7 +332,14 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec<DocumentLink> {
/// The same computation the links use, so F12 and ctrl-click can never
/// disagree about where a line goes.
pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option<Location> {
let (_, path) = resolved(ws, doc).into_iter().find(|(inc, _)| inc.span.contains(offset))?;
// Definition is a cursor request, so inspect only its line. `documentLink`
// still scans the whole file because it must return every include.
let (line, _) = doc.line_index.line_col(offset);
let line = doc.line_index.line_range(line)?;
let text = doc.text.get(line.as_range())?;
let include =
include_on_line(text, line.start).filter(|include| include.span.contains(offset))?;
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
}
@@ -541,7 +582,7 @@ mod tests {
filelist: Some(tree.path.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join(rel);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -735,7 +776,7 @@ mod qa_scope_probe {
filelist: Some(dir.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
File diff suppressed because it is too large. Load diff
+6 -6
View File
@@ -25,9 +25,9 @@ use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
use crate::convert::Positions;
use crate::instantiations;
use crate::state::Workspace;
/// The ghost labels for one range of a buffer.
@@ -280,7 +280,7 @@ endmodule
}
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
inlay_hints(&ws, &uri, range)
@@ -321,7 +321,7 @@ endmodule
let top = "module top;\n sub u1 (clk);\nendmodule\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let hints = inlay_hints(&ws, &uri, everything());
@@ -708,7 +708,7 @@ endmodule
let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n";
let top_path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&sub_path).expect("uri");
let top_uri = path_to_uri(&top_path).expect("uri");
ws.set_document(top_uri.clone(), top.to_string());
@@ -758,7 +758,7 @@ endmodule
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let screen = Range {
@@ -793,7 +793,7 @@ endmodule
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let _ = inlay_hints(&ws, &uri, everything());
+897
View File
@@ -0,0 +1,897 @@
//! The large-file fast path: what a buffer nobody lexed can still answer.
//!
//! A buffer over `lucisv.largeFile.threshold` is opened by
//! [`crate::state::Document::large`] — one newline scan, no lex, no parse, no
//! semantics, no index. This module is everything that then reads such a
//! buffer *on demand*:
//!
//! * [`window`] lexes one viewport's worth of source for
//! `textDocument/semanticTokens/range`, which is what paints the file;
//! * [`definition`] and [`references`] scan the buffer once per request for a
//! name.
//!
//! Nothing here is exact, and the rules it approximates by are stated in
//! `docs/features/large-file-mode/README.md`. The contract is only that an
//! answer costs a bounded amount of work and never a pass over the whole
//! file — except the two scans, which are one linear pass and are measured.
use vlog_parser::token::Token;
use vlog_parser::{tokenize, LineIndex, TextRange};
use crate::state::Document;
/// How far back [`inside_block_comment`] looks for the marker that decides
/// whether a window opens inside `/* ... */`.
///
/// 64 KiB. A block comment longer than this is a licence header nobody is
/// scrolled to the middle of, and the cost of the decision has to stay flat in
/// the file's size: this is the one backwards read the fast path does, and it
/// is a `memchr`-shaped search over a fixed slice however big the file is.
const BACKSCAN: u32 = 64 * 1024;
/// The most source one window may lex, 1 MiB.
///
/// A client is free to ask for `semanticTokens/range` over the whole document
/// — VS Code's own `_provideDocumentRangeSemanticTokens` command does exactly
/// that — and answering it over 100 MB would be the whole-file pass this mode
/// exists to avoid. A viewport plus the pages above and below it is a few tens
/// of kilobytes, so the cap is three orders of magnitude clear of anything an
/// editor asks for while scrolling.
const MAX_WINDOW: u32 = 1024 * 1024;
/// How many times [`lex`] may shrink a window that does not lex before giving
/// up on it. Each attempt drops the lines from the failure onwards, and the
/// failure moves backwards every time, so this is a belt-and-braces bound
/// rather than a number anything real reaches.
const SHRINK_ATTEMPTS: usize = 4;
/// The most occurrences `textDocument/references` reports on a large buffer.
/// A name in a netlist can occur a hundred thousand times, and a reference
/// list nobody can read costs the editor more than it gives.
pub const REFERENCE_LIMIT: usize = 1000;
/// One window of a large buffer, lexed.
///
/// Both fields are in **document** offsets: the caller never sees the slice
/// the lexer actually ran on.
pub struct Window {
/// What the lexer made of the window. Empty when the window could not be
/// lexed at all, which is not an error — it is a window whose text is one
/// unterminated construct.
pub tokens: Vec<Token>,
/// Block-comment text the lexer was never shown: the tail of a comment the
/// window opens inside, and the head of one it ends inside. Colouring
/// these is the whole reason the fast path looks backwards at all.
pub comments: Vec<TextRange>,
}
/// Lex the lines `range` touches, and nothing else.
///
/// The window is snapped out to whole lines, capped at [`MAX_WINDOW`], and
/// then treated as a self-contained piece of source. The two things that
/// makes wrong, and what is done about each:
///
/// * **A comment the window opens inside.** Decided by a bounded backwards
/// scan ([`inside_block_comment`]); the tail of the comment is returned as a
/// comment span and the lexer starts after it.
/// * **A construct the window ends inside.** The lexer is all-or-nothing, so
/// an unterminated comment or string at the far edge would cost the whole
/// window; [`lex`] shrinks the window to the last line that does lex, and
/// what is left over is coloured as a comment when it opens one.
pub fn window(doc: &Document, range: lsp_types::Range) -> Window {
let text = &doc.text;
let (start, end) = bounds(&doc.line_index, text.len() as u32, range);
let mut comments = Vec::new();
let mut from = start;
if inside_block_comment(text, start) {
let Some(rest) = text.get(start as usize..end as usize) else {
return Window { tokens: Vec::new(), comments };
};
match rest.find("*/") {
// The comment ends inside the window: colour its tail and lex
// from the first byte after it.
Some(at) => {
from = start + at as u32 + 2;
comments.push(TextRange::new(start, from));
}
// The whole window is inside one comment. Nothing to lex at all,
// which is the cheapest window there is.
None => {
comments.push(TextRange::new(start, end));
return Window { tokens: Vec::new(), comments };
}
}
}
let Some(slice) = text.get(from as usize..end as usize) else {
return Window { tokens: Vec::new(), comments };
};
let (mut tokens, lexed) = lex(slice);
for token in &mut tokens {
rebase(token, from);
}
if let Some(tail) = trailing_comment(slice, lexed) {
comments.push(TextRange::new(from + tail.start, from + tail.end));
}
Window { tokens, comments }
}
/// The byte range one `Range` asks about, snapped out to whole lines and
/// capped.
///
/// Both ends land on a character boundary: a line start and a line end always
/// do, and the cap is floored onto one.
fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) {
let last = index.line_count();
let first_line = (range.start.line + 1).min(last);
let last_line = (range.end.line + 1).clamp(first_line, last);
let start = index.line_range(first_line).map_or(0, |line| line.start);
let mut end = index.line_range(last_line).map_or(len, |line| line.end);
if end.saturating_sub(start) > MAX_WINDOW {
// Snapped to the line the cap lands in where that helps, and cut
// mid-line where it does not: a single line longer than the cap is
// exactly the netlist shape the cap is for. A token cut in half at the
// far edge still colours as what it started as.
let capped = start + MAX_WINDOW;
end = match index.line_range(index.line_col(capped).0) {
Some(line) if line.end <= capped => line.end,
_ => capped,
};
}
(start, end.max(start))
}
/// Whether the byte at `at` is inside a `/* ... */` comment, as far as a
/// backwards scan of at most [`BACKSCAN`] bytes can tell.
///
/// **Deliberately approximate.** It reads the last `/*` or `*/` before `at`
/// and believes it: a `/*` written inside a string or after a `//` fools it,
/// and so does a comment whose opener is further back than the budget, in
/// which case the answer is "code". Both mis-colour a screen and neither can
/// corrupt anything, which is the trade the whole mode is built on.
fn inside_block_comment(text: &str, at: u32) -> bool {
let at = at as usize;
let mut from = at.saturating_sub(BACKSCAN as usize);
while from < at && !text.is_char_boundary(from) {
from += 1;
}
let Some(hay) = text.get(from..at) else { return false };
match (hay.rfind("/*"), hay.rfind("*/")) {
(Some(open), Some(close)) => open > close,
(Some(_), None) => true,
_ => false,
}
}
/// Lex as much of `slice` as lexes, reporting how many bytes that was.
///
/// The lexer is all-or-nothing (`docs/features/error-recovery/README.md`), and
/// a window cut out of the middle of a file ends wherever the viewport ended —
/// so an unterminated comment or string at the far edge is the *normal* case
/// here, not a broken file. Its error names the line it gave up on, so the
/// retry drops that line and everything after it.
fn lex(slice: &str) -> (Vec<Token>, u32) {
let mut end = slice.len();
for _ in 0..SHRINK_ATTEMPTS {
let Some(head) = slice.get(..end) else { return (Vec::new(), 0) };
match tokenize(head) {
Ok(tokens) => return (tokens, end as u32),
Err(problem) => match line_start(head, problem.line) {
// Line 1 failed: there is nothing left to keep.
Some(0) | None => return (Vec::new(), 0),
Some(shorter) => end = shorter,
},
}
}
(Vec::new(), 0)
}
/// The byte offset of a 1-based line of `text`, or `None` when it has no such
/// line. Used only on the failure path, so it walks rather than indexing.
fn line_start(text: &str, line: u32) -> Option<usize> {
if line <= 1 {
return Some(0);
}
let mut seen = 1;
for (at, byte) in text.bytes().enumerate() {
if byte == b'\n' {
seen += 1;
if seen == line {
return Some(at + 1);
}
}
}
None
}
/// The block comment the leftovers of a shrunk window open, if they open one.
///
/// A banner comment crossing the bottom of the viewport is the shape this is
/// for: the lexer refused the window because of it, and colouring the rest of
/// the window as comment is both what it is and what the *next* window (once
/// the user scrolls) will say too.
fn trailing_comment(slice: &str, lexed: u32) -> Option<TextRange> {
let rest = slice.get(lexed as usize..)?;
let open = rest.find("/*")?;
// A `/*` that is closed inside the leftovers was not what stopped the
// lexer, so this is not the shape above and guessing would be wrong.
if rest[open..].contains("*/") {
return None;
}
Some(TextRange::new(lexed + open as u32, lexed + rest.len() as u32))
}
/// Move a token, and the comments hanging off it, from window offsets to
/// document offsets.
fn rebase(token: &mut Token, by: u32) {
token.span = shift(token.span, by);
for comment in &mut token.leading {
comment.span = shift(comment.span, by);
}
if let Some(comment) = &mut token.trailing {
comment.span = shift(comment.span, by);
}
}
fn shift(span: TextRange, by: u32) -> TextRange {
TextRange::new(span.start + by, span.end + by)
}
// ----------------------------------------------------------------------
// the two scans
// ----------------------------------------------------------------------
/// The keywords that make the identifier after them a declaration, as far as
/// the fast path is concerned.
///
/// A heuristic, and a small one on purpose: it is read backwards from an
/// occurrence, not parsed, so a declaration written any other way (a port
/// listed in an ANSI header after its direction and type, a `typedef`'s new
/// name, an instance name) is simply not found and the request answers
/// nothing. Every word here is a real keyword — pinned by a test against
/// `vlog_parser::KEYWORDS`, so a typo cannot sit here quietly.
const DECLARATORS: [&str; 22] = [
"module",
"macromodule",
"interface",
"package",
"program",
"primitive",
"class",
"function",
"task",
"input",
"output",
"inout",
"wire",
"reg",
"logic",
"bit",
"integer",
"int",
"real",
"genvar",
"parameter",
"localparam",
];
/// The identifier `offset` sits in, if it sits in one.
pub fn word_at(text: &str, offset: u32) -> Option<TextRange> {
let bytes = text.as_bytes();
let at = (offset as usize).min(bytes.len());
let mut start = at;
while start > 0 && is_word(bytes[start - 1]) {
start -= 1;
}
let mut end = at;
while end < bytes.len() && is_word(bytes[end]) {
end += 1;
}
// A cursor in whitespace between two words has an empty range, and an
// empty name would match everywhere.
(start < end).then(|| TextRange::new(start as u32, end as u32))
}
/// Where the name at `offset` looks declared: the first occurrence of it
/// preceded by a declaring keyword, or nothing.
///
/// One linear pass over the buffer, which is what a request on a file nothing
/// has indexed costs. The measurement is in the feature README.
pub fn definition(doc: &Document, offset: u32) -> Option<TextRange> {
let name = word_at(&doc.text, offset)?;
let name = doc.text.get(name.as_range())?;
occurrences(&doc.text, name).find(|at| declares(&doc.text, *at))
}
/// Every occurrence of the name at `offset`, capped at [`REFERENCE_LIMIT`].
///
/// Occurrences of the *text*, whole-word: this buffer has no scopes, so a
/// local `i` in one module and a local `i` in another are one answer. That is
/// the honest thing a text scan can say, and it is what the README calls
/// checking-light.
pub fn references(doc: &Document, offset: u32, include_declaration: bool) -> Vec<TextRange> {
let Some(name) = word_at(&doc.text, offset) else { return Vec::new() };
let Some(text) = doc.text.get(name.as_range()) else { return Vec::new() };
let declaration = (!include_declaration).then(|| definition(doc, offset)).flatten();
occurrences(&doc.text, text)
.filter(|found| Some(*found) != declaration)
.take(REFERENCE_LIMIT)
.collect()
}
/// Every whole-word occurrence of `name` in `text`, in order.
fn occurrences<'a>(text: &'a str, name: &'a str) -> impl Iterator<Item = TextRange> + 'a {
let bytes = text.as_bytes();
text.match_indices(name).filter_map(move |(at, _)| {
let before = at.checked_sub(1).map(|i| bytes[i]);
let after = bytes.get(at + name.len()).copied();
let bounded = !before.is_some_and(is_word) && !after.is_some_and(is_word);
bounded.then(|| TextRange::new(at as u32, (at + name.len()) as u32))
})
}
/// Whether the word before this occurrence declares it.
fn declares(text: &str, occurrence: TextRange) -> bool {
let bytes = text.as_bytes();
let mut end = occurrence.start as usize;
while end > 0 && bytes[end - 1].is_ascii_whitespace() {
end -= 1;
}
let mut start = end;
while start > 0 && is_word(bytes[start - 1]) {
start -= 1;
}
text.get(start..end).is_some_and(|word| DECLARATORS.contains(&word))
}
/// Whether a byte can be part of an identifier. `$` is in, for the system
/// tasks; the escaped-identifier form (`\name `) is not modelled at all.
fn is_word(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::{Position, Range};
use std::path::PathBuf;
/// A fast-path document over `text`.
fn large(text: &str) -> Document {
Document::large(Some(PathBuf::from("/rtl/net.v")), text.to_string())
}
fn range(from: u32, to: u32) -> Range {
Range {
start: Position { line: from, character: 0 },
end: Position { line: to, character: 0 },
}
}
/// The text of every token a window produced, in order.
fn words(doc: &Document, window: &Window) -> Vec<String> {
window
.tokens
.iter()
.filter(|t| t.kind != vlog_parser::token::TokenKind::Eof)
.map(|t| doc.text[t.span.as_range()].to_string())
.collect()
}
// ------------------------------------------------------------------
// the window
// ------------------------------------------------------------------
#[test]
fn a_window_lexes_its_own_lines_and_reports_document_offsets() {
let doc = large("module a;\nwire b;\nwire c;\nendmodule\n");
let window = window(&doc, range(1, 2));
assert_eq!(words(&doc, &window), ["wire", "b", ";", "wire", "c", ";"]);
// The spans are the document's, not the slice's: the first token is
// `wire` on line 1, which starts at byte 10.
assert_eq!(window.tokens[0].span.start, 10);
}
#[test]
fn a_window_starting_mid_line_is_snapped_back_to_the_line_start() {
let doc = large("module a;\nwire b;\n");
let mid = Range {
start: Position { line: 1, character: 4 },
end: Position { line: 1, character: 6 },
};
assert_eq!(words(&doc, &window(&doc, mid)), ["wire", "b", ";"]);
}
#[test]
fn a_window_past_the_end_of_the_file_is_empty_and_does_not_panic() {
let doc = large("module a;\nendmodule\n");
assert!(words(&doc, &window(&doc, range(900, 999))).is_empty());
}
#[test]
fn a_window_opening_inside_a_block_comment_colours_the_tail_and_lexes_the_rest() {
let doc = large("/* a\n b\n c */ wire d;\nwire e;\n");
// Lines 1..3: the window opens on ` b`, which is inside the comment
// opened on line 0, so the tail up to `*/` is a comment span and the
// lexer only saw what followed it.
let window = window(&doc, range(1, 3));
assert_eq!(window.comments.len(), 1);
let comment = &doc.text[window.comments[0].as_range()];
assert!(comment.ends_with("*/"), "{comment:?}");
assert!(comment.starts_with(" b"), "{comment:?}");
assert_eq!(words(&doc, &window), ["wire", "d", ";", "wire", "e", ";"]);
}
#[test]
fn a_window_wholly_inside_a_block_comment_is_one_comment_and_no_tokens() {
let mut text = String::from("/* opener\n");
for _ in 0..40 {
text.push_str(" still a comment\n");
}
text.push_str("*/\nwire a;\n");
let doc = large(&text);
let window = window(&doc, range(10, 20));
assert!(window.tokens.is_empty());
assert_eq!(window.comments.len(), 1);
}
#[test]
fn the_backward_scan_gives_up_beyond_its_budget_and_assumes_code() {
// A block comment opened further back than BACKSCAN: the decision
// cannot be made, and the documented answer is "code".
let mut text = String::from("/* opener\n");
text.push_str(&" filler filler filler filler\n".repeat(4000));
assert!(text.len() as u32 > BACKSCAN, "the premise: past the budget");
text.push_str("wire a;\n");
let doc = large(&text);
let last = doc.line_index.line_count() - 2;
let window = window(&doc, range(last, last));
assert!(window.comments.is_empty(), "no comment was detected");
assert_eq!(words(&doc, &window), ["wire", "a", ";"], "it lexed as code");
}
#[test]
fn a_window_ending_inside_a_block_comment_keeps_the_lines_that_lex() {
let doc = large("wire a;\nwire b;\n/* an unterminated banner\n");
let window = window(&doc, range(0, 2));
assert_eq!(words(&doc, &window), ["wire", "a", ";", "wire", "b", ";"]);
assert_eq!(window.comments.len(), 1, "the banner is coloured as a comment");
assert!(doc.text[window.comments[0].as_range()].starts_with("/*"));
}
#[test]
fn a_window_ending_inside_a_string_keeps_the_lines_that_lex() {
let doc = large("wire a;\n$display(\"unterminated\n");
let window = window(&doc, range(0, 1));
assert_eq!(words(&doc, &window), ["wire", "a", ";"]);
assert!(window.comments.is_empty(), "an unterminated string is not a comment");
}
#[test]
fn a_window_whose_first_line_cannot_lex_answers_nothing_rather_than_guessing() {
let doc = large("$display(\"unterminated\nwire a;\n");
let window = window(&doc, range(0, 0));
assert!(window.tokens.is_empty());
assert!(window.comments.is_empty());
}
#[test]
fn a_window_is_capped_however_much_the_client_asks_for() {
// Every line is 8 bytes, so 200_000 lines is 1.6 MB — a client asking
// for the whole document must still lex at most MAX_WINDOW of it.
let text = "wire a;\n".repeat(200_000);
assert!(text.len() as u32 > MAX_WINDOW, "the premise");
let doc = large(&text);
let window = window(&doc, range(0, doc.line_index.line_count()));
let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0);
assert!(last <= MAX_WINDOW, "lexed past the cap: {last}");
assert!(last > MAX_WINDOW - 64, "and up to it: {last}");
}
#[test]
fn one_line_longer_than_the_cap_is_cut_rather_than_lexed_whole() {
let mut text = String::from("wire ");
text.push_str(&"a".repeat(MAX_WINDOW as usize + 1000));
text.push_str(";\n");
let doc = large(&text);
let window = window(&doc, range(0, 0));
// It still answers, and it did not read the whole line.
let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0);
assert!(last <= MAX_WINDOW, "{last}");
}
#[test]
fn an_empty_buffer_answers_an_empty_window() {
let doc = large("");
let window = window(&doc, range(0, 10));
assert!(window.tokens.is_empty() || words(&doc, &window).is_empty());
assert!(window.comments.is_empty());
}
/// QA attack: a buffer of nothing but newlines. Every line is empty, so
/// every byte offset the code touches (line starts, line ends, the
/// backward scan's window) coincides with several others — the shape most
/// likely to trip an off-by-one into an out-of-range slice.
#[test]
fn a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens() {
let doc = large(&"\n".repeat(5_000));
for (from, to) in [(0, 1), (0, 5000), (4998, 4999), (2500, 2500)] {
let window = window(&doc, range(from, to));
// Only the EOF token, which every `tokenize` call ends with even
// over blank input — no real token, and no panic getting there.
assert!(words(&doc, &window).is_empty(), "nothing to lex: {from}..{to}");
}
}
/// QA attack: a CRLF netlist. `LineIndex` keeps the `\r` as an ordinary
/// byte of its line (`convert.rs`'s own rule), so a window boundary lands
/// right before a `\r` rather than a `\n` — this pins that the window
/// still lexes the same tokens CRLF or not, and that the trailing `\r` on
/// each line does not get coloured as part of the token before it.
#[test]
fn a_crlf_netlist_windows_the_same_as_its_lf_twin() {
let lf = "module m;\r\n wire sig_a;\r\n wire sig_b;\r\nendmodule\r\n";
let doc = large(lf);
let window = window(&doc, range(1, 2));
assert_eq!(words(&doc, &window), ["wire", "sig_a", ";", "wire", "sig_b", ";"]);
// No token swallowed the `\r`: every token's text is exactly itself.
for token in &window.tokens {
let text = &doc.text[token.span.as_range()];
assert!(!text.contains('\r'), "a token ate the line ending: {text:?}");
}
}
// ------------------------------------------------------------------
// the shrink helper on its own
// ------------------------------------------------------------------
#[test]
fn lex_reports_how_much_of_the_slice_it_used() {
let (tokens, used) = lex("wire a;\n");
assert!(!tokens.is_empty());
assert_eq!(used, 8);
let (tokens, used) = lex("wire a;\n/* open");
assert!(!tokens.is_empty());
assert_eq!(used, 8, "the comment line was dropped");
}
#[test]
fn line_start_counts_lines_from_one() {
assert_eq!(line_start("a\nb\nc", 1), Some(0));
assert_eq!(line_start("a\nb\nc", 2), Some(2));
assert_eq!(line_start("a\nb\nc", 3), Some(4));
assert_eq!(line_start("a\nb\nc", 4), None);
}
// ------------------------------------------------------------------
// definition and references
// ------------------------------------------------------------------
const NETLIST: &str = "module top;\n wire sig_a;\n wire sig_b;\n sub u0 (.a(sig_a), \
.b(sig_b));\n assign sig_a = sig_b;\nendmodule\n";
/// The offset of the `n`-th occurrence of `needle`.
fn at(text: &str, needle: &str, n: usize) -> u32 {
text.match_indices(needle).nth(n).expect("occurrence").0 as u32
}
#[test]
fn a_declaration_is_found_by_the_keyword_before_it() {
let doc = large(NETLIST);
let found = definition(&doc, at(NETLIST, "sig_a", 2)).expect("a declaration");
assert_eq!(found.start, at(NETLIST, "sig_a", 0), "the `wire sig_a;` line");
assert_eq!(&NETLIST[found.as_range()], "sig_a");
}
#[test]
fn a_name_no_keyword_introduces_has_no_definition() {
let doc = large(NETLIST);
assert!(definition(&doc, at(NETLIST, "u0", 0)).is_none(), "an instance name");
}
#[test]
fn a_cursor_that_is_not_on_a_word_answers_nothing() {
let doc = large(NETLIST);
let space = NETLIST.find(" wire").expect("indent") as u32;
assert!(definition(&doc, space).is_none());
assert!(references(&doc, space, true).is_empty());
}
#[test]
fn references_are_whole_word_and_in_order() {
let doc = large(NETLIST);
let found = references(&doc, at(NETLIST, "sig_a", 0), true);
assert_eq!(found.len(), 3, "declaration, connection, assignment");
assert!(found.windows(2).all(|pair| pair[0].start < pair[1].start));
// `sig_a` is not found inside `sig_ab`.
let doc = large("wire sig_ab;\nwire sig_a;\n");
assert_eq!(references(&doc, at(&doc.text, "sig_a", 1), true).len(), 1);
}
#[test]
fn excluding_the_declaration_drops_exactly_the_declaration() {
let doc = large(NETLIST);
let with = references(&doc, at(NETLIST, "sig_a", 1), true);
let without = references(&doc, at(NETLIST, "sig_a", 1), false);
assert_eq!(without.len(), with.len() - 1);
assert!(!without.contains(&with[0]));
}
#[test]
fn the_reference_list_is_capped() {
let text = format!("wire sig;\n{}", "assign x = sig;\n".repeat(REFERENCE_LIMIT + 500));
let doc = large(&text);
assert_eq!(references(&doc, 5, true).len(), REFERENCE_LIMIT);
}
// ------------------------------------------------------------------
// the 100 MB probes
// ------------------------------------------------------------------
/// A netlist-shaped buffer of about `bytes` bytes.
///
/// Instantiation lines, which is what a synthesized netlist really is, with
/// a declaration and a comment every so often so the scans have something
/// to find and the windows have something to colour.
fn netlist(bytes: usize) -> String {
let mut text = String::with_capacity(bytes + 4096);
text.push_str("module netlist_top;\n wire needle;\n");
let mut n = 0u64;
while text.len() < bytes {
text.push_str(&format!(
" sky130_fd_sc_hd__inv_2 _{n}_ (.A(net{n}), .Y(net{}));\n",
n + 1
));
if n.is_multiple_of(500) {
text.push_str(" /* a banner comment, so the windows are not all code */\n");
text.push_str(" wire net_local;\n");
}
n += 1;
}
// A second declaration at the far end: a scan for it is the worst
// case, since the answer is the last thing in the file.
text.push_str(" wire tail_needle;\nendmodule\n");
text
}
/// **The measurement the feature README quotes.** Ignored by default: it
/// builds a 100 MB buffer, which is not something `cargo test` should do
/// on every run. Run it as
/// `cargo test -p lucisv_server --release -- --ignored --nocapture
/// large::tests::the_hundred_megabyte_probes`.
///
/// The bounds asserted are deliberately loose — an order of magnitude over
/// what the numbers actually are on the machine this was written on — so
/// the probe fails on a regression in *kind* (someone made the open path
/// scan the file twice, someone made the window lex the document) rather
/// than on a slow CI box.
#[test]
#[ignore = "synthesizes a 100 MB buffer; run with --release --ignored --nocapture"]
fn the_hundred_megabyte_probes() {
use std::time::Instant;
let text = netlist(100 * 1024 * 1024);
let bytes = text.len();
let clock = Instant::now();
let doc = Document::large(Some(PathBuf::from("/rtl/netlist.v")), text);
let open = clock.elapsed();
let lines = doc.line_index.line_count();
let middle = lines / 2;
let viewport = Range {
start: Position { line: middle, character: 0 },
end: Position { line: middle + 60, character: 0 },
};
// Twice: the first call is where any accidental one-off whole-file
// work would hide.
let clock = Instant::now();
let first = window(&doc, viewport);
let first_window = clock.elapsed();
let clock = Instant::now();
let again = window(&doc, viewport);
let second_window = clock.elapsed();
assert_eq!(first.tokens.len(), again.tokens.len());
assert!(!first.tokens.is_empty(), "the window really did lex something");
// The worst case for both scans: the name is declared in the *last*
// line of the file, so the answer is only found after a whole pass.
let tail = doc.text.rfind("tail_needle").expect("the tail declaration") as u32;
let clock = Instant::now();
let found = definition(&doc, tail);
let definition_scan = clock.elapsed();
assert!(found.is_some());
let clock = Instant::now();
let refs = references(&doc, tail, true);
let reference_scan = clock.elapsed();
assert!(!refs.is_empty());
// And the shape that is worst for the search itself: a short name
// that occurs as a *prefix* of a million others, so the whole-word
// filter runs on every one of them.
let common = doc.text.find("net1)").expect("a net use") as u32;
let clock = Instant::now();
let many = references(&doc, common, true);
let capped_scan = clock.elapsed();
eprintln!(
"100 MB probe: {bytes} bytes, {lines} lines\n \
open (line index only): {open:?}\n \
semanticTokens/range window (60 lines): {first_window:?} then {second_window:?}\n \
definition scan (declared in the last line): {definition_scan:?}\n \
references scan (2 hits, whole file): {reference_scan:?}\n \
references scan (short name, {} hits among a million prefixes): {capped_scan:?}",
many.len()
);
assert!(open.as_millis() < 5_000, "opening cost {open:?}");
assert!(first_window.as_millis() < 200, "the first window cost {first_window:?}");
assert!(second_window.as_millis() < 200, "the second window cost {second_window:?}");
assert!(
definition_scan.as_millis() < 1_000,
"the definition scan cost {definition_scan:?}"
);
assert!(reference_scan.as_millis() < 1_000, "the reference scan cost {reference_scan:?}");
assert!(capped_scan.as_millis() < 1_000, "the worst-case scan cost {capped_scan:?}");
}
/// What the fast path is worth, measured rather than asserted: the same
/// buffer through [`Document::new`] and through [`Document::large`].
///
/// Ten megabytes rather than a hundred, because the point is the *ratio*
/// and because a 100 MB full analysis is minutes and gigabytes — which is
/// itself the finding, and is why the threshold exists.
#[test]
#[ignore = "analyzes a 10 MB buffer in full; run with --release --ignored --nocapture"]
fn the_full_pipeline_probe_says_what_the_fast_path_saves() {
use std::time::Instant;
let text = netlist(10 * 1024 * 1024);
let clock = Instant::now();
let fast = Document::large(None, text.clone());
let fast_open = clock.elapsed();
let clock = Instant::now();
let full = Document::new(None, text, &vlog_semantic::WorkspaceIndex::default());
let full_open = clock.elapsed();
eprintln!(
"10 MB open: fast path {fast_open:?} ({} tokens), full pipeline {full_open:?} \
({} tokens) — {:.0}x",
fast.tokens.len(),
full.tokens.len(),
full_open.as_secs_f64() / fast_open.as_secs_f64().max(f64::MIN_POSITIVE)
);
assert!(fast_open < full_open, "the fast path is the fast one");
}
#[test]
fn every_declarator_is_a_real_keyword() {
for word in DECLARATORS {
assert!(
vlog_parser::KEYWORDS.contains(&word),
"{word} is not a keyword the lexer knows"
);
}
}
/// **QA finding 1 (2026-08-27), fixed and now a gate.** A single line far
/// longer than [`BACKSCAN`], packed with thousands of short tokens rather
/// than one long one — a wide bus concatenation or a one-line generated
/// port list, both ordinary netlist shapes. `window()` itself only ever
/// touches [`MAX_WINDOW`] bytes, so the *lexer* side was always bounded by
/// construction. But colouring the window also converts every token's byte
/// span to a UTF-16 LSP position (`tokens::flatten`), and that conversion
/// used to scan from the **start of the token's line** every time: on an
/// ordinary file a few dozen bytes of work, on a window that is all one
/// line O(line length) per token, i.e. **O(tokens²)**. Measured at
/// 107.8 ms → 439.3 ms → 1.85 s → **7.86 s** across the four sizes below
/// (release) — 4x the time for 2x the tokens, the signature of a quadratic
/// wall rather than the "bounded, however big the file is" cost the
/// feature README promises.
///
/// `tokens::flatten` now converts through `Positions::walker`
/// (`convert.rs`), which measures each line once however many offsets fall
/// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for
/// 2x, and 596x faster at the top.
///
/// The bound is wall-clock, loose, and in debug (this test runs in the
/// normal suite): ~4x the measured debug cost of the largest size, which
/// the quadratic version overshoots by more than two orders of magnitude.
/// A regression in *kind* fails it; a slow CI box does not.
#[test]
fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() {
use std::time::Instant;
for count in [5_000u32, 10_000, 20_000, 40_000] {
// One line: `module m; wire a0,a1,...,last;` — realistic in shape
// (a wide declaration), synthetic only in how wide.
let mut text = String::from("module m; wire ");
for n in 0..count {
text.push_str(&format!("a{n},"));
}
text.push_str("last;\nendmodule\n");
let doc = large(&text);
let clock = Instant::now();
let window = window(&doc, range(0, 1));
let lex_elapsed = clock.elapsed();
assert!(!window.tokens.is_empty());
let clock2 = Instant::now();
let data = crate::tokens::semantic_tokens_in_window(&doc, range(0, 1));
let colour_elapsed = clock2.elapsed();
eprintln!(
"{count} tokens, {}-byte line: lex {lex_elapsed:?}, colour {colour_elapsed:?}, \
{} tokens answered",
text.len(),
data.len() / 5
);
assert!(!data.is_empty(), "the window really did colour something");
assert!(
colour_elapsed.as_millis() < COLOUR_BUDGET_MS,
"colouring {count} tokens on one line cost {colour_elapsed:?} — \
the quadratic conversion is back"
);
}
}
/// The wall-clock ceiling the test above holds the colourer to, in a
/// **debug** build: 4.5x the slowest of the four sizes as measured on the
/// machine this was written on (77 ms at 40,000 tokens, ±0.5 ms over
/// four runs), where the quadratic version this replaced would need tens
/// of seconds.
const COLOUR_BUDGET_MS: u128 = 350;
/// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other*
/// fast-path consumer of `Positions`: `references`' hits still have to
/// become `lsp_types::Location`s (`Server::large_scan`, `server.rs`), one
/// `Positions::range` each. `large::references` itself was always linear;
/// the wall was entirely in turning up to [`REFERENCE_LIMIT`] hits on one
/// gigantic line into positions — 206 ms → 789 ms → 3.15 s → **12.6 s**
/// for 100 → 800 hits (release), against a scan of 0.9 → 6.4 ms.
///
/// `large_scan` now walks the hits with one `Positions::walker`, which
/// they are already in ascending order for. This runs at an eighth of the
/// original probe's line lengths so it can live in the normal suite; the
/// bound is debug wall-clock and ~4x the measured cost, which a return of
/// the per-hit rescan overshoots by two orders of magnitude.
#[test]
fn references_on_one_giant_line_locate_their_hits_in_linear_time() {
use std::time::Instant;
for width in [100u32, 200, 400, 800] {
// One line: `wire sig;` filler `sig` filler `sig` ... — `width`
// occurrences of the needle spread over one line, all comfortably
// under REFERENCE_LIMIT so the cap is not what is being timed.
let mut text = String::from("wire sig;");
for _ in 0..width {
text.push_str(&" filler_word ".repeat(250));
text.push_str("sig");
}
text.push('\n');
let doc = large(&text);
let clock = Instant::now();
let hits = references(&doc, 5, true);
let scan_elapsed = clock.elapsed();
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
let positions = doc.positions();
let clock2 = Instant::now();
// Exactly what `Server::large_scan` does with them.
let mut walker = positions.walker();
for hit in &hits {
std::hint::black_box(walker.range(*hit));
}
let locate_elapsed = clock2.elapsed();
eprintln!(
"{width} hits on one {}-byte line: scan {scan_elapsed:?}, locate {locate_elapsed:?}",
text.len()
);
assert!(
locate_elapsed.as_millis() < LOCATE_BUDGET_MS,
"locating {width} hits on one line cost {locate_elapsed:?} — \
the per-hit line rescan is back"
);
}
}
/// The wall-clock ceiling for the locator above, in a **debug** build:
/// 4.7x the slowest of the four sizes as measured on the machine this was
/// written on (32 ms at 800 hits on a 2.6 MB line, ±0.2 ms over four
/// runs).
const LOCATE_BUDGET_MS: u128 = 150;
}
+79 -15
View File
@@ -25,8 +25,10 @@
use lsp_types::{CodeLens, Command, Location, Uri};
use serde_json::Value;
use vlog_semantic::instantiations;
use crate::hierarchy;
use crate::state::Workspace;
use crate::{hierarchy, instantiations};
/// Show every instantiation of a module: `[module-name]`.
pub const SHOW_INSTANTIATIONS: &str = "lucisv.showInstantiations";
@@ -179,7 +181,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -505,7 +507,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
let lenses = code_lenses(&ws, &uri).expect("open");
@@ -567,7 +569,7 @@ endmodule
tree_b.write("a/m.sv", m_a);
let path_b = tree_b.write("b/m.sv", m_b);
tree_b.write("top.sv", user);
ws_b.open_roots(vec![tree_b.path.clone()]);
ws_b.open_whole_workspace(vec![tree_b.path.clone()]);
let uri_b = path_to_uri(&path_b).expect("uri");
ws_b.set_document(uri_b.clone(), m_b.to_string());
assert_eq!(
@@ -639,17 +641,73 @@ endmodule
// the performance claim, measured
// ------------------------------------------------------------------
/// What a whole file's lenses cost over the real corpus, and — the point
/// of the batch — that asking about three modules at once costs about what
/// asking about one does, not three times as much.
/// The number the round's Handshake was filed for, measured: what a whole
/// file's lenses cost before the edge table (a walk of every in-scope
/// file, re-read and re-parsed) and what they cost after (a lookup).
///
/// `#[ignore]`d like the other measurement probes in this crate — it prints
/// a number rather than asserting one, and the assertion that must hold is
/// `code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk`
/// above. Run with `cargo test -p lucisv_server -- --ignored --nocapture`.
#[test]
#[ignore]
fn qa_perf_lens_lookup_against_the_walk_it_replaced() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
let Ok(text) = fs::read_to_string(&file) else {
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
return;
};
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
let _ = code_lenses(&ws, &uri);
let mut lenses = std::time::Duration::ZERO;
let mut walk = std::time::Duration::ZERO;
for _ in 0..3 {
let started = std::time::Instant::now();
let _ = code_lenses(&ws, &uri).expect("open");
lenses = lenses.max(started.elapsed());
// What `callers_of_each` used to begin with, every request.
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.max(started.elapsed());
}
eprintln!(
"codeLens over {} files: {lenses:?} for the whole file; one workspace walk \
(what the old census re-read on every request) is {walk:?}",
ws.index().files().len()
);
}
/// What a whole file's lenses cost over the real corpus, against what one
/// workspace walk costs.
///
/// **Superseded this round (incremental-index, 2026-08-27):**
/// `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted
/// `whole_file < one_name * 2` — that asking about three modules cost about
/// what asking about one did, because both were *one walk* of the whole
/// workspace. There is no walk any more: the count is a lookup in the
/// index's instantiation-edge table, and the only I/O left is reading the
/// handful of files that really do instantiate one of the three. Both sides
/// of that ratio are now microseconds dominated by a file read each, so the
/// ratio pins noise. The property worth pinning is the stronger one this
/// round bought: **a whole file's lenses cost a small fraction of one
/// workspace walk**, measured here rather than asserted.
///
/// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`),
/// like the other corpus tests. The budget is deliberately loose: a debug
/// build on a loaded machine is the worst case this ever runs in, and this
/// exists to catch an order-of-magnitude regression — a lens handler that
/// re-read the workspace once per declaration would fail the ratio.
/// went back to re-reading the workspace would fail it by two.
#[test]
fn code_lenses_for_a_whole_file_cost_about_one_workspace_walk() {
fn code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
@@ -663,14 +721,17 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
// Warm, then the worst of three, for the whole file and for one name.
// Warm, then the worst of three, for the whole file and for one name;
// and the best of three for the walk it used to be, so the comparison
// is stacked against the claim rather than for it.
let _ = code_lenses(&ws, &uri);
let mut whole_file = std::time::Duration::ZERO;
let mut one_name = std::time::Duration::ZERO;
let mut walk = std::time::Duration::MAX;
let mut count = 0;
for _ in 0..3 {
let started = std::time::Instant::now();
@@ -680,18 +741,21 @@ endmodule
let started = std::time::Instant::now();
let _ = sites_of(&ws, "cdc_fifo_gray");
one_name = one_name.max(started.elapsed());
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.min(started.elapsed());
}
eprintln!(
"corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \
(one name alone: {one_name:?})",
(one name alone: {one_name:?}; one workspace walk: {walk:?})",
ws.index().files().len(),
);
assert!(count >= 3, "the file declares three modules: {count}");
assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}");
assert!(
whole_file < one_name * 2,
"the batch is one walk, not one per module: {count} names cost {whole_file:?} \
against {one_name:?} for one"
whole_file * 10 < walk,
"the lens is a lookup, not a walk: {count} names cost {whole_file:?} against \
{walk:?} for one walk of the workspace"
);
}
}
+44 -2
View File
@@ -18,9 +18,10 @@ mod format;
mod hierarchy;
mod hover;
mod includes;
mod index_cache;
mod inlay;
mod inline;
mod instantiations;
mod large;
mod lens;
mod linked;
mod lint;
@@ -72,6 +73,10 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// capabilities have no field for it and drop it on the floor — see
// `ranges_formatting_support`.
let ranges_formatting = ranges_formatting_support(&params);
// Read from the raw params for the same reason, and because it is not a
// capability at all: `initializationOptions` is whatever the client's
// extension put there.
let storage = storage_path(&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();
@@ -85,10 +90,11 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
code_lens_refresh: code_lens_refresh_support(&params),
show_document: show_document_support(&params),
configuration: configuration_support(&params),
token_server_cancel: token_server_cancel_support(&params),
};
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
Server::new(connection, roots, abilities).run()?;
Server::new(connection, roots, abilities, storage).run()?;
io_threads.join()?;
Ok(())
}
@@ -374,6 +380,22 @@ fn ranges_formatting_support(params: &serde_json::Value) -> bool {
params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true
}
/// The folder the client set aside for this workspace's server state —
/// `initializationOptions.storagePath`, which the VS Code extension fills in
/// with `context.storageUri`.
///
/// The persistent index cache goes here when there is one: it is
/// per-workspace, the editor cleans it up when the workspace is forgotten,
/// and it needs no guess about where this platform keeps caches. A client
/// that sends nothing — every client but ours, and ours before this — leaves
/// the OS cache directory to decide
/// (`docs/features/index-persistence/README.md`). A blank value counts as
/// unset, the same reading `lucisv.serverPath` gives a blank setting.
fn storage_path(params: &serde_json::Value) -> Option<PathBuf> {
let path = params["initializationOptions"]["storagePath"].as_str()?;
(!path.trim().is_empty()).then(|| PathBuf::from(path))
}
/// 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
@@ -404,6 +426,26 @@ fn apply_edit_support(params: &InitializeParams) -> bool {
.unwrap_or(false)
}
/// Whether the client lets the *server* cancel a semantic-tokens request —
/// `textDocument.semanticTokens.serverCancelSupport`.
///
/// The large-file fast path declines `semanticTokens/full`, and this decides
/// with which error code: `ServerCancelled` for a client that says it
/// understands one (the spec restricts that code to requests "that explicitly
/// support being server cancellable", and this capability is how a client
/// says so), `ContentModified` for one that does not. Both leave
/// `vscode-languageclient` throwing a `CancellationError`, which is what keeps
/// the range provider alive — see
/// `docs/features/large-file-mode/README.md`.
fn token_server_cancel_support(params: &InitializeParams) -> bool {
params.capabilities.text_document.as_ref().is_some_and(|text_document| {
text_document
.semantic_tokens
.as_ref()
.is_some_and(|tokens| tokens.server_cancel_support == Some(true))
})
}
/// Whether the client pulls diagnostics (LSP 3.17).
///
/// Sending the capability at all is what says so; its two fields are about
+265 -31
View File
@@ -2,9 +2,10 @@
//! `textDocument/documentHighlight`.
use lsp_types::{DocumentHighlight, DocumentHighlightKind, Location, Uri};
use vlog_parser::TextRange;
use vlog_semantic::{Definition, Semantics, SymbolId};
use vlog_parser::{LineIndex, TextRange};
use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId};
use crate::convert::Positions;
use crate::includes;
use crate::locate::location;
use crate::state::{Document, Workspace};
@@ -58,17 +59,11 @@ fn path_to_uri_or_self(ws: &Workspace, uri: &Uri) -> Option<Uri> {
/// Find-all-references, across the workspace when the symbol can leave this
/// file and inside it when it cannot.
///
/// The two paths answer the same question at very different prices: the
/// in-file answer is a lookup in an analysis the buffer already carries, and
/// the workspace answer re-reads and re-analyzes every in-scope file. So the
/// gate below is asked first, and it is asked of the *index* — a name it does
/// not hold as a unit or as an exported member cannot be named from another
/// file, so a local `wire` never starts a workspace walk.
///
/// The cross-file collection is `vlog_refactor`'s, the same one a rename runs
/// (`docs/features/references-nav/README.md`). When it declines — an
/// ambiguous name, a use nothing resolves — the file's own answer is sent
/// rather than an error: a highlight the editor can draw beats a shrug.
/// The cross-file path is an in-memory declaration-to-occurrence lookup in the
/// workspace index. Open buffers overlay their live semantics on those saved
/// postings, so unsaved additions and deletions remain visible without a
/// project scan. When the index declines an ambiguous target, the file's own
/// answer is sent rather than an error.
pub fn references(
ws: &Workspace,
uri: &Uri,
@@ -77,8 +72,10 @@ pub fn references(
) -> Vec<Location> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
if leaves_this_file(ws, doc, offset) {
if let Some(locations) = workspace_references(ws, doc, offset, include_declaration) {
return locations;
if let Some(target) = indexed_target(ws, doc, offset) {
if let Some(locations) = indexed_references(ws, target, include_declaration) {
return locations;
}
}
}
in_file_references(ws, doc, uri, offset, include_declaration)
@@ -120,17 +117,164 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool {
}
}
/// The workspace-wide answer, or `None` when the engine declined it.
fn workspace_references(
ws: &Workspace,
#[derive(Clone)]
struct IndexedTarget {
def: Def,
name: String,
declaration_path: std::path::PathBuf,
declaration_span: TextRange,
}
/// Map the live cursor answer onto the stable declaration held by this index.
fn indexed_target(ws: &Workspace, doc: &Document, offset: u32) -> Option<IndexedTarget> {
match doc.external.definition_of(&doc.semantics, offset)? {
Definition::Local(symbol) => {
let def = indexed_def_for_symbol(ws, doc, symbol)?.clone();
let declaration_path = doc.path.clone()?;
Some(IndexedTarget {
def,
name: symbol.name.clone(),
declaration_path,
declaration_span: symbol.name_span,
})
}
Definition::External([def]) => {
let id = doc.semantics.reference_id_at(offset)?;
let name = doc.semantics.reference(id)?.name.clone();
let declaration_path = ws.index().path(def.file)?.to_path_buf();
Some(IndexedTarget {
def: def.clone(),
name,
declaration_path,
declaration_span: def.name_span,
})
}
Definition::External(_) => None,
}
}
/// The indexed declaration represented by one live single-file symbol.
///
/// Matching is logical (path, owner, name and kind), not positional: edits
/// above a declaration may move its live span before the next save.
fn indexed_def_for_symbol<'a>(
ws: &'a Workspace,
doc: &Document,
offset: u32,
symbol: &Symbol,
) -> Option<&'a Def> {
let path = doc.path.as_deref()?;
let file = ws.index().file_id(path)?;
let defs = if symbol.scope == doc.semantics.file_scope() {
ws.index().units(&symbol.name)
} else {
let owner = doc
.semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| doc.semantics.symbol(owner))?;
ws.index().member(&owner.name, &symbol.name)
};
if defs.len() != 1 {
return None;
}
defs.first().filter(|def| def.file == file && def.kind == symbol.kind)
}
/// The project-wide answer from persisted postings, overlaid by every live
/// buffer. `None` preserves the old ambiguity contract and lets the caller
/// degrade to its single-file answer.
fn indexed_references(
ws: &Workspace,
target: IndexedTarget,
include_declaration: bool,
) -> Option<Vec<Location>> {
let path = doc.path.clone()?;
let found =
vlog_refactor::find_references(&ws.sources(), &path, offset, include_declaration).ok()?;
Some(found.iter().filter_map(|(path, span)| location(ws, path, *span)).collect())
if ws.index().references_are_ambiguous(&target.def) {
return None;
}
let mut found = Vec::new();
for site in ws.index().references_to(&target.def) {
let path = ws.index().path(site.file)?;
if ws.document_for_path(path).is_none() {
found.push((path.to_path_buf(), site.name_span));
}
}
for (_, doc) in ws.open_documents() {
let Some(path) = doc.path.as_ref() else { continue };
for (id, reference) in doc.semantics.references().iter().enumerate() {
let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) {
Some(symbol) => indexed_def_for_symbol(ws, doc, symbol) == 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) => {
return None;
}
_ => false,
},
};
if matches && !reference.name_span.is_empty() {
found.push((path.clone(), reference.name_span));
}
}
}
if include_declaration {
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)
})
})
.unwrap_or(target.declaration_span);
found.push((target.declaration_path, span));
}
Some(locations(ws, found))
}
/// Convert all occurrences in one file with one text fetch and one line
/// index, rather than repeating both operations for every location.
fn locations(ws: &Workspace, mut found: Vec<(std::path::PathBuf, TextRange)>) -> Vec<Location> {
found.retain(|(_, span)| !span.is_empty());
found.sort_by(|(a_path, a_span), (b_path, b_span)| {
(a_path, a_span.start, a_span.end).cmp(&(b_path, b_span.start, b_span.end))
});
found.dedup();
let mut out = Vec::with_capacity(found.len());
let mut start = 0;
while start < found.len() {
let path = &found[start].0;
let end = found[start..].partition_point(|(candidate, _)| candidate == path) + start;
let Some(uri) = path_to_uri(path) else {
start = end;
continue;
};
if let Some(doc) = ws.document_for_path(path) {
let positions = doc.positions();
let mut walker = positions.walker();
out.extend(
found[start..end]
.iter()
.map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }),
);
} else if let Some(text) = ws.text_of(path) {
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let mut walker = positions.walker();
out.extend(
found[start..end]
.iter()
.map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }),
);
}
start = end;
}
out
}
/// The file's own answer: what `Semantics` alone knows about this symbol.
@@ -309,7 +453,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
@@ -333,7 +477,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
@@ -355,7 +499,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
@@ -386,7 +530,7 @@ mod tests {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let path = dir.join(which);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -439,6 +583,67 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn indexed_references_equal_the_refactor_walk_they_replace() {
let (dir, ws, uri) = instantiated("xrefs_equivalence", "top.sv");
let offset = at(TOP, "sub u_b");
let indexed = references(&ws, &uri, offset, true);
let path = dir.join("top.sv");
let walked = vlog_refactor::find_references(&ws.sources(), &path, offset, true)
.expect("the existing refactor walk answers");
let walked = locations(&ws, walked);
assert_eq!(indexed, walked);
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "manual indexed-navigation latency probe"]
fn qa_indexed_references_latency_over_a_large_workspace() {
let dir = temp_dir("xrefs_latency");
let sub_path = dir.join("sub.sv");
fs::write(&sub_path, SUB).expect("write declaration");
for i in 0..4 {
fs::write(
dir.join(format!("use_{i}.sv")),
format!("module use_{i}; sub u (); endmodule\n"),
)
.expect("write use");
}
for i in 0..815 {
fs::write(
dir.join(format!("unrelated_{i}.sv")),
format!("module unrelated_{i}; logic signal_{i}; endmodule\n"),
)
.expect("write unrelated source");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&sub_path).expect("uri");
ws.set_document(uri.clone(), SUB.to_string());
assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5);
let requests = 200;
let start = std::time::Instant::now();
for _ in 0..requests {
assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5);
}
let indexed = start.elapsed();
let start = std::time::Instant::now();
let walked = vlog_refactor::find_references(&ws.sources(), &sub_path, at(SUB, "sub"), true)
.expect("old walk");
let old = start.elapsed();
assert_eq!(walked.len(), 5);
eprintln!(
"indexed references: {:.3} ms/request over 820 files; old walk: {:.3} ms/request",
indexed.as_secs_f64() * 1_000.0 / f64::from(requests),
old.as_secs_f64() * 1_000.0,
);
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");
@@ -460,7 +665,7 @@ mod tests {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&dir.join("p.sv")).expect("uri");
ws.set_document(uri.clone(), pkg.to_string());
@@ -489,7 +694,7 @@ mod tests {
fs::write(dir.join("m.sv"), text).expect("write");
fs::write(dir.join("other.sv"), "module other;\n wire a;\nendmodule\n").expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&dir.join("m.sv")).expect("uri");
ws.set_document(uri.clone(), text.to_string());
let doc = ws.document(&uri).expect("open");
@@ -517,7 +722,7 @@ mod tests {
fs::write(dir.join("a.sv"), text).expect("write");
fs::write(dir.join("b.sv"), text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let a_path = dir.join("a.sv");
let uri = path_to_uri(&a_path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -546,6 +751,35 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() {
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv");
let edited = "module top;\n\n sub only_now ();\nendmodule\n";
ws.set_document(uri.clone(), edited.to_string());
let found = references(&ws, &uri, at(edited, "sub only_now"), false);
assert_eq!(
places(&found),
vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 2)],
"the new live use replaces both saved top.sv uses"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_unsaved_declaration_move_is_reported_at_its_live_span() {
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_decl", "sub.sv");
let edited = "// moved down\n\nmodule sub (input logic clk);\nendmodule\n";
ws.set_document(uri.clone(), edited.to_string());
let found = references(&ws, &uri, at(edited, "module sub") + 7, true);
assert!(
places(&found).contains(&("sub.sv".to_string(), 2)),
"the declaration comes from the live buffer, not its saved offset"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_untitled_buffer_still_answers_from_itself() {
// No path means no place in the index and nothing to hand the engine,
@@ -615,7 +849,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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());
+2 -2
View File
@@ -244,7 +244,7 @@ mod tests {
let sub = tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let top_uri = path_to_uri(&top).expect("uri");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(top_uri.clone(), TOP.to_string());
@@ -323,7 +323,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", text);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), text.to_string());
let arguments = vec![
+3 -3
View File
@@ -122,7 +122,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
(ws, uri)
@@ -194,7 +194,7 @@ mod tests {
let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n";
let file = tree.write("m.sv", text);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -212,7 +212,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top_path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
// The buffer instantiates `sub`; the file on disk does not.
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
File diff suppressed because it is too large. Load diff
+311 -3
View File
@@ -28,6 +28,39 @@ use serde_json::Value;
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
/// `lucisv.index.maxFileSize`'s default: 1 MiB. A source file bigger than this
/// is almost always a generated netlist or a dumped trace, which costs minutes
/// to index and answers nothing a user asked. `0` means no cap; see
/// `docs/features/indexing-ux/README.md`.
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;
/// `lucisv.largeFile.threshold`'s default: 4 MiB. A buffer bigger than this is
/// opened on the fast path — line index only, no lex, no parse, no index — and
/// coloured a viewport at a time. `0` turns the fast path off, so every buffer
/// is analyzed in full however big it is; see
/// `docs/features/large-file-mode/README.md`.
pub const DEFAULT_LARGE_FILE_THRESHOLD: u64 = 4 * 1024 * 1024;
/// What `lucisv.index.scope` chooses: how wide the workspace walk goes.
///
/// The default is deliberately the narrow one. A large project is the case
/// worth optimising for, and in it the files a user is working with are the
/// ones beside the file they opened; walking every workspace folder to answer
/// a question about one folder is minutes of work nobody asked for. See
/// `docs/features/index-scope/README.md` for what the narrow scope costs,
/// which is cross-folder answers until the scope reaches the other folder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IndexScope {
/// The open buffers' own folders, each raised
/// [`ClientSettings::index_scope_depth`] levels, walked.
#[default]
Folder,
/// Every workspace folder, walked whole — what the server did before
/// 2026-08-27, and what a user with a small project or a big machine can
/// ask for back.
Workspace,
}
/// The configuration section these settings live in — the key a push nests
/// them under, and the `section` a pull asks for. One constant, because the
/// two must name the same thing or the pull would answer settings the parser
@@ -36,8 +69,11 @@ pub const SECTION: &str = "lucisv";
/// The `lucisv.*` settings in force, after validation. Every field is "no
/// opinion" until a client says otherwise, which is exactly what an unset
/// VS Code setting means.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
/// VS Code setting means — except the two whose own default is not silence
/// (`index.maxFileSize`, `index.logFiles`), which resolve to it here so no
/// use site has to remember what "unset" meant. See the hand-written
/// [`Default`] below.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSettings {
/// `lucisv.lineLength`.
pub line_length: Option<usize>,
@@ -60,6 +96,72 @@ pub struct ClientSettings {
/// also formatted would format twice. See
/// `docs/features/will-save-wait-until/README.md`.
pub format_on_save: bool,
/// `lucisv.index.maxFileSize`: the largest *walked* file, in bytes, that
/// the workspace index will read. `0` is no cap. An open buffer is
/// indexed whatever its size — the user opened it deliberately. Defaults
/// to [`DEFAULT_MAX_FILE_SIZE`] rather than to 0, so a plain
/// `ClientSettings::default()` is the capped behaviour the server ships
/// with.
pub max_file_size: u64,
/// `lucisv.index.logFiles`: whether each file the index reads is named in
/// a `window/logMessage`, and each oversized one in a skip line. On
/// unless a client says otherwise — the Output panel it lands in is
/// hidden until somebody opens it.
pub log_files: bool,
/// `lucisv.index.scope`: whether the walk covers the open files' folders
/// or every workspace folder. Defaults to [`IndexScope::Folder`], which
/// is a narrower index than the server built before 2026-08-27 — see
/// `docs/features/index-scope/README.md`.
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.
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.
/// On unless a client says otherwise — a half-finished scan that has to
/// start again from zero is the thing this exists to prevent. Off means
/// off in both directions: nothing is read and nothing is written
/// (`docs/features/index-persistence/README.md`).
pub index_persist: bool,
/// `lucisv.index.cachePath`: where that store lives, absolute or relative
/// to the first workspace root. Empty means "unset", and then the
/// editor's own storage folder — or this platform's cache directory —
/// decides; see `index_cache::cache_dir` for the ladder.
pub index_cache_path: Option<String>,
/// `lucisv.largeFile.threshold`: the size in bytes above which an **open
/// buffer** is served by the fast path instead of being analyzed. `0`
/// disables the fast path. Unlike `index.maxFileSize`, which is about
/// files on disk that nobody asked for, this one is about the file on
/// screen — see `docs/features/large-file-mode/README.md`.
pub large_file_threshold: u64,
}
/// The settings a client that said nothing is treated as having asked for.
///
/// Hand-written because two of them do not default to silence: the size cap
/// is on at 1 MiB and the file log is on. Every other field is its type's own
/// zero, exactly as the derive produced.
impl Default for ClientSettings {
fn default() -> ClientSettings {
ClientSettings {
line_length: None,
indent: None,
exclude: Vec::new(),
filelist: None,
inline_templates: None,
format_on_save: false,
max_file_size: DEFAULT_MAX_FILE_SIZE,
log_files: true,
index_scope: IndexScope::Folder,
index_scope_depth: 0,
index_persist: true,
index_cache_path: None,
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
}
}
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
@@ -78,6 +180,15 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// the section (including the `{"settings": null}` a client sends when it
// syncs no section at all) means "no opinion about anything".
let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() };
// `lucisv.index.maxFileSize` is a dotted id, and both doors nest it: VS
// Code's settings model turns every segment into an object, so the section
// arrives as `{"index": {"maxFileSize": …}}`. An `index` that is missing —
// or is not an object at all — leaves both of its keys at their defaults,
// which is what `Value::get` on a non-object already returns.
let index = lucisv.get("index");
// `lucisv.largeFile.threshold` nests exactly as `index.*` does, for the
// same reason: VS Code turns every dotted segment into an object.
let large_file = lucisv.get("largeFile");
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
@@ -88,6 +199,44 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// values included: the safe direction for a setting that rewrites the
// user's buffer on every save is the one that does nothing.
format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false),
// The safe direction for these two is the shipped default, not zero:
// a wrong-typed cap that read as `0` would index the netlist the
// setting exists to skip.
max_file_size: count(index.and_then(|i| i.get("maxFileSize")))
.unwrap_or(DEFAULT_MAX_FILE_SIZE),
log_files: flag(index.and_then(|i| i.get("logFiles"))).unwrap_or(true),
// An unreadable scope leaves the narrow default standing, for the
// same reason a junk cap leaves the cap on: the direction that
// 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 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
// a cache that is on can only ever cost a file's parse, because every
// hit is verified against the file's own bytes.
index_persist: flag(index.and_then(|i| i.get("persist"))).unwrap_or(true),
index_cache_path: path(index.and_then(|i| i.get("cachePath"))),
// The safe direction again: a wrong-typed threshold leaves the fast
// path armed at its default. A junk value that read as `0` would turn
// it off, and the first 100 MB netlist opened after that would hang
// the editor for minutes — which is the whole thing this exists to
// prevent.
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
/// case and all — because the enum in `package.json` is what a settings UI
/// offers, and forgiving `"Workspace"` here would make a typo mean something
/// on one client and nothing on another.
fn scope(value: Option<&Value>) -> Option<IndexScope> {
match value?.as_str()? {
"folder" => Some(IndexScope::Folder),
"workspace" => Some(IndexScope::Workspace),
_ => None,
}
}
@@ -151,6 +300,16 @@ fn bounded(value: Option<&Value>, range: RangeInclusive<u64>) -> Option<usize> {
range.contains(&number).then_some(number as usize)
}
/// A JSON count — any unsigned integer, `0` included — or nothing.
///
/// Unbounded on purpose: there is no size a cap may not take, and a cap larger
/// than any file on disk is the same as no cap at all. `as_u64` still rejects
/// the negatives, the fractions, the strings and the booleans, exactly as
/// [`bounded`] does.
fn count(value: Option<&Value>) -> Option<u64> {
value?.as_u64()
}
/// Every string in a JSON array, or an empty list for anything else. Entries
/// that are not strings are dropped rather than stringified: a number in an
/// exclude list is a mistake, and guessing what it meant would hide it.
@@ -183,11 +342,160 @@ mod tests {
"exclude": exclude,
"filelist": "",
"inlineTemplates": true,
"formatOnSave": false
"formatOnSave": false,
"index": {
"maxFileSize": 1048576, "logFiles": true,
"scope": "folder", "scopeDepth": 0
}
}
})
}
#[test]
fn the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off() {
assert_eq!(settings(json!({ "lucisv": {} })).max_file_size, DEFAULT_MAX_FILE_SIZE);
assert_eq!(DEFAULT_MAX_FILE_SIZE, 1_048_576, "1 MiB, as the setting's description says");
// The whole sub-section missing is the same as the key missing.
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).max_file_size, 1_048_576);
let off = settings(json!({ "lucisv": { "index": { "maxFileSize": 0 } } }));
assert_eq!(off.max_file_size, 0, "0 is the client asking for no cap at all");
let raised = settings(json!({ "lucisv": { "index": { "maxFileSize": 20_000_000 } } }));
assert_eq!(raised.max_file_size, 20_000_000, "and there is no upper bound");
}
#[test]
fn a_wrong_typed_size_cap_leaves_the_default_standing() {
// The safe direction is the shipped cap: reading junk as `0` would
// turn the cap *off*, which is the failure the setting exists to
// prevent.
for bad in
[json!("1048576"), json!(-1), json!(1.5), json!(true), json!(null), json!([1048576])]
{
let found = settings(json!({ "lucisv": { "index": { "maxFileSize": bad } } }));
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "maxFileSize {bad} is ignored");
}
// An `index` that is not an object at all is the same as no `index`.
for bad in [json!(null), json!(7), json!("index"), json!([])] {
let found = settings(json!({ "lucisv": { "index": bad } }));
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");
}
}
#[test]
fn the_file_log_is_on_until_a_client_turns_it_off() {
assert!(settings(json!({ "lucisv": {} })).log_files, "absence is on");
assert!(
settings(json!({ "lucisv": { "index": {} } })).log_files,
"and so is an empty section"
);
assert!(settings(json!({ "lucisv": { "index": { "logFiles": true } } })).log_files);
assert!(!settings(json!({ "lucisv": { "index": { "logFiles": false } } })).log_files);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "index": { "logFiles": bad } } }));
assert!(found.log_files, "logFiles {bad} must be ignored");
}
}
#[test]
fn the_index_settings_come_through_the_pull_door_too() {
// `from_section` is the same parser, and these were the first nested
// keys to go through it — a section that lost the nesting on the way
// would silently un-cap every pulling client.
let section = json!({
"index": {
"maxFileSize": 4096, "logFiles": false,
"scope": "workspace", "scopeDepth": 2,
"persist": false, "cachePath": "/tmp/store"
}
});
let pulled = from_section(&section);
assert_eq!(pulled.max_file_size, 4096);
assert!(!pulled.log_files);
assert_eq!(pulled.index_scope, IndexScope::Workspace);
assert_eq!(pulled.index_scope_depth, 2);
assert!(!pulled.index_persist);
assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store"));
assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules");
}
#[test]
fn the_index_cache_is_on_until_a_client_turns_it_off() {
// Same shape as the file log, and the same direction for junk: the
// setting that costs a user work if it is guessed wrong is "off", so
// anything unreadable leaves it on.
assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on");
assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one");
assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist);
assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "index": { "persist": bad } } }));
assert!(found.index_persist, "persist {bad} must be ignored");
}
}
#[test]
fn the_cache_path_is_unset_until_a_client_names_one() {
// The empty string is `lucisv.index.cachePath`'s own default and means
// "you decide", exactly as it does for `lucisv.filelist` — not "the
// directory named by the empty path".
assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path,
None
);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } }))
.index_cache_path
.as_deref(),
Some(".cache/lucisv")
);
for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] {
let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } }));
assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored");
}
}
#[test]
fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() {
// The default is the narrow one, and it is what silence, an empty
// sub-section and a missing `index` all resolve to.
assert_eq!(settings(json!({ "lucisv": {} })).index_scope, IndexScope::Folder);
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope, IndexScope::Folder);
assert_eq!(IndexScope::default(), IndexScope::Folder, "and the enum agrees");
let wide = settings(json!({ "lucisv": { "index": { "scope": "workspace" } } }));
assert_eq!(wide.index_scope, IndexScope::Workspace, "the migration setting");
let narrow = settings(json!({ "lucisv": { "index": { "scope": "folder" } } }));
assert_eq!(narrow.index_scope, IndexScope::Folder, "spelled out, same thing");
// Anything else is junk, and junk leaves the *narrow* default: a
// misparse must never buy a whole-workspace scan silently.
for bad in
[json!("Workspace"), json!("all"), json!(""), json!(2), json!(true), json!(["folder"])]
{
let found = settings(json!({ "lucisv": { "index": { "scope": bad } } }));
assert_eq!(found.index_scope, IndexScope::Folder, "scope {bad} must be ignored");
}
}
#[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);
let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } }));
assert_eq!(raised.index_scope_depth, 3);
// 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.
let absurd = settings(json!({ "lucisv": { "index": { "scopeDepth": 9999 } } }));
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");
}
}
#[test]
fn a_filelist_is_taken_when_it_names_something() {
let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } }));
+2 -2
View File
@@ -321,7 +321,7 @@ endmodule
tree.write("sub.sv", SUB);
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
@@ -456,7 +456,7 @@ endmodule
let top = "module top;\n bare #(\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = top.len() as u32 - 1;
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -179,7 +179,7 @@ mod tests {
.expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let hits = workspace_symbols(&ws, "alpha");
let names: Vec<_> = hits.iter().map(|h| h.name.as_str()).collect();
+290 -12
View File
@@ -121,18 +121,35 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
encode(&within(absolute(doc), range))
}
/// The tokens a range covers of a buffer nothing has lexed — the large-file
/// fast path's answer to `semanticTokens/range`.
///
/// Identical to [`semantic_tokens_in_range`] in everything the client can see:
/// the same classification, the same line splitting, the same encoding from
/// the start of the document, the same overlap filter. The only difference is
/// where the tokens come from — `large::window` lexes the window instead of
/// the document's own (empty) token stream — and that a plain identifier can
/// only ever be `variable`, because there is no `Semantics` to refine it with.
/// See `docs/features/large-file-mode/README.md`.
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
let window = crate::large::window(doc, range);
let mut pieces = Vec::new();
// The comment spans the lexer never saw go in first; `flatten` sorts, so
// the order they are collected in cannot reach the wire.
for span in &window.comments {
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
}
for token in &window.tokens {
collect(token, &doc.semantics, &mut pieces);
}
encode(&within(flatten(pieces, doc), range))
}
/// Classify the whole buffer, split at line boundaries, in wire order.
fn absolute(doc: &Document) -> Vec<Absolute> {
let mut pieces = Vec::new();
for token in &doc.tokens {
collect_trivia(token, &mut pieces);
if let Some(ty) = classify(token, &doc.semantics) {
pieces.push(Piece {
span: token.span,
ty,
modifiers: modifiers(token, &doc.semantics),
});
}
collect(token, &doc.semantics, &mut pieces);
}
flatten(pieces, doc)
}
@@ -151,13 +168,22 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect()
}
/// One token's pieces: its comments and the token itself.
///
/// Comments live as trivia on the token that follows (or, for a trailing
/// comment, precedes) them — including on the EOF token, which is what makes
/// a comment at the end of the file reachable.
fn collect_trivia(token: &Token, out: &mut Vec<Piece>) {
/// a comment at the end of the file reachable. They are pushed **in source
/// order** — leading comments, the token, then the trailing comment that sits
/// after it on the same line — because [`flatten`] converts the offsets with a
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
/// and no two pieces here can start at the same byte.
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
for comment in &token.leading {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
}
if let Some(ty) = classify(token, semantics) {
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
}
if let Some(comment) = &token.trailing {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
}
@@ -233,11 +259,18 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
/// multi-line macro invocation.
fn flatten(pieces: Vec<Piece>, doc: &Document) -> Vec<Absolute> {
let positions = doc.positions();
// The pieces arrive in source order (see [`collect`]), so one monotonic
// cursor measures each line once however many tokens sit on it. The
// per-call converter re-measures from the line's start every time, which
// is quadratic on a netlist's single million-byte line — seconds per
// viewport, measured. Out-of-order pieces (the fast path's window-edge
// comments) are answered identically, just without the saving.
let mut walker = positions.walker();
let mut flat: Vec<Absolute> = Vec::new();
for piece in pieces {
for line_span in split_lines(&doc.text, piece.span) {
let start = positions.position(line_span.start);
let end = positions.position(line_span.end);
let start = walker.position(line_span.start);
let end = walker.position(line_span.end);
if end.character <= start.character {
continue;
}
@@ -435,6 +468,44 @@ mod tests {
assert_eq!(comments[1].0, 3);
}
/// QA (fix-round re-verification): `collect_trivia` became `collect`,
/// folding two callers' duplicated classify-and-push into one function
/// that pushes a token's own piece *between* its leading comments and its
/// trailing one. A single token flanked by both is the shape that
/// exercises every branch of that function on one token, and `flatten`'s
/// stable sort means the exact byte offsets have to be right regardless
/// of the order `collect` happened to push them in.
#[test]
fn a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces() {
let text = "/* lead */\nwire /* mid */ a;\n";
let out = decoded(text);
let comment = |n: usize| {
out.iter()
.filter(|&&(.., t, _)| t == Highlight::Comment as u32)
.nth(n)
.copied()
.unwrap_or_else(|| panic!("comment {n} missing in {out:?}"))
};
// Line 0: "/* lead */" is 10 bytes, all ASCII.
assert_eq!(comment(0), (0, 0, 10, Highlight::Comment as u32, 0));
// Line 1: "wire /* mid */ a;" — `wire` at 0..4, the comment at 5..14
// (9 bytes), `a` at 15.
let keyword = out
.iter()
.find(|&&(l, c, _, t, _)| l == 1 && c == 0 && t == Highlight::Keyword as u32)
.copied()
.expect("the `wire` keyword");
assert_eq!(keyword, (1, 0, 4, Highlight::Keyword as u32, 0));
assert_eq!(comment(1), (1, 5, 9, Highlight::Comment as u32, 0));
let ident = out
.iter()
.find(|&&(l, c, _, t, _)| l == 1 && c == 15 && t == Highlight::Variable as u32)
.copied()
.expect("the `a` identifier");
// `a` is a real declaration in this fragment's full semantics.
assert_eq!(ident, (1, 15, 1, Highlight::Variable as u32, DECLARATION));
}
#[test]
fn no_token_ever_spans_a_line_break() {
let text = "/* a\n b\n c */\nmodule m;\nendmodule\n";
@@ -594,6 +665,213 @@ mod tests {
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
}
// ------------------------------------------------------------------
// the large-file fast path's window
// ------------------------------------------------------------------
/// The classes a plain identifier can take once `Semantics` has spoken.
/// A fast-path buffer has no `Semantics`, so every one of them is
/// `variable` there — the one difference between the two paths, and the
/// one this normalization folds away so the rest can be compared.
fn coarse(ty: u32) -> u32 {
let refined = [
Highlight::Namespace,
Highlight::Class,
Highlight::Type,
Highlight::EnumMember,
Highlight::Parameter,
Highlight::Variable,
Highlight::Property,
Highlight::Function,
];
match refined.iter().any(|&r| r as u32 == ty) {
true => Highlight::Variable as u32,
false => ty,
}
}
/// Decoded tokens with the identifier refinement folded away.
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
}
/// Whether any construct in `doc` crosses `offset` — a block comment, a
/// continued `` `define``, a multi-line macro call. A window boundary
/// inside one of those is exactly where the fast path is *documented* to
/// disagree, so the agreement property excludes them rather than
/// pretending they do not exist.
fn crosses(doc: &Document, offset: u32) -> bool {
doc.tokens.iter().any(|token| {
let spans = token
.leading
.iter()
.map(|c| c.span)
.chain(token.trailing.iter().map(|c| c.span))
.chain(std::iter::once(token.span));
spans.into_iter().any(|span| span.start < offset && offset < span.end)
})
}
/// **The agreement anchor.** For a window no multi-line construct reaches
/// into, the fast path's answer is the full pipeline's answer — same
/// spans, same lengths, same classes. Run over real corpus files, in the
/// forty-line windows an editor asks for.
#[test]
fn the_window_lexer_answers_what_the_full_pipeline_answers() {
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let files = [
corpus.join("picorv32/picorv32.v"),
corpus.join("common_cells/src/fifo_v3.sv"),
corpus.join("common_cells/src/rr_arb_tree.sv"),
];
let (mut compared, mut skipped) = (0, 0);
for path in files {
let Ok(text) = std::fs::read_to_string(&path) else {
eprintln!("{} not checked out — skipping", path.display());
continue;
};
let full = Document::new(Some(path.clone()), text.clone(), &WorkspaceIndex::default());
let fast = Document::large(Some(path.clone()), text);
assert!(!full.tokens.is_empty(), "{}: the premise", path.display());
assert!(fast.tokens.is_empty(), "the fast path lexed nothing at open");
let lines = full.line_index.line_count();
let mut from = 0;
while from < lines {
let to = (from + 40).min(lines);
let window = range((from, 0), (to, 0));
// The two boundaries in bytes: the start of the first line and
// the end of the last line the window lexes.
let start = full.line_index.line_range(from + 1).map_or(0, |l| l.start);
let end =
full.line_index.line_range(to + 1).map_or(full.text.len() as u32, |l| l.end);
if crosses(&full, start) || crosses(&full, end) {
skipped += 1;
from = to;
continue;
}
assert_eq!(
coarsely(&semantic_tokens_in_window(&fast, window)),
coarsely(&semantic_tokens_in_range(&full, window)),
"{}: lines {from}..{to}",
path.display()
);
compared += 1;
from = to;
}
}
assert!(compared > 50, "the corpus really is checked out: {compared} (skipped {skipped})");
// The excluded windows are a small minority; if they ever became the
// majority the property would be vacuous.
assert!(skipped * 4 < compared, "too many windows excluded: {skipped} of {compared}");
}
#[test]
fn a_window_of_a_fast_path_buffer_is_self_contained_like_a_range_answer() {
let text = "module m;\n wire a;\n wire b;\nendmodule\n";
let doc = Document::large(None, text.to_string());
let data = semantic_tokens_in_window(&doc, range((2, 0), (3, 0)));
let first = data.first().expect("line 2 has tokens");
assert_eq!(first.delta_line, 2, "encoded from the start of the document");
assert_eq!(first.delta_start, 2, "the `wire` keyword's own column");
assert!(decode(&data).iter().all(|&(line, ..)| line == 2));
}
#[test]
fn a_fast_path_identifier_is_a_plain_variable_with_no_declaration_modifier() {
// The one documented difference: nothing analyzed the buffer, so the
// module name is not a `class` and carries no `declaration` bit.
let text = "module top;\nendmodule\n";
let doc = Document::large(None, text.to_string());
let data = decode(&semantic_tokens_in_window(&doc, range((0, 0), (1, 0))));
let name = data.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("`top`");
assert_eq!(name.3, Highlight::Variable as u32);
assert_eq!(name.4, 0);
}
#[test]
fn a_fast_path_window_never_carries_a_token_from_outside_the_range() {
let text = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
let doc = Document::large(None, text.to_string());
let inside = decode(&semantic_tokens_in_window(&doc, range((2, 0), (3, 0))));
assert!(!inside.is_empty(), "premise: line 2 has tokens");
assert!(inside.iter().all(|&(line, ..)| line == 2), "{inside:?}");
}
/// QA (fix-round re-verification): the load-bearing claim behind the
/// walker's restart-on-backwards-offset behaviour is that a window's tail
/// comment genuinely arrives at `flatten` *after* every token in byte
/// order but is pushed into `pieces` *before* them (`semantic_tokens_in_window`
/// pushes `window.comments` ahead of the token loop). This reproduces that
/// exact shape through the real request path — a long declaration line
/// followed by a banner comment that never closes — and checks two
/// things: that the comment really is a byte-order tail relative to every
/// token (the premise the walker's reset exists for), and that every
/// token's and the comment's own position, once decoded off the wire,
/// matches what `Positions::position` would say for the same offset —
/// i.e. the single mid-window restart the out-of-order comment forces
/// does not corrupt anything that comes after it.
#[test]
fn a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly() {
let mut text = String::from("wire ");
for n in 0..500 {
text.push_str(&format!("a{n},"));
}
text.push_str("last;\n");
let declaration_line_len = text.len() as u32;
text.push_str("/* a banner that never closes\n");
let doc = Document::large(None, text.clone());
// The final `within` filter re-checks the *exact* requested LSP
// range (not the whole-line window `large::window` snapped to), so
// the end has to reach past the comment's own start on line 1 for it
// to survive onto the wire at all.
let window_range = range((0, 0), (1, 50));
let window = crate::large::window(&doc, window_range);
assert!(!window.tokens.is_empty(), "premise: the declaration line lexed");
assert_eq!(window.comments.len(), 1, "premise: the banner is one tail comment");
let comment_span = window.comments[0];
let last_token_end = window.tokens.iter().map(|t| t.span.end).max().expect("a token");
assert!(
comment_span.start >= declaration_line_len,
"premise: the comment opens on the second line, after every token byte-wise"
);
assert!(
comment_span.start >= last_token_end,
"premise: the out-of-order shape this test targets — the comment \
collected before the tokens in `pieces` has the higher byte offset"
);
let positions = doc.positions();
let decoded = decode(&semantic_tokens_in_window(&doc, window_range));
assert!(decoded.iter().any(|&(_, _, _, ty, _)| ty == Highlight::Comment as u32));
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
// never reaches `pieces` — only the tokens `classify` keeps are
// expected on the wire.
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
let expected = positions.position(token.span.start);
let found = decoded
.iter()
.find(|&&(line, start, ..)| line == expected.line && start == expected.character);
assert!(
found.is_some(),
"token at byte {} expected at {expected:?}, not found in {decoded:?}",
token.span.start
);
}
let comment_expected = positions.position(comment_span.start);
assert!(
decoded.iter().any(|&(line, start, _, ty, _)| line == comment_expected.line
&& start == comment_expected.character
&& ty == Highlight::Comment as u32),
"comment at byte {} expected at {comment_expected:?}, not found in {decoded:?}",
comment_span.start
);
}
// ------------------------------------------------------------------
// `semanticTokens/full/delta`
// ------------------------------------------------------------------
+2 -2
View File
@@ -629,7 +629,7 @@ endmodule
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let path = dir.join(which);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -1280,7 +1280,7 @@ endmodule
return;
}
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let open = |ws: &mut Workspace, rel: &str| -> (Uri, String) {
let file = root.join(rel);
+107 -85
View File
@@ -21,24 +21,15 @@
//! See `docs/features/type-hierarchy/README.md`.
use lsp_types::{Range, SymbolKind, TypeHierarchyItem, Uri};
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
use vlog_parser::ast::Item;
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
use vlog_semantic::classes::{self, Decl};
use vlog_semantic::{Definition, SymbolKind as SemanticKind};
use crate::convert::Positions;
use crate::state::{Document, Workspace};
use crate::uri::{path_to_uri, uri_to_path};
/// One class declaration: the node, and the extent of the whole
/// `class ... endclass` it was written as.
#[derive(Clone, Copy)]
struct Decl<'a> {
class: &'a ClassDecl,
/// Code extent of the declaration, attributes included — what a type
/// hierarchy item's `range` is.
span: TextRange,
}
/// The class the cursor names, as the root of a type hierarchy — its own
/// declaration, or any use of its name.
///
@@ -53,8 +44,9 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<TypeHierarc
let doc = ws.document(uri)?;
// The cursor on a declaration written in this buffer answers from the
// buffer, unsaved edits and all — no index lookup can beat that.
if let Some(decl) =
declarations(&doc.tree.items).into_iter().find(|decl| touches(decl.class.name_span, offset))
if let Some(decl) = classes::declarations(&doc.tree.items)
.into_iter()
.find(|decl| touches(decl.class.name_span, offset))
{
let positions = doc.positions();
return Some(vec![item(uri.clone(), &positions, decl)?]);
@@ -94,37 +86,38 @@ pub fn supertypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchy
/// Who extends this class, across the workspace.
///
/// Every in-scope file is walked, because the workspace index records what a
/// file *declares* and not what it extends — there is no edge table to consult,
/// exactly as there is none for instantiations
/// (`docs/features/hierarchy/README.md`). A file whose text does not contain
/// the name is skipped before it is parsed, which is what keeps the walk
/// affordable: `extends base` has to write `base`.
/// **A lookup in the workspace index's inheritance-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The edges are recorded by the same [`classes::declarations`] walk this
/// function used to run, at index time
/// (`docs/features/incremental-index/README.md`), so the answer and its order
/// are unchanged; only the files that really do extend the class are read now,
/// and only to turn the recorded byte spans into line/character ranges.
///
/// An empty name is answered with nothing rather than searched for: nothing
/// this server hands out is nameless, and the prefilter matches every file for
/// one, which would parse the whole workspace to find nothing.
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyItem> {
if item.name.is_empty() {
return Vec::new();
}
let index = ws.index();
let mut found: Vec<TypeHierarchyItem> = Vec::new();
for (path, text) in ws.sources() {
if !text.contains(&item.name) {
continue;
}
let Some(uri) = path_to_uri(&path) else { continue };
let (tree, _) = parse_source_tolerant(&text);
let edges = index.subclasses_of(&item.name);
let mut at = 0;
while at < edges.len() {
// The edges arrive in file order, so one file's are consecutive: read
// its text once and build every item it holds.
let file = edges[at].file;
let group = &edges[at..][..edges[at..].iter().take_while(|e| e.file == file).count()];
at += group.len();
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for decl in declarations(&tree.items) {
if extends_name(decl.class) != Some(item.name.as_str()) {
continue;
}
if let Some(built) = self::item(uri.clone(), &positions, decl) {
found.push(built);
}
}
found.extend(group.iter().map(|edge| &edge.subclass).filter_map(|subclass| {
item_of(uri.clone(), &positions, &subclass.name, subclass.name_span, subclass.span)
}));
}
found.sort_by(|a, b| {
(a.uri.as_str(), key(a.selection_range)).cmp(&(b.uri.as_str(), key(b.selection_range)))
@@ -132,16 +125,6 @@ pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyIt
found
}
/// The base class of one class declaration, as written — `None` when the
/// header has no `extends`.
///
/// The name is the bare base: `extends base #(8)` stores `base`, because the
/// parser keeps the parameter overrides on their own field, so a parameterized
/// base needs no unwrapping here.
fn extends_name(class: &ClassDecl) -> Option<&str> {
class.extends.as_ref().map(|extends| extends.name.as_str())
}
/// The base classes of the class an item names, in the file it names.
fn bases_of(
ws: &Workspace,
@@ -200,20 +183,28 @@ fn classes_at(ws: &Workspace, doc: &Document, uri: &Uri, offset: u32) -> Vec<Typ
/// The hierarchy item for one class declaration, positioned against the text it
/// was parsed from.
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<TypeHierarchyItem> {
let name_span = decl.class.name_span;
item_of(uri, positions, &decl.class.name, decl.class.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's
/// inheritance-edge table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<TypeHierarchyItem> {
if name_span.is_empty() {
return None;
}
// The protocol requires `selectionRange` inside `range`; a declaration the
// parser could not close is the case where that may not hold, and there the
// name alone is the honest extent.
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
decl.span
} else {
name_span
};
let full =
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(TypeHierarchyItem {
name: decl.class.name.clone(),
name: name.to_string(),
// `interface class` is a different construct (IEEE 1800 §8.26) that
// `vlog_parser` does not model at all, so there is nothing here that
// could carry `SymbolKind::INTERFACE`.
@@ -250,34 +241,11 @@ fn item_in_file(
item(uri, &Positions::new(&text, &line_index), decl)
}
/// Every class declaration in `items`, wherever a class may be written: at file
/// scope, inside a `package`, inside a `module`, and nested inside another
/// class.
fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
let mut out = Vec::new();
collect(items, &mut out);
out
}
fn collect<'a>(items: &'a [Item], out: &mut Vec<Decl<'a>>) {
for item in items {
match &item.kind {
ItemKind::Class(class) => {
out.push(Decl { class, span: item.span });
collect(&class.items, out);
}
ItemKind::Package { items, .. } => collect(items, out),
ItemKind::Module(module) => collect(&module.items, out),
_ => {}
}
}
}
/// The declaration of `name` in a parsed file: the one whose name sits at `at`,
/// else the first of that name.
fn find_class<'a>(items: &'a [Item], name: &str, at: Option<TextRange>) -> Option<Decl<'a>> {
let decls: Vec<Decl> =
declarations(items).into_iter().filter(|d| d.class.name == name).collect();
classes::declarations(items).into_iter().filter(|d| d.class.name == name).collect();
if let Some(at) = at {
if let Some(exact) = decls.iter().find(|d| d.class.name_span == at) {
return Some(*exact);
@@ -351,7 +319,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -718,7 +686,7 @@ endclass
tree.write("files.f", "base.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let base_uri = path_to_uri(&tree.path.join("base.sv")).expect("uri");
ws.set_document(base_uri.clone(), BASE.to_string());
@@ -727,9 +695,14 @@ endclass
}
#[test]
fn an_unsaved_extends_is_a_subtype_before_it_is_saved() {
// The sources a walk reads are the open buffers overlaid on disk, so a
// just-typed `extends` counts.
fn an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_extends_is_a_subtype_before_it_is_saved` pinned the walk
// over `Workspace::sources()`, so a keystroke in another buffer moved
// the answer before anything rebuilt. Subtypes are the index's
// inheritance-edge table now — as of its last build or update, both of
// which fold every open buffer in. Same rule as the call hierarchy's
// census, pinned from both sides.
let (tree, mut ws, uri) = two("unsaved");
let root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone();
assert_eq!(subtypes(&ws, &root).len(), 1, "premise");
@@ -737,7 +710,13 @@ endclass
let fresh = tree.path.join("child.sv");
let child_uri = path_to_uri(&fresh).expect("uri");
ws.set_document(child_uri, "class child;\nendclass\n".to_string());
assert!(subtypes(&ws, &root).is_empty(), "the buffer took the `extends` away");
assert_eq!(
subtypes(&ws, &root).len(),
1,
"the buffer alone does not move the answer — the index has not seen it"
);
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert!(subtypes(&ws, &root).is_empty(), "the edit took the `extends` away");
}
// ------------------------------------------------------------------
@@ -1088,6 +1067,49 @@ endclass
// the corpus, smoke-tested
// ------------------------------------------------------------------
/// What `subtypes` costs after the inheritance-edge table, against the
/// workspace walk it replaced. `#[ignore]`d: it prints a number rather
/// than asserting one — the budget is asserted in
/// `the_corpus_uvm_classes_answer_all_three_requests`.
#[test]
#[ignore]
fn qa_perf_subtypes_lookup_against_the_walk_it_replaced() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv");
let Ok(text) = fs::read_to_string(&lib) else {
eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping");
return;
};
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&lib).expect("uri");
ws.set_document(uri.clone(), text.clone());
let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6;
let child = prepare(&ws, &uri, offset).expect("the class")[0].clone();
let base = supertypes(&ws, &child).first().cloned().expect("core_ibex_base_test");
let mut lookup = std::time::Duration::ZERO;
let mut walk = std::time::Duration::ZERO;
for _ in 0..3 {
let started = std::time::Instant::now();
let found = subtypes(&ws, &base);
lookup = lookup.max(started.elapsed());
assert!(!found.is_empty());
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.max(started.elapsed());
}
eprintln!(
"typeHierarchy/subtypes over {} files: {lookup:?}; one workspace walk (what it \
used to begin with) is {walk:?}",
ws.index().files().len()
);
}
/// Every class of a real UVM-shaped corpus file, through all three
/// requests, plus one known `extends` chain. Skipped when `corpus/` is not
/// checked out (`tools/corpus_fetch.sh`), like the other corpus tests.
@@ -1104,7 +1126,7 @@ endclass
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&lib).expect("uri");
ws.set_document(uri.clone(), text.clone());
let files = ws.index().files().len();
@@ -1113,7 +1135,7 @@ endclass
// every item the protocol's containment rule.
let doc = ws.document(&uri).expect("the open buffer");
let names: Vec<String> =
declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
classes::declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
assert!(names.len() > 20, "the file really is class-heavy: {}", names.len());
let mut with_a_base = 0;
for name in &names {
+24 -1
View File
@@ -8,7 +8,7 @@
//! module asks it to say what it sees. See
//! `docs/features/file-watching/README.md`.
use std::path::Path;
use std::path::{Path, PathBuf};
use lsp_types::notification::{DidChangeWatchedFiles, Notification as _};
use lsp_types::{
@@ -112,6 +112,29 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
.any(|path| watched(&path, filelist))
}
/// The one file an event named, when it named exactly one and that one is not
/// the filelist.
///
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
/// checkout fills this list, and a list of one is the case a single file's
/// contribution can be replaced in place. The filelist is excluded because a
/// change to it moves the whole scope, which is a rebuild by definition. An
/// event naming the same path twice — a client is free to send `Changed` and
/// `Created` for one file — is still one file.
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
let mut named: Vec<PathBuf> = changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
.filter(|path| watched(path, filelist))
.collect();
named.sort();
named.dedup();
match named.as_slice() {
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
_ => None,
}
}
/// Whether one path is something the index reads: a source file, or the
/// filelist that decides which source files there are.
///
+520 -8
View File
@@ -20,6 +20,16 @@ fn frame(payload: &str) -> String {
format!("Content-Length: {}\r\n\r\n{payload}", payload.len())
}
/// The `didChangeConfiguration` push that asks for the whole-workspace index
/// scope — what every session had before 2026-08-27.
///
/// Sessions whose subject is *not* the scope send it right after
/// `initialized`: the default scope is the folders the client's own buffers
/// live in, so a session that opens no buffer (or that expects a folder it
/// never opened a file in to be indexed) would otherwise be asking questions
/// of an empty index. See `docs/features/index-scope/README.md`.
const WIDE_SCOPE: &str = r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scope":"workspace"}}}}}"#;
/// Split a stdout dump into its JSON payloads.
fn unframe(mut input: impl BufRead) -> Vec<serde_json::Value> {
let mut out = Vec::new();
@@ -51,6 +61,27 @@ fn read_message(input: &mut impl BufRead) -> Option<serde_json::Value> {
serde_json::from_slice(&body).ok()
}
/// The server binary, with its OS cache directory pointed somewhere a test
/// may write.
///
/// Without a client-supplied `storagePath` the persistent index cache falls
/// back to this platform's cache directory
/// (`docs/features/index-persistence/README.md`), and the developer's own
/// `~/Library/Caches` is not somewhere a test run may leave anything. The
/// three variables below are the ones that decide it on the three platforms.
/// A test whose subject *is* the cache passes a `storagePath` of its own,
/// which outranks all of them.
fn server_command() -> Command {
let sandbox =
std::env::temp_dir().join(format!("lucisv_server_e2e_home_{}", std::process::id()));
let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-server"));
command
.env("HOME", &sandbox)
.env("XDG_CACHE_HOME", sandbox.join("cache"))
.env("LOCALAPPDATA", sandbox.join("cache"));
command
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lucisv_server_e2e_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -64,7 +95,7 @@ fn temp_dir(name: &str) -> PathBuf {
/// processes the messages in order and exits on `exit`, so stdout closes and
/// the read terminates on its own.
fn talk(session: &str) -> Vec<serde_json::Value> {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
let mut child = server_command()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -1101,9 +1132,13 @@ fn a_pushed_filelist_narrows_the_index_mid_session_and_reports_a_bad_one() {
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"#
))
};
// Every push carries `index.scope: "workspace"`: this test is about the
// filelist rung and the walk it falls back to, and a push replaces every
// setting — without it each message would also move the fallback to the
// folder scope, which no buffer has widened here.
let filelist = |path: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"filelist":"{path}"}}}}}}}}"#
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"filelist":"{path}","index":{{"scope":"workspace"}}}}}}}}}}"#
))
};
let session = [
@@ -1111,6 +1146,8 @@ fn a_pushed_filelist_narrows_the_index_mid_session_and_reports_a_bad_one() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The walk this test starts from is the opt-in one now.
filelist(""),
query(2, "b_pkg"),
filelist("files.f"),
query(3, "b_pkg"),
@@ -2151,7 +2188,7 @@ struct Live {
impl Live {
fn start() -> Live {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
let mut child = server_command()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -2664,6 +2701,7 @@ endmodule
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{mid_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(mid_text).expect("json")
@@ -2693,6 +2731,7 @@ endmodule
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"callHierarchy/incomingCalls","params":{{"item":{}}}}}"#,
serde_json::to_string(&sub2_item).expect("json")
@@ -3205,8 +3244,14 @@ fn indexing_reports_its_progress_over_the_wire() {
})
.collect();
// Two rescans: the startup build, then the save. Each one create, one
// begin, one end, on its own token.
// **Two** rescans, and the shape of them is the folder scope on the wire
// (index-scope, 2026-08-27) plus the incremental save path
// (incremental-index, 2026-08-27). The startup build has **no file to
// scan** — the default scope is the open buffers' folders and no buffer is
// open yet — so its bar carries no report; the `didOpen` widens the scope
// to `m.sv`'s folder and rebuilds, reporting the one file. The **save
// puts no bar up at all**: it names one file the index already holds, so
// it is one parse on the incremental path rather than a scan to report.
assert_eq!(
steps,
vec![
@@ -3215,11 +3260,18 @@ fn indexing_reports_its_progress_over_the_wire() {
("end".to_string(), "lucisv-index-0".to_string()),
("create".to_string(), "lucisv-index-1".to_string()),
("begin".to_string(), "lucisv-index-1".to_string()),
("report".to_string(), "lucisv-index-1".to_string()),
("end".to_string(), "lucisv-index-1".to_string()),
],
"{messages:#?}"
);
// The report counts, on the wire: "1/1 m.sv" at 100%.
let report =
messages.iter().find(|m| m["params"]["value"]["kind"] == "report").expect("a report");
assert_eq!(report["params"]["value"]["message"], "1/1 m.sv", "{report:#?}");
assert_eq!(report["params"]["value"]["percentage"], 100, "{report:#?}");
// The begin says what it is doing, and offers no cancel button — a rescan
// that has started runs to completion, whatever `$/cancelRequest` can do
// for the requests still queued.
@@ -3228,8 +3280,15 @@ fn indexing_reports_its_progress_over_the_wire() {
assert_eq!(begin["params"]["value"]["cancellable"], false, "{begin:#?}");
assert!(begin["params"]["value"].get("percentage").is_none(), "no fake numbers: {begin:#?}");
let end = messages.iter().find(|m| m["params"]["value"]["kind"] == "end").expect("an end");
assert_eq!(end["params"]["value"]["message"], "1 file indexed", "{end:#?}");
// The startup bar ends at nothing indexed — honestly, since the folder
// scope had no folder yet — and the `didOpen` rebuild after it names the
// file. The save has no bar to end.
let ends: Vec<&serde_json::Value> = messages
.iter()
.filter(|m| m["params"]["value"]["kind"] == "end")
.map(|m| &m["params"]["value"]["message"])
.collect();
assert_eq!(ends, ["0 files indexed", "1 file indexed"], "{messages:#?}");
// The create is a request the client may answer or error; leaving it
// unanswered here is exactly what a client that does not care does, and
@@ -3237,6 +3296,96 @@ fn indexing_reports_its_progress_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_size_cap_and_the_file_log_work_over_the_wire() {
// The three settings of `docs/features/indexing-ux/README.md` together,
// against the real binary: a pushed cap rescans, the oversized file is
// gone from the index, the log names every file and the skip, and the bar
// counts what is left.
let dir = temp_dir("indexcap");
std::fs::write(dir.join("keep.sv"), "package keep_pkg;\n localparam K = 1;\nendpackage\n")
.expect("write");
let mut fat = String::from("package netlist_pkg;\n localparam K = 1;\nendpackage\n// ");
while fat.len() < 4096 {
fat.push('x');
}
fat.push('\n');
std::fs::write(dir.join("netlist.sv"), &fat).expect("write");
let root = format!("file://{}", dir.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The cap arrives the way VS Code sends a dotted setting: nested. It
// carries `scope: "workspace"` because this test is about the cap, and
// a push replaces every setting — without it the same message would
// narrow the index to the folder scope in the same breath.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"maxFileSize":1024,"scope":"workspace"}}}}}"#,
),
frame(
r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"pkg"}}"#,
),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
// 1. The capped file is not in the index; the other one is.
let symbols = messages.iter().find(|m| m["id"] == 2).expect("symbol response");
let names: Vec<&str> = symbols["result"]
.as_array()
.expect("an array")
.iter()
.filter_map(|s| s["name"].as_str())
.collect();
assert!(names.contains(&"keep_pkg"), "{symbols:#?}");
assert!(!names.contains(&"netlist_pkg"), "the capped file is invisible: {symbols:#?}");
// 2. The log named every file it read, and the one it did not.
let logged: Vec<&str> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.collect();
assert!(
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.all(|m| m["params"]["type"] == 4),
"MessageType::LOG, which vscode-languageclient appends verbatim: {logged:?}"
);
assert!(
logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("keep.sv")),
"{logged:?}"
);
let skip = logged
.iter()
.find(|l| l.starts_with("skipped ("))
.unwrap_or_else(|| panic!("a skip line: {logged:?}"));
assert!(skip.ends_with("netlist.sv"), "{skip}");
assert!(skip.starts_with("skipped (4.0 KiB > 1.0 KiB cap): "), "{skip}");
// 3. The bar for the rescan the cap triggered: one file of one, and an
// end that counts the skip.
let after: Vec<&serde_json::Value> = messages
.iter()
.filter(|m| m["method"] == "$/progress" && m["params"]["token"] == "lucisv-index-1")
.collect();
let kinds: Vec<&str> =
after.iter().filter_map(|m| m["params"]["value"]["kind"].as_str()).collect();
assert_eq!(kinds, ["begin", "report", "end"], "the cap change rescanned: {after:#?}");
assert_eq!(after[1]["params"]["value"]["message"], "1/1 keep.sv", "{after:#?}");
assert_eq!(after[1]["params"]["value"]["percentage"], 100, "{after:#?}");
assert_eq!(after[2]["params"]["value"]["message"], "1 file indexed, 1 skipped", "{after:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() {
let dir = temp_dir("noprogress");
@@ -3654,8 +3803,11 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() {
messages.iter().filter(|m| m["method"] == "workspace/codeLens/refresh").count()
};
// One per rescan, and this script has two: the `didOpen` widens the folder
// scope to `lens_sub.sv`'s own folder and rebuilds (index-scope,
// 2026-08-27), and then the save rebuilds again.
let capable = talk(&script(r#"{"workspace":{"codeLens":{"refreshSupport":true}}}"#));
assert_eq!(refreshes(&capable), 1, "one per rescan, and the save is one: {capable:#?}");
assert_eq!(refreshes(&capable), 2, "one per rescan: {capable:#?}");
let silent = talk(&script("{}"));
assert_eq!(refreshes(&silent), 0, "a client that did not ask is never told: {silent:#?}");
@@ -3805,6 +3957,8 @@ fn a_rename_round_trips_through_the_edit_and_leaves_the_include_resolving() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
@@ -3836,6 +3990,8 @@ fn a_rename_round_trips_through_the_edit_and_leaves_the_include_resolving() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
@@ -3889,6 +4045,8 @@ fn a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
@@ -3959,6 +4117,7 @@ fn a_folder_added_mid_session_is_indexed_over_the_wire() {
"{handshake:#?}"
);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(WIDE_SCOPE);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string("module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n")
@@ -4080,3 +4239,356 @@ fn the_configuration_pull_round_trips_over_the_wire() {
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
/// index-scope (2026-08-27): the default folder scope over the real wire.
///
/// What only an e2e test can settle: that the narrowing is what a *client*
/// sees, not just what `Workspace` computes — a definition into a sibling
/// folder answers nothing until a buffer in that folder widens the scope, and
/// a client that asked for `lucisv.index.scope: "workspace"` never sees the
/// narrow answer at all.
#[test]
fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() {
let dir = temp_dir("indexscope");
std::fs::create_dir_all(dir.join("rtl")).expect("rtl");
std::fs::create_dir_all(dir.join("include")).expect("include");
let top = dir.join("rtl/scope_top.sv");
let top_text = "module scope_top;\n localparam W = scope_defs::WIDTH;\nendmodule\n";
std::fs::write(&top, top_text).expect("write");
let defs = dir.join("include/scope_defs.sv");
let defs_text = "package scope_defs;\n localparam WIDTH = 8;\nendpackage\n";
std::fs::write(&defs, defs_text).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
let defs_uri = format!("file://{}", defs.display());
// The cursor on `WIDTH` in `scope_defs::WIDTH`.
let definition = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":1,"character":33}}}}}}"#
)
};
let open = |uri: &str, text: &str| {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(text).expect("json")
)
};
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
let _ = live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&open(&top_uri, top_text));
live.send(&definition(2));
let narrow = live.wait_for(|m| m["id"] == 2);
assert_eq!(
narrow["result"].as_array().map(Vec::len),
Some(0),
"the package is in a sibling folder, which the default scope does not cover: {narrow:#?}"
);
// Opening the other file widens the scope and rebuilds — no save, no
// settings change, just the file the user opened.
live.send(&open(&defs_uri, defs_text));
live.send(&definition(3));
let widened = live.wait_for(|m| m["id"] == 3);
let targets = widened["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "{widened:#?}");
assert_eq!(targets[0]["uri"], defs_uri.as_str(), "{widened:#?}");
live.finish();
// And the migration setting: the same session, the same first question,
// answered straight away.
let mut wide = Live::start();
wide.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
let _ = wide.wait_for(|m| m["id"] == 1);
wide.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
wide.send(WIDE_SCOPE);
wide.send(&open(&top_uri, top_text));
wide.send(&definition(2));
let immediate = wide.wait_for(|m| m["id"] == 2);
let targets = immediate["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "the whole workspace was indexed: {immediate:#?}");
assert_eq!(targets[0]["uri"], defs_uri.as_str(), "{immediate:#?}");
wide.finish();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_save_of_one_file_updates_the_index_over_the_wire() {
// The incremental path against the real binary: a save rewrites one file,
// the answer that file supplies changes, and a second file nobody touched
// still answers exactly what it did before.
let dir = temp_dir("incremental");
std::fs::write(dir.join("sub.sv"), "module sub;\nendmodule\n").expect("write");
std::fs::write(dir.join("other.sv"), "module other;\nendmodule\n").expect("write");
let top = dir.join("top.sv");
let before = "module top;\n sub u1 ();\nendmodule\n";
std::fs::write(&top, before).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top.display());
// After the save `top.sv` instantiates `other` instead of `sub`. Both
// definition requests are asked twice, once each side of the save.
let after = "module top;\n other u1 ();\nendmodule\n";
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(before).expect("json")
)),
// Where `sub` is instantiated, before: line 1, character 2.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)),
// And what the untouched second file's own declaration answers, out
// of the index rather than out of a buffer — the file has none.
frame(
r#"{"jsonrpc":"2.0","id":3,"method":"workspace/symbol","params":{"query":"sub"}}"#,
),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}},"text":{}}}}}"#,
serde_json::to_string(after).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)),
frame(
r#"{"jsonrpc":"2.0","id":5,"method":"workspace/symbol","params":{"query":"sub"}}"#,
),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let answer = |id: i64| -> serde_json::Value {
messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no answer to {id} in {messages:#?}"))["result"]
.clone()
};
// `textDocument/definition` answers a list of locations.
let target =
|id: i64| -> String { answer(id)[0]["uri"].as_str().unwrap_or_default().to_string() };
assert!(target(2).ends_with("sub.sv"), "premise: {:#?}", answer(2));
assert!(target(4).ends_with("other.sv"), "the save moved the answer to `other.sv`");
assert_eq!(answer(3), answer(5), "the file nobody touched answers exactly what it did");
assert!(
answer(3).as_array().is_some_and(|hits| hits.iter().any(|hit| hit["name"] == "sub")),
"premise: it answers at all — {:#?}",
answer(3)
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_second_session_over_the_same_storage_path_indexes_from_the_cache() {
// The owner's case on the wire, with the real binary: one session indexes
// a workspace and writes what it learned into the folder the client named
// in `initializationOptions.storagePath`; a second session over the same
// folder gets the same index without parsing a file
// (docs/features/index-persistence/README.md).
let dir = temp_dir("persist");
let storage = temp_dir("persist_storage");
std::fs::write(dir.join("a.sv"), "module a;\nendmodule\n").expect("write");
std::fs::write(dir.join("b.sv"), "module b;\nendmodule\n").expect("write");
let root = format!("file://{}", dir.display());
let session = || {
[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","initializationOptions":{{"storagePath":{}}},"capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#,
serde_json::to_string(&storage.display().to_string()).expect("json")
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The scope push is what makes the workspace really get walked;
// it also rescans, which is the scan these assertions are about.
frame(WIDE_SCOPE),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat()
};
/// Every `window/logMessage` line of a transcript.
fn log_lines(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str().map(str::to_string))
.collect()
}
/// Every progress `end` message of a transcript.
fn ends(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["params"]["value"]["kind"] == "end")
.filter_map(|m| m["params"]["value"]["message"].as_str().map(str::to_string))
.collect()
}
let cold = talk(&session());
assert_eq!(ends(&cold), ["0 files indexed", "2 files indexed"], "{cold:#?}");
let parsed: Vec<String> =
log_lines(&cold).into_iter().filter(|l| l.starts_with("indexing: ")).collect();
assert_eq!(parsed.len(), 2, "the first session parses both files: {parsed:?}");
assert!(
storage.join("index-cache").exists(),
"and writes what it found where the client said: {}",
storage.display()
);
let warm = talk(&session());
assert_eq!(
ends(&warm),
["0 files indexed", "2 files indexed, 2 from cache"],
"the second session's bar says where its files came from: {warm:#?}"
);
let lines = log_lines(&warm);
assert_eq!(
lines.iter().filter(|l| l.starts_with("cached: ")).count(),
2,
"and its log names them one by one: {lines:?}"
);
assert!(
!lines.iter().any(|l| l.starts_with("indexing: ")),
"with nothing parsed at all: {lines:?}"
);
// A file changed between sessions is the only thing the third one parses.
std::fs::write(dir.join("b.sv"), "module b_renamed;\nendmodule\n").expect("write");
let half = talk(&session());
let lines = log_lines(&half);
assert_eq!(lines.iter().filter(|l| l.starts_with("cached: ")).count(), 1, "{lines:?}");
assert_eq!(lines.iter().filter(|l| l.starts_with("indexing: ")).count(), 1, "{lines:?}");
assert_eq!(ends(&half), ["0 files indexed", "2 files indexed, 1 from cache"], "{half:#?}");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&storage);
}
/// A 5 MB netlist — over the shipped `lucisv.largeFile.threshold` of 4 MiB,
/// so this needs no settings push to reach the fast path.
fn big_netlist() -> String {
let mut text = String::from("module netlist_top;\n wire needle;\n");
let mut n = 0u64;
while text.len() < 5 * 1024 * 1024 {
text.push_str(&format!(" inv_2 _{n}_ (.A(net{n}), .Y(needle));\n"));
n += 1;
}
text.push_str("endmodule\n");
text
}
#[test]
fn a_five_megabyte_buffer_opens_on_the_fast_path_over_the_wire() {
// The one thing the handler tests cannot show: that a buffer far too big
// to analyze goes through the real binary, over real framing, at the
// shipped default threshold — and that what comes back is colour for the
// window, an answer for the scans, an error for the format, and a decline
// for `semanticTokens/full`.
let dir = temp_dir("largefile");
let file = dir.join("netlist.v");
let text = big_netlist();
std::fs::write(&file, &text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/semanticTokens/range","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":1,"character":0}},"end":{{"line":3,"character":0}}}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":9}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let clock = std::time::Instant::now();
let messages = talk(&session);
let elapsed = clock.elapsed();
// The window painted, in the file's own coordinates.
let ranged = messages.iter().find(|m| m["id"] == 2).expect("range response");
let window = token_numbers(&ranged["result"]["data"]);
assert!(!window.is_empty(), "the viewport was coloured: {ranged:#?}");
assert_eq!(window.len() % 5, 0, "five numbers per token");
assert_eq!(window[0], 1, "starting on the window's own first line");
// `full` is declined, not answered — see the feature README for why an
// empty answer would cost the file all of its colour.
let full = messages.iter().find(|m| m["id"] == 3).expect("full response");
assert!(full["result"].is_null(), "no result at all: {full:#?}");
assert_eq!(full["error"]["code"], -32801, "ContentModified for a client that said nothing");
assert!(
full["error"]["message"].as_str().unwrap_or("").contains("largeFile.threshold"),
"{full:#?}"
);
// The scan answered, in this file.
let definition = messages.iter().find(|m| m["id"] == 4).expect("definition response");
let locations = definition["result"].as_array().expect("an array");
assert_eq!(locations.len(), 1, "{definition:#?}");
assert_eq!(locations[0]["range"]["start"]["line"], 1);
// Formatting refuses, out loud, and edits nothing.
let formatting = messages.iter().find(|m| m["id"] == 5).expect("formatting response");
assert_eq!(formatting["result"], serde_json::json!([]), "{formatting:#?}");
let shown: Vec<String> = messages
.iter()
.filter(|m| m["method"] == "window/showMessage")
.filter_map(|m| m["params"]["message"].as_str().map(str::to_string))
.collect();
assert_eq!(shown.len(), 1, "{shown:?}");
assert!(shown[0].contains("cannot format"), "{shown:?}");
// And the fast path announced itself once.
let announced: Vec<String> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str().map(str::to_string))
.filter(|line| line.starts_with("lucisv: large-file fast path:"))
.collect();
assert_eq!(announced.len(), 1, "{announced:?}");
// The whole session — 5 MB across a pipe and back — in a debug build.
// 0.4 s on the machine this was written on, and the bound is twenty-five
// times that: the point is that nothing here parses five megabytes of
// Verilog, which in a debug build is minutes.
assert!(elapsed.as_secs() < 10, "the session took {elapsed:?}");
eprintln!("5 MB fast-path session: {elapsed:?}");
let _ = std::fs::remove_dir_all(&dir);
}
+14 -2
View File
@@ -22,7 +22,7 @@ pub enum DefineKind {
}
/// One `` `define`` or `` `undef`` directive, as written.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Define {
/// Whether this entry defines the name or undefines it.
pub kind: DefineKind,
@@ -48,12 +48,24 @@ pub struct Define {
///
/// Redefinition is legal Verilog, so a name can have several definitions; they
/// are all kept and [`DefineTable::latest`] picks the last one.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DefineTable {
entries: Vec<Define>,
}
impl DefineTable {
/// A table from entries that are already known, in source order.
///
/// The inverse of [`DefineTable::entries`], for the one caller that has a
/// file's directives without the file's tokens: the workspace index's
/// persistent cache, which stores what a parse found and restores it
/// (`docs/features/index-persistence/README.md`). Nothing is re-derived
/// here — `collect_defines` is still the only thing that *reads* a table
/// out of a file.
pub fn from_entries(entries: Vec<Define>) -> DefineTable {
DefineTable { entries }
}
/// Every recorded directive, `` `undef``s included, in source order.
pub fn entries(&self) -> &[Define] {
&self.entries
+123
View File
@@ -0,0 +1,123 @@
//! Finding class declarations in a parse tree — one walk, two readers.
//!
//! `type_hierarchy.rs` wants every class in a file so it can build a hierarchy
//! item for the one the cursor names; the workspace index wants the same walk
//! so it can record who extends whom as it builds
//! (`docs/features/incremental-index/README.md`). One walk here, so the census
//! the index holds and the declaration the hierarchy shows can never disagree.
//!
//! **Lifted from `lucisv_server::type_hierarchy` on 2026-08-27**, unchanged by
//! the move.
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
use vlog_parser::TextRange;
/// One class declaration: the node, and the extent of the whole
/// `class ... endclass` it was written as.
#[derive(Clone, Copy)]
pub struct Decl<'a> {
/// The declaration node, for its name and its `extends` clause.
pub class: &'a ClassDecl,
/// Code extent of the declaration, attributes included — what a type
/// hierarchy item's `range` is.
pub span: TextRange,
}
/// Every class declaration in `items`, wherever a class may be written: at file
/// scope, inside a `package`, inside a `module`, and nested inside another
/// class.
pub fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
let mut out = Vec::new();
collect(items, &mut out);
out
}
/// The base class one declaration names, as written — `None` when the header
/// has no `extends`.
///
/// The name is the bare base: `extends base #(8)` reads `base`, because the
/// parser keeps the parameter overrides on their own field, so a parameterized
/// base needs no unwrapping here.
pub fn extends_name(class: &ClassDecl) -> Option<&str> {
class.extends.as_ref().map(|extends| extends.name.as_str())
}
fn collect<'a>(items: &'a [Item], out: &mut Vec<Decl<'a>>) {
for item in items {
match &item.kind {
ItemKind::Class(class) => {
out.push(Decl { class, span: item.span });
collect(&class.items, out);
}
ItemKind::Package { items, .. } => collect(items, out),
ItemKind::Module(module) => collect(&module.items, out),
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
/// Every class name a file declares, in walk order, with its base.
fn declared(text: &str) -> Vec<(String, String)> {
let (tree, _) = parse_source_tolerant(text);
declarations(&tree.items)
.iter()
.map(|decl| {
(decl.class.name.clone(), extends_name(decl.class).unwrap_or("-").to_string())
})
.collect()
}
#[test]
fn a_class_is_found_wherever_it_may_be_written() {
let text = "\
class top extends base;
class nested extends top;
endclass
endclass
package p;
class in_pkg extends top;
endclass
endpackage
module m;
class in_mod;
endclass
endmodule
";
assert_eq!(
declared(text),
[
("top".to_string(), "base".to_string()),
("nested".to_string(), "top".to_string()),
("in_pkg".to_string(), "top".to_string()),
("in_mod".to_string(), "-".to_string()),
]
);
}
#[test]
fn a_parameterized_base_names_the_bare_class() {
assert_eq!(
declared("class d extends b #(8);\nendclass\n"),
[("d".to_string(), "b".to_string())]
);
}
#[test]
fn a_declarations_extent_contains_its_own_name() {
let text = "class first;\nendclass\n\nclass second;\nendclass\n";
let (tree, _) = parse_source_tolerant(text);
let decls = declarations(&tree.items);
assert_eq!(decls.len(), 2);
for decl in &decls {
assert!(decl.span.start <= decl.class.name_span.start);
assert!(decl.class.name_span.end <= decl.span.end);
}
}
}
+480
View File
@@ -0,0 +1,480 @@
//! [`FileFacts`] as one line of text: the format the index cache stores a
//! parse's result in, and reads it back from.
//!
//! Hand-rolled, because the alternative is a serialization dependency in a
//! crate that has one dependency and it is the parser. The shape is the one
//! `lucisv_core::cache` established for the formatter's store — tab-separated
//! fields on one line, so a torn write is a line without a newline and a
//! record that does not parse is a record that is dropped — with lists
//! length-prefixed rather than nested, so reading a record is one pass over a
//! flat token stream and nothing is ambiguous.
//!
//! **Anything that changes what a record holds, or how it is written, bumps
//! [`FACTS_FORMAT`].** A record written by another format is not read at all;
//! see `docs/features/index-persistence/README.md` for why the cache would
//! rather redo the work than guess.
use std::path::PathBuf;
use vlog_parser::defines::{Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use crate::model::SymbolKind;
use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact};
/// 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;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
///
/// `None` for a path that cannot be written on a line of text — not UTF-8,
/// or holding a tab or a newline. Such a file is simply never cached, the
/// same answer `lucisv_core::cache` gives for the same shape of path.
/// Every *other* string a record holds is escaped instead, because a macro
/// body really can contain a tab.
pub fn encode(&self) -> Option<String> {
let path = self.path.to_str()?;
let mut out = Writer::default();
out.text(path);
out.tag("D", self.defines.entries().len());
for define in self.defines.entries() {
out.define(define);
}
out.tag("U", self.units.len());
for decl in &self.units {
out.decl(decl);
}
out.tag("M", self.members.len());
for (unit, decl) in &self.members {
out.text(unit);
out.decl(decl);
}
out.tag("I", self.instantiations.len());
for (module, site) in &self.instantiations {
out.text(module);
out.site(&site.owner);
out.range(site.site_span);
}
out.tag("S", self.subclasses.len());
for (base, subclass) in &self.subclasses {
out.text(base);
out.site(subclass);
}
out.tag("R", self.references.len());
for reference in &self.references {
out.reference(reference);
}
Some(out.out)
}
/// The facts a record describes, or `None` for anything that is not
/// exactly one whole record of this format.
///
/// Strict on purpose, in both directions: a field missing, a number that
/// does not parse, a kind this version has no name for, a count that
/// outruns the line, **or a field left over at the end** all mean the same
/// thing — this is not a record this version wrote, so nothing is taken
/// from it. A dropped record costs one file's parse; a half-read one would
/// cost correctness.
pub fn decode(line: &str) -> Option<FileFacts> {
let mut input = Reader::new(line);
let path = PathBuf::from(input.text()?);
let mut defines = Vec::new();
for _ in 0..input.tag("D")? {
defines.push(input.define()?);
}
let mut units = Vec::new();
for _ in 0..input.tag("U")? {
units.push(input.decl()?);
}
let mut members = Vec::new();
for _ in 0..input.tag("M")? {
members.push((input.text()?, input.decl()?));
}
let mut instantiations = Vec::new();
for _ in 0..input.tag("I")? {
let module = input.text()?;
let owner = input.site()?;
instantiations.push((module, SiteFact { owner, site_span: input.range()? }));
}
let mut subclasses = Vec::new();
for _ in 0..input.tag("S")? {
subclasses.push((input.text()?, input.site()?));
}
let mut references = Vec::new();
for _ in 0..input.tag("R")? {
references.push(input.reference()?);
}
if !input.done() {
return None;
}
Some(FileFacts {
path,
defines: DefineTable::from_entries(defines),
units,
members,
instantiations,
subclasses,
references,
})
}
}
/// The path a record is for, without decoding the rest of it.
///
/// A store keyed by path has to read this out of every record it holds, and
/// only ever decodes the handful it is asked for — so the cheap half of the
/// format is public separately from [`FileFacts::decode`]. `None` for a record
/// whose first field is not a readable path, which is a record that would not
/// decode either.
pub fn record_path(record: &str) -> Option<PathBuf> {
let field = record.split('\t').next()?;
Some(PathBuf::from(unescape(field)?))
}
/// A record under construction: fields pushed in order, separated by tabs.
#[derive(Default)]
struct Writer {
out: String,
/// Whether a field has been written yet, so the separator goes *between*
/// fields — asked of a flag rather than of `out.is_empty()`, which would
/// be wrong for a first field that is itself empty.
written: bool,
}
impl Writer {
/// One string field, escaped.
fn text(&mut self, text: &str) {
self.field();
for ch in text.chars() {
match ch {
'\\' => self.out.push_str("\\\\"),
'\t' => self.out.push_str("\\t"),
'\n' => self.out.push_str("\\n"),
'\r' => self.out.push_str("\\r"),
_ => self.out.push(ch),
}
}
}
/// One number field.
fn num(&mut self, n: u32) {
self.field();
self.out.push_str(&n.to_string());
}
/// A list's marker and its length — the length prefix that makes the
/// stream flat and still unambiguous.
fn tag(&mut self, tag: &str, len: usize) {
self.field();
self.out.push_str(tag);
self.num(len as u32);
}
fn range(&mut self, range: TextRange) {
self.num(range.start);
self.num(range.end);
}
fn decl(&mut self, decl: &Decl) {
self.text(&decl.name);
self.field();
self.out.push_str(kind_name(decl.kind));
self.range(decl.name_span);
}
fn site(&mut self, site: &DeclSite) {
self.text(&site.name);
self.range(site.name_span);
self.range(site.span);
}
fn define(&mut self, define: &Define) {
self.field();
self.out.push(match define.kind {
DefineKind::Define => 'd',
DefineKind::Undef => 'u',
});
self.text(&define.name);
match &define.params {
// A macro with no parameter list at all is not a macro with an
// empty one — `` `define A x`` against `` `define A() x`` — so the
// two cannot share a spelling.
None => {
self.field();
self.out.push('-');
}
Some(params) => {
self.num(params.len() as u32);
for param in params {
self.text(param);
}
}
}
self.text(&define.body);
self.range(define.span);
self.range(define.name_span);
}
fn reference(&mut self, reference: &ReferenceFact) {
match reference {
ReferenceFact::Local { definition, occurrence } => {
self.field();
self.out.push('l');
self.range(*definition);
self.range(*occurrence);
}
ReferenceFact::External { name, paths, occurrence } => {
self.field();
self.out.push('e');
self.text(name);
self.num(paths.len() as u32);
for path in paths {
self.text(path);
}
self.range(*occurrence);
}
}
}
/// The separator before every field but the first.
fn field(&mut self) {
if self.written {
self.out.push('\t');
}
self.written = true;
}
}
/// A record being read, one field at a time.
struct Reader<'a> {
fields: Vec<&'a str>,
at: usize,
}
impl<'a> Reader<'a> {
fn new(line: &'a str) -> Reader<'a> {
Reader { fields: line.split('\t').collect(), at: 0 }
}
fn next(&mut self) -> Option<&'a str> {
let field = self.fields.get(self.at)?;
self.at += 1;
Some(field)
}
/// Whether every field has been read — the check that makes a record with
/// something extra on the end invalid rather than merely surprising.
fn done(&self) -> bool {
self.at == self.fields.len()
}
fn text(&mut self) -> Option<String> {
unescape(self.next()?)
}
fn num(&mut self) -> Option<u32> {
self.next()?.parse().ok()
}
fn range(&mut self) -> Option<TextRange> {
Some(TextRange::new(self.num()?, self.num()?))
}
/// A list's length, once its marker has been confirmed. The marker is what
/// turns a misaligned read into a dropped record instead of a plausible
/// one.
fn tag(&mut self, tag: &str) -> Option<usize> {
if self.next()? != tag {
return None;
}
Some(self.num()? as usize)
}
fn decl(&mut self) -> Option<Decl> {
let name = self.text()?;
let kind = kind_of(self.next()?)?;
Some(Decl { name, name_span: self.range()?, kind })
}
fn site(&mut self) -> Option<DeclSite> {
Some(DeclSite { name: self.text()?, name_span: self.range()?, span: self.range()? })
}
fn define(&mut self) -> Option<Define> {
let kind = match self.next()? {
"d" => DefineKind::Define,
"u" => DefineKind::Undef,
_ => return None,
};
let name = self.text()?;
let params = match self.next()? {
"-" => None,
count => {
let count: u32 = count.parse().ok()?;
let mut params = Vec::new();
for _ in 0..count {
params.push(self.text()?);
}
Some(params)
}
};
Some(Define {
kind,
name,
params,
body: self.text()?,
span: self.range()?,
name_span: self.range()?,
})
}
fn reference(&mut self) -> Option<ReferenceFact> {
match self.next()? {
"l" => {
Some(ReferenceFact::Local { definition: self.range()?, occurrence: self.range()? })
}
"e" => {
let name = self.text()?;
let count = self.num()? as usize;
let mut paths = Vec::with_capacity(count);
for _ in 0..count {
paths.push(self.text()?);
}
Some(ReferenceFact::External { name, paths, occurrence: self.range()? })
}
_ => None,
}
}
}
/// One escaped string field, back as it was written. `None` for an escape
/// this format does not write, which is a record it did not write either.
fn unescape(field: &str) -> Option<String> {
let mut out = String::with_capacity(field.len());
let mut chars = field.chars();
while let Some(ch) = chars.next() {
if ch != '\\' {
out.push(ch);
continue;
}
out.push(match chars.next()? {
'\\' => '\\',
't' => '\t',
'n' => '\n',
'r' => '\r',
_ => return None,
});
}
Some(out)
}
/// A [`SymbolKind`]'s name in a record. Written out rather than numbered, so
/// a variant inserted in the middle of the enum cannot silently turn one kind
/// into another — and a name this version does not know drops the record.
fn kind_name(kind: SymbolKind) -> &'static str {
match kind {
SymbolKind::Module => "module",
SymbolKind::Package => "package",
SymbolKind::Port => "port",
SymbolKind::Net => "net",
SymbolKind::Var => "var",
SymbolKind::Param => "param",
SymbolKind::Genvar => "genvar",
SymbolKind::Typedef => "typedef",
SymbolKind::EnumVariant => "enumvariant",
SymbolKind::Function => "function",
SymbolKind::Task => "task",
SymbolKind::TfArg => "tfarg",
SymbolKind::Instance => "instance",
SymbolKind::Block => "block",
SymbolKind::StructMember => "structmember",
SymbolKind::Class => "class",
}
}
/// The inverse of [`kind_name`], total in the other direction: anything else
/// is not a kind this version writes.
fn kind_of(name: &str) -> Option<SymbolKind> {
Some(match name {
"module" => SymbolKind::Module,
"package" => SymbolKind::Package,
"port" => SymbolKind::Port,
"net" => SymbolKind::Net,
"var" => SymbolKind::Var,
"param" => SymbolKind::Param,
"genvar" => SymbolKind::Genvar,
"typedef" => SymbolKind::Typedef,
"enumvariant" => SymbolKind::EnumVariant,
"function" => SymbolKind::Function,
"task" => SymbolKind::Task,
"tfarg" => SymbolKind::TfArg,
"instance" => SymbolKind::Instance,
"block" => SymbolKind::Block,
"structmember" => SymbolKind::StructMember,
"class" => SymbolKind::Class,
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Every kind round-trips, and the two directions are inverses. If a
/// variant is added to `SymbolKind` this fails to compile in `kind_name`
/// first, which is the point of writing both matches out.
#[test]
fn every_symbol_kind_has_a_name_and_only_its_own() {
let kinds = [
SymbolKind::Module,
SymbolKind::Package,
SymbolKind::Port,
SymbolKind::Net,
SymbolKind::Var,
SymbolKind::Param,
SymbolKind::Genvar,
SymbolKind::Typedef,
SymbolKind::EnumVariant,
SymbolKind::Function,
SymbolKind::Task,
SymbolKind::TfArg,
SymbolKind::Instance,
SymbolKind::Block,
SymbolKind::StructMember,
SymbolKind::Class,
];
let mut names: Vec<&str> = kinds.iter().map(|k| kind_name(*k)).collect();
for kind in kinds {
assert_eq!(kind_of(kind_name(kind)), Some(kind));
}
names.sort_unstable();
let before = names.len();
names.dedup();
assert_eq!(names.len(), before, "two kinds share a name: {names:?}");
assert_eq!(kind_of("Module"), None, "the names are exact");
assert_eq!(kind_of(""), None);
}
#[test]
fn every_escape_survives_a_round_trip() {
for text in ["", "plain", "a\tb", "a\nb", "a\\b", "a\\\\tb", "\r\n", "\\", "üñî"] {
let mut out = Writer::default();
out.text(text);
let field = out.out;
assert_eq!(unescape(&field).as_deref(), Some(text), "{text:?}");
assert!(!field.contains('\t'), "a field never holds a raw tab: {field:?}");
assert!(!field.contains('\n'), "nor a newline: {field:?}");
}
}
#[test]
fn an_escape_this_format_does_not_write_is_not_read() {
assert_eq!(unescape("a\\qb"), None);
assert_eq!(unescape("trailing\\"), None);
}
}
@@ -11,6 +11,13 @@
//! Gate primitives are not instantiations here: `and (q, a, b)` is an
//! [`ItemKind::GateInstantiation`], names no module, and is nobody's edge in
//! the hierarchy.
//!
//! **Lifted from `lucisv_server` on 2026-08-27** so the workspace index can
//! record instantiation edges as it builds
//! (`docs/features/incremental-index/README.md`). The walk is the census —
//! what counts as one instantiation site — and a second copy of it in the
//! index would have been free to drift from the one the call hierarchy uses.
//! The code is unchanged by the move.
use vlog_parser::ast::{GenBlock, GenElse, Instantiation, Item, ItemKind, Module};
use vlog_parser::TextRange;
@@ -19,6 +26,7 @@ use vlog_parser::TextRange;
/// `module ... endmodule` it was written as.
#[derive(Clone, Copy)]
pub struct Decl<'a> {
/// The declaration node, for its name and its own items.
pub module: &'a Module,
/// Code extent of the declaration, attributes included — what a call
/// hierarchy item's `range` is.
@@ -27,6 +35,7 @@ pub struct Decl<'a> {
/// One module instantiation, and the module whose body it sits in.
pub struct Site<'a> {
/// The instantiation node: the module it names, and its connections.
pub inst: &'a Instantiation,
/// The innermost module the instantiation is written inside. `None` for
/// one written at file scope — illegal SystemVerilog, and reachable
+36 -9
View File
@@ -17,18 +17,23 @@
//! the simplifications taken.
mod bind;
pub mod classes;
mod facts;
pub mod instantiations;
mod model;
mod resolve;
mod scan;
mod workspace;
pub use facts::{record_path, FACTS_FORMAT};
pub use model::{
DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol,
SymbolId, SymbolKind,
};
pub use workspace::{
resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId, IndexCounts,
WorkspaceIndex, WorkspaceSymbol,
index_order, resolve_external, DeclSite, Def, Definition, DefinitionKey, ExternalResolutions,
ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge,
InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
};
use std::collections::HashMap;
@@ -43,6 +48,10 @@ pub struct Semantics {
references: Vec<Reference>,
/// symbol → indices into `references`, in source order.
uses: HashMap<SymbolId, Vec<usize>>,
/// Non-empty declaration-name spans, sorted by start for cursor lookup.
symbol_positions: Vec<(TextRange, SymbolId)>,
/// Non-empty reference-name spans, sorted by start for cursor lookup.
reference_positions: Vec<(TextRange, ReferenceId)>,
}
/// Build the symbol table for one parsed file. `src` must be the text the
@@ -74,7 +83,21 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
uses.entry(id).or_default().push(i);
}
}
Semantics { scopes, symbols, references, uses }
let mut symbol_positions: Vec<(TextRange, SymbolId)> = symbols
.iter()
.enumerate()
.filter(|(_, symbol)| !symbol.name_span.is_empty())
.map(|(i, symbol)| (symbol.name_span, SymbolId(i as u32)))
.collect();
symbol_positions.sort_by_key(|(span, _)| (span.start, span.end));
let mut reference_positions: Vec<(TextRange, ReferenceId)> = references
.iter()
.enumerate()
.filter(|(_, reference)| !reference.name_span.is_empty())
.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 }
}
/// Point every import at the package it names, when this file declares it.
@@ -125,21 +148,18 @@ impl Semantics {
/// 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> {
self.symbols.iter().position(|s| s.name_span.contains(offset)).map(|i| SymbolId(i as u32))
position_at(&self.symbol_positions, offset)
}
/// The use whose name covers `offset`.
pub fn reference_at(&self, offset: u32) -> Option<&Reference> {
self.references.iter().find(|r| r.name_span.contains(offset))
self.reference_id_at(offset).and_then(|id| self.reference(id))
}
/// The id of the use whose name covers `offset` — the key the workspace
/// index's overlay uses.
pub fn reference_id_at(&self, offset: u32) -> Option<ReferenceId> {
self.references
.iter()
.position(|r| r.name_span.contains(offset))
.map(|i| ReferenceId(i as u32))
position_at(&self.reference_positions, offset)
}
/// One use by id.
@@ -211,3 +231,10 @@ impl Semantics {
self.scopes.first().map_or(TextRange::empty(0), |s| s.span)
}
}
/// The source span covering `offset` in a non-overlapping, start-sorted table.
fn position_at<Id: Copy>(positions: &[(TextRange, Id)], offset: u32) -> Option<Id> {
let after = positions.partition_point(|(span, _)| span.start <= offset);
let (span, id) = positions.get(after.checked_sub(1)?)?;
span.contains(offset).then_some(*id)
}
+767 -70
View File
@@ -13,15 +13,16 @@
//! See `docs/features/workspace-index/README.md` for the resolution order,
//! the duplicate-name policy and the corpus numbers.
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::{collect_defines, Define, DefineTable};
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 crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
use crate::{analyze, Semantics};
use crate::{analyze, classes, instantiations, Semantics};
/// Index of a file in a [`WorkspaceIndex`], assigned in sorted path order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
@@ -38,6 +39,38 @@ pub struct Def {
pub kind: SymbolKind,
}
/// Stable identity of one indexed declaration inside the current index.
///
/// A [`FileId`] may move when a file is added or removed, so this key survives
/// only as long as the [`WorkspaceIndex`] that produced it. That is exactly the
/// lifetime of every merged table in the index; callers never persist it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DefinitionKey {
pub file: FileId,
pub name_start: u32,
pub name_end: u32,
}
impl DefinitionKey {
/// The key of an indexed definition.
pub fn of(def: &Def) -> DefinitionKey {
DefinitionKey {
file: def.file,
name_start: def.name_span.start,
name_end: def.name_span.end,
}
}
}
/// One indexed use of a declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReferenceSite {
/// The file the use is written in.
pub file: FileId,
/// Byte range of the referenced name inside that file.
pub name_span: TextRange,
}
/// One hit of [`WorkspaceIndex::workspace_symbols`].
#[derive(Debug, Clone)]
pub struct WorkspaceSymbol<'a> {
@@ -49,18 +82,80 @@ pub struct WorkspaceSymbol<'a> {
pub def: &'a Def,
}
/// One end of an edge: a declaration another file's edge points at or hangs
/// off. The instantiating module of an instantiation edge, the extending class
/// of an inheritance edge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclSite {
/// The declared name, as written.
pub name: String,
/// Byte range of that name in its file.
pub name_span: TextRange,
/// Byte range of the whole declaration — `module … endmodule`, `class …
/// endclass` — which is what a hierarchy item's `range` is.
pub span: TextRange,
}
/// One place the workspace instantiates a module.
///
/// The census this records is `callHierarchy/incomingCalls`'s, unchanged: one
/// edge per `Instantiation` node however many instances it declares, textual
/// rather than elaborated (a `generate for` body is one site, both arms of an
/// `` `ifdef`` are sites), matched by the name as written. An instantiation at
/// **file scope** is not an edge: it has no enclosing module to be the caller,
/// which is the rule `hierarchy::callers_in` has always applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstantiationEdge {
/// The file the instantiation is written in.
pub file: FileId,
/// The module it is written inside — the caller.
pub owner: DeclSite,
/// Byte range of the instantiated module's name at the site.
pub site_span: TextRange,
}
/// One class that extends another.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InheritanceEdge {
/// The file the extending class is declared in.
pub file: FileId,
/// The extending class.
pub subclass: DeclSite,
}
/// What every file in the workspace declares: the units other files can name,
/// their exported members, and their `` `define`` tables.
/// their exported members, their `` `define`` tables, and the edges between
/// them — who instantiates which module, and who extends which class.
///
/// The index keeps every file's contribution **unmerged** beside the merged
/// tables ([`FileFacts`]), which is what lets one file be replaced without
/// re-reading the workspace ([`WorkspaceIndex::update_file`]). The price is
/// memory: the same names and spans the tables hold, held once more per file.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceIndex {
/// Indexed by [`FileId`], sorted by path.
/// Indexed by [`FileId`], sorted by path. The paths of `facts`, kept flat
/// so [`WorkspaceIndex::files`] can hand out a slice.
files: Vec<PathBuf>,
/// What each file contributes, parallel to `files` and in the same order.
/// A [`FileId`] is an index into both.
facts: Vec<FileFacts>,
/// File-scope name → every declaration of it, in disambiguation order.
units: BTreeMap<String, Vec<Def>>,
/// Unit name → member name → every declaration of it.
members: BTreeMap<String, BTreeMap<String, Vec<Def>>>,
/// Indexed by [`FileId`], parallel to `files`.
defines: Vec<DefineTable>,
/// Instantiated module name → every site, in file order then walk order.
instantiations: BTreeMap<String, Vec<InstantiationEdge>>,
/// Base class name → every class extending it, in file order then walk
/// order.
subclasses: BTreeMap<String, Vec<InheritanceEdge>>,
/// Macro name → `(file, entry-in-that-file)` for each definition.
macro_definitions: BTreeMap<String, Vec<(FileId, usize)>>,
/// Declaration → every unambiguous use, in file then source order.
reference_sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>>,
/// Declarations touched by at least one ambiguous external reference.
/// Find-references refuses those rather than assigning the use to one of
/// several equally plausible declarations.
ambiguous_references: HashSet<DefinitionKey>,
}
impl WorkspaceIndex {
@@ -70,23 +165,21 @@ impl WorkspaceIndex {
/// contributes every declaration that *did* parse.
///
/// Pure: the same inputs always give the same index, whatever order they
/// arrive in. Re-scanning a changed workspace means calling this again —
/// there is no incremental update (TODO.md §6 defers that to salsa).
/// arrive in. A workspace where **one** file changed does not need this at
/// all — see [`WorkspaceIndex::update_file`], which produces exactly the
/// index this would have.
///
/// This is exactly [`index_order`] followed by an [`IndexBuilder`] loop,
/// and stays the API every caller that does not care to watch the build
/// should use. The [`index_order`] here saves parsing a duplicate path
/// twice; it is not what makes the result deterministic — the builder
/// sorts for itself.
pub fn build<'a>(files: impl IntoIterator<Item = (PathBuf, &'a str)>) -> WorkspaceIndex {
let mut sources: Vec<(PathBuf, &str)> = 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);
let mut index = WorkspaceIndex::default();
for (path, src) in sources {
let file = FileId(index.files.len() as u32);
index.files.push(path);
let (tree, defines) = parse_and_collect(src);
index.defines.push(defines);
index.add_file(file, &analyze(&tree, src));
let mut builder = IndexBuilder::new();
for (path, src) in index_order(files) {
builder.add_file(path, src);
}
index
builder.finish()
}
/// Every file the index covers, by [`FileId`].
@@ -99,6 +192,14 @@ impl WorkspaceIndex {
self.files.get(file.0 as usize).map(PathBuf::as_path)
}
/// The id of an indexed path.
pub fn file_id(&self, path: &Path) -> Option<FileId> {
self.files
.binary_search_by(|held| held.as_path().cmp(path))
.ok()
.map(|at| FileId(at as u32))
}
/// Every file-scope declaration of `name` — module, package or typedef —
/// in disambiguation order (by file path, then by position in the file).
/// More than one means the workspace really does declare the name twice.
@@ -122,9 +223,45 @@ impl WorkspaceIndex {
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
}
/// Every place the workspace instantiates `name`, in disambiguation order
/// — by file path, then in the order the sites are written.
///
/// This is the table `callHierarchy/incomingCalls` and the code lens read
/// instead of re-reading and re-parsing every in-scope file; see
/// [`InstantiationEdge`] for the census it records.
pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge] {
self.instantiations.get(name).map_or(&[], Vec::as_slice)
}
/// Every class extending `name`, in the same order.
pub fn subclasses_of(&self, name: &str) -> &[InheritanceEdge] {
self.subclasses.get(name).map_or(&[], Vec::as_slice)
}
/// Every instantiated module name the workspace names, with its sites.
pub fn instantiations(&self) -> impl Iterator<Item = (&str, &[InstantiationEdge])> {
self.instantiations.iter().map(|(name, edges)| (name.as_str(), edges.as_slice()))
}
/// Every extended class name the workspace names, with its subclasses.
pub fn subclasses(&self) -> impl Iterator<Item = (&str, &[InheritanceEdge])> {
self.subclasses.iter().map(|(name, edges)| (name.as_str(), edges.as_slice()))
}
/// What one file contributes to this index, by path.
///
/// The unmerged record — everything the file's parse found. Public so a
/// caller that persists those records can store the one an incremental
/// update just produced without parsing the file a second time
/// (`docs/features/index-persistence/README.md`).
pub fn facts_for(&self, path: &Path) -> Option<&FileFacts> {
let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?;
self.facts.get(at)
}
/// The `` `define`` table of one file.
pub fn defines(&self, file: FileId) -> Option<&DefineTable> {
self.defines.get(file.0 as usize)
self.facts.get(file.0 as usize).map(|facts| &facts.defines)
}
/// Every definition of a macro name anywhere in the workspace, in file
@@ -133,12 +270,25 @@ impl WorkspaceIndex {
/// this index models. A hover showing all of them is honest; picking one
/// silently would not be.
pub fn find_define(&self, name: &str) -> Vec<(FileId, &Define)> {
let mut out = Vec::new();
for (i, table) in self.defines.iter().enumerate() {
let file = FileId(i as u32);
out.extend(table.all(name).into_iter().map(|d| (file, d)));
}
out
self.macro_definitions
.get(name)
.into_iter()
.flatten()
.filter_map(|&(file, entry)| {
let define = self.facts.get(file.0 as usize)?.defines.entries().get(entry)?;
Some((file, define))
})
.collect()
}
/// Every indexed use of `def`, excluding its declaration.
pub fn references_to(&self, def: &Def) -> &[ReferenceSite] {
self.reference_sites.get(&DefinitionKey::of(def)).map_or(&[], Vec::as_slice)
}
/// Whether at least one use could name `def` or another declaration equally.
pub fn references_are_ambiguous(&self, def: &Def) -> bool {
self.ambiguous_references.contains(&DefinitionKey::of(def))
}
/// Every indexed name containing `query`, case-insensitively — LSP's
@@ -190,7 +340,9 @@ impl WorkspaceIndex {
.filter(|d| d.kind == SymbolKind::Class)
.count(),
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
defines: self.defines.iter().map(|t| t.entries().len()).sum(),
defines: self.facts.iter().map(|f| f.defines.entries().len()).sum(),
instantiations: self.instantiations.values().map(Vec::len).sum(),
inheritances: self.subclasses.values().map(Vec::len).sum(),
}
}
@@ -198,53 +350,593 @@ impl WorkspaceIndex {
self.units.values().flatten().filter(|d| d.kind == kind).count()
}
/// Record what one analyzed file declares.
fn add_file(&mut self, file: FileId, sem: &Semantics) {
let Some(file_scope) = sem.scope(sem.file_scope()) else {
return;
};
for &id in &file_scope.symbols {
let Some(unit) = sem.symbol(id) else {
continue;
};
if !is_unit(unit.kind) || unit.name_span.is_empty() {
continue;
// ------------------------------------------------------------------
// incremental update
// ------------------------------------------------------------------
/// Replace one file's contribution to the index — or add the file, when
/// the index does not hold it yet.
///
/// **The result is the index a full [`WorkspaceIndex::build`] over the same
/// file set would have produced, byte for byte**: same [`FileId`]s, same
/// disambiguation order, same member tables, same edges. That is the whole
/// contract, and it is what makes an incremental server safe. It holds by
/// construction rather than by care — the merge below is `finish`'s own
/// loop, over the same path-sorted records, restricted to the names this
/// file could have moved.
///
/// A [`FileId`] is a position in the path-sorted file list and nothing
/// else, so **adding a file renumbers the ones after it**. That is
/// deliberate: an id that meant a different thing depending on how the
/// index was arrived at would make "the same index" unprovable, and the
/// renumbering costs one merge pass over records already in memory — no
/// file is read and no file is re-parsed. Ids do not survive an add or a
/// remove; nothing in this workspace holds one across an update (the
/// 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);
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,
// and the file list has not, so ids are untouched.
Ok(at) => {
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
self.facts[at] = facts;
self.merge(Some(&affected));
}
// A file the index did not hold: every id from here on shifts, so
// every table is rebuilt from the records. No parse, no read.
Err(at) => {
self.files.insert(at, path);
self.facts.insert(at, facts);
self.merge(None);
}
self.units.entry(unit.name.clone()).or_default().push(Def {
file,
name_span: unit.name_span,
kind: unit.kind,
});
self.add_members(file, sem, unit);
}
}
/// Record the names another file may reach *into* this unit for.
fn add_members(&mut self, file: FileId, sem: &Semantics, unit: &Symbol) {
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
return;
/// Drop one file from the index, reporting whether it was there.
///
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
/// index a full build over the remaining files would have produced.
pub fn remove_file(&mut self, path: &Path) -> bool {
let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) else {
return false;
};
for &id in &scope.symbols {
let Some(member) = sem.symbol(id) else {
continue;
};
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
continue;
}
self.members
.entry(unit.name.clone())
.or_default()
.entry(member.name.clone())
.or_default()
.push(Def { file, name_span: member.name_span, kind: member.kind });
// 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 {
self.add_members(file, sem, member);
self.files.remove(at);
self.facts.remove(at);
self.merge(None);
true
}
/// Every observable this index answers, rendered as one comparable value.
///
/// The witness for the equivalence [`WorkspaceIndex::update_file`]
/// promises: two indexes are the same index exactly when their
/// fingerprints are equal. Public because the proof is worth writing in
/// more than one crate's tests — `lucisv_server` checks it against the
/// real corpus, this crate against crafted attacks.
pub fn fingerprint(&self) -> String {
let mut out = String::new();
for (id, path) in self.files.iter().enumerate() {
let defines = self.defines(FileId(id as u32)).map_or(0, |t| t.entries().len());
out.push_str(&format!("file {id} {} defines={defines}\n", path.display()));
}
for symbol in self.workspace_symbols("") {
out.push_str(&format!(
"sym {} in {:?} {:?} {}:{}..{}\n",
symbol.name,
symbol.container,
symbol.def.kind,
symbol.def.file.0,
symbol.def.name_span.start,
symbol.def.name_span.end
));
}
for (definition, sites) in &self.reference_sites {
for site in sites {
out.push_str(&format!(
"ref {}:{}..{} <- {}:{}..{}\n",
definition.file.0,
definition.name_start,
definition.name_end,
site.file.0,
site.name_span.start,
site.name_span.end
));
}
}
let mut ambiguous: Vec<DefinitionKey> = self.ambiguous_references.iter().copied().collect();
ambiguous.sort();
for definition in ambiguous {
out.push_str(&format!(
"ambiguous-ref {}:{}..{}\n",
definition.file.0, definition.name_start, definition.name_end
));
}
for (name, edges) in self.instantiations() {
for edge in edges {
out.push_str(&format!(
"inst {name} {} in {}@{}..{} site {}..{}\n",
edge.file.0,
edge.owner.name,
edge.owner.name_span.start,
edge.owner.span.end,
edge.site_span.start,
edge.site_span.end
));
}
}
for (name, edges) in self.subclasses() {
for edge in edges {
out.push_str(&format!(
"extends {name} {} {}@{}..{}\n",
edge.file.0,
edge.subclass.name,
edge.subclass.name_span.start,
edge.subclass.span.end
));
}
}
out
}
/// Rebuild the merged tables from the per-file records.
///
/// `affected` names the keys that may have moved; `None` means all of
/// them. Either way this is one loop over the path-sorted records pushing
/// in the order it meets them, which is the *only* place any table's order
/// is decided — so a restricted merge and a whole one agree by
/// construction, and both agree with [`IndexBuilder::finish`].
fn merge(&mut self, affected: Option<&Affected>) {
match affected {
None => {
self.units.clear();
self.members.clear();
self.instantiations.clear();
self.subclasses.clear();
self.macro_definitions.clear();
}
Some(affected) => {
for name in &affected.units {
self.units.remove(name);
}
for name in &affected.containers {
self.members.remove(name);
}
for name in &affected.modules {
self.instantiations.remove(name);
}
for name in &affected.bases {
self.subclasses.remove(name);
}
for name in &affected.macros {
self.macro_definitions.remove(name);
}
}
}
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for decl in &facts.units {
if affected.is_some_and(|a| !a.units.contains(&decl.name)) {
continue;
}
self.units.entry(decl.name.clone()).or_default().push(decl.def(file));
}
for (unit, decl) in &facts.members {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
self.members
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
.or_default()
.push(decl.def(file));
}
for (module, edge) in &facts.instantiations {
if affected.is_some_and(|a| !a.modules.contains(module)) {
continue;
}
self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
});
}
for (base, subclass) in &facts.subclasses {
if affected.is_some_and(|a| !a.bases.contains(base)) {
continue;
}
self.subclasses
.entry(base.clone())
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
{
continue;
}
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
}
}
// A changed declaration can change how references in any file resolve,
// even when only one file's facts moved. Re-resolving compact facts is
// one in-memory pass; no source is read or parsed.
self.merge_references();
}
/// Rebuild declaration-to-occurrence postings from compact per-file facts.
fn merge_references(&mut self) {
let mut sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>> = BTreeMap::new();
let mut ambiguous: HashSet<DefinitionKey> = HashSet::new();
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for reference in &facts.references {
let site = ReferenceSite { file, name_span: reference.occurrence() };
match reference {
ReferenceFact::Local { definition, .. } => {
let key = DefinitionKey {
file,
name_start: definition.start,
name_end: definition.end,
};
sites.entry(key).or_default().push(site);
}
ReferenceFact::External { name, paths, .. } => {
match follow_paths(self, name, paths) {
ExternalTarget::Resolved(def) => {
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
}
ExternalTarget::Ambiguous(defs) => {
ambiguous.extend(defs.iter().map(DefinitionKey::of));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
}
self.reference_sites = sites;
self.ambiguous_references = ambiguous;
}
}
/// The table keys one file's records can move, so a merge after replacing that
/// file can leave every other key alone.
#[derive(Debug, Default)]
struct Affected {
units: HashSet<String>,
/// Keys of the `members` table — the *unit* a member is exported by, not
/// the member itself. A whole unit's sub-table is the smallest thing worth
/// rebuilding: one file adding a member to a package cannot move any other
/// package.
containers: HashSet<String>,
modules: HashSet<String>,
bases: HashSet<String>,
macros: HashSet<String>,
}
impl Affected {
fn of(facts: &FileFacts) -> Affected {
let mut out = Affected::default();
out.add(facts);
out
}
fn add(&mut self, facts: &FileFacts) {
self.units.extend(facts.units.iter().map(|decl| decl.name.clone()));
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
}
}
/// One declaration as a single file contributes it, before that file has a
/// [`FileId`]. The id depends on where the file's path sorts among all of
/// them, which is not known until [`IndexBuilder::finish`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Decl {
pub(crate) name: String,
pub(crate) name_span: TextRange,
pub(crate) kind: SymbolKind,
}
impl Decl {
fn of(symbol: &Symbol) -> Decl {
Decl { name: symbol.name.clone(), name_span: symbol.name_span, kind: symbol.kind }
}
fn def(&self, file: FileId) -> Def {
Def { file, name_span: self.name_span, kind: self.kind }
}
}
/// One instantiation site as a single file contributes it — an
/// [`InstantiationEdge`] without its [`FileId`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SiteFact {
pub(crate) owner: DeclSite,
pub(crate) site_span: TextRange,
}
/// Everything one file contributes to an index: read while the file is parsed,
/// merged in path order by [`IndexBuilder::finish`].
///
/// This is the same data the finished index holds, kept per file rather than
/// merged, which is what lets the merge happen in an order the caller does not
/// choose — and, since it is *everything* one file contributes, the one thing
/// worth storing between two sessions. [`FileFacts::encode`] and
/// [`FileFacts::decode`] are that store's format; a decoded record put back
/// through [`IndexBuilder::add_facts`] gives the index the file's parse would
/// have, without the parse (`docs/features/index-persistence/README.md`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileFacts {
pub(crate) path: PathBuf,
pub(crate) defines: DefineTable,
/// File-scope declarations, in declaration order.
pub(crate) units: Vec<Decl>,
/// Members, each under the name of the unit that exports it, in the order
/// the scope tree yields them.
pub(crate) members: Vec<(String, Decl)>,
/// Instantiation sites, each under the name of the module instantiated, in
/// walk order.
pub(crate) instantiations: Vec<(String, SiteFact)>,
/// Class declarations with a base, each under the base's name, in walk
/// order.
pub(crate) subclasses: Vec<(String, DeclSite)>,
/// Uses of declarations another file may name, stored before file ids and
/// cross-file candidates have been resolved by the finished index.
pub(crate) references: Vec<ReferenceFact>,
}
/// One reference contribution before the workspace's declarations are merged.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ReferenceFact {
/// A use resolved to an exported declaration in this same file.
Local { definition: TextRange, occurrence: TextRange },
/// A use whose recorded paths need the workspace declaration tables.
External { name: String, paths: Vec<String>, occurrence: TextRange },
}
impl ReferenceFact {
fn occurrence(&self) -> TextRange {
match self {
ReferenceFact::Local { occurrence, .. }
| ReferenceFact::External { occurrence, .. } => *occurrence,
}
}
}
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.
pub fn of(path: PathBuf, src: &str) -> FileFacts {
facts_of(path, src)
}
/// The file these facts were read from.
pub fn path(&self) -> &Path {
&self.path
}
}
/// Parse one file and read off what it declares and what it points at.
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines) = parse_and_collect(src);
let sem = analyze(&tree, src);
let mut facts = FileFacts {
path,
defines,
units: Vec::new(),
members: Vec::new(),
instantiations: edges_of(&tree),
subclasses: inheritance_of(&tree),
references: Vec::new(),
};
let Some(file_scope) = sem.scope(sem.file_scope()) else {
return facts;
};
for &id in &file_scope.symbols {
let Some(unit) = sem.symbol(id) else {
continue;
};
if !is_unit(unit.kind) || unit.name_span.is_empty() {
continue;
}
facts.units.push(Decl::of(unit));
collect_members(&sem, unit, &mut facts.members);
}
let exported: HashSet<(u32, u32)> = facts
.units
.iter()
.map(|decl| (decl.name_span.start, decl.name_span.end))
.chain(facts.members.iter().map(|(_, decl)| (decl.name_span.start, decl.name_span.end)))
.collect();
for reference in sem.references() {
let fact = match &reference.resolution {
Resolution::Resolved(id) => sem.symbol(*id).and_then(|symbol| {
let definition = symbol.name_span;
exported
.contains(&(definition.start, definition.end))
.then_some(ReferenceFact::Local { definition, occurrence: reference.name_span })
}),
Resolution::ExternalCandidate { paths }
| Resolution::InheritedCandidate { paths, .. }
if !paths.is_empty() =>
{
Some(ReferenceFact::External {
name: reference.name.clone(),
paths: paths.clone(),
occurrence: reference.name_span,
})
}
_ => None,
};
if let Some(fact) = fact {
facts.references.push(fact);
}
}
facts
}
/// Every instantiation one file writes, under the name of the module it
/// instantiates.
///
/// The walk is [`crate::instantiations::sites`] — the same one the call
/// 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)> {
instantiations::sites(&tree.items)
.into_iter()
.filter_map(|site| {
let owner = site.owner?;
Some((
site.inst.module.clone(),
SiteFact {
owner: DeclSite {
name: owner.module.name.clone(),
name_span: owner.module.name_span,
span: owner.span,
},
site_span: site.inst.module_span,
},
))
})
.collect()
}
/// Every class one file declares that extends another, under the base's name.
fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> {
classes::declarations(&tree.items)
.into_iter()
.filter_map(|decl| {
let base = classes::extends_name(decl.class)?;
Some((
base.to_string(),
DeclSite {
name: decl.class.name.clone(),
name_span: decl.class.name_span,
span: decl.span,
},
))
})
.collect()
}
/// Read off the names another file may reach *into* this unit for.
fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) {
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
return;
};
for &id in &scope.symbols {
let Some(member) = sem.symbol(id) else {
continue;
};
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
continue;
}
out.push((unit.name.clone(), Decl::of(member)));
// 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);
}
}
}
/// The file list an index will be built from, in the order it is built in:
/// sorted by path, one entry per path (a path handed over twice is one file,
/// and the first copy wins).
///
/// Exposed because a caller that wants to *watch* a build — the server's
/// indexing progress bar — has to know the work list, and its length, before
/// 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();
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);
sources
}
/// A [`WorkspaceIndex`] under construction, one file at a time.
///
/// The same work [`WorkspaceIndex::build`] does — that function is a loop over
/// this one — split so a caller can do something between two files, which in
/// practice means reporting progress. A file can be added here and nothing
/// else; replacing or dropping one is [`WorkspaceIndex::update_file`] /
/// [`WorkspaceIndex::remove_file`], on the finished index.
///
/// **The order files are added in cannot change the result.** `add_file`
/// parses its file and keeps what it declares to itself; `finish` sorts those
/// per-file records by path — [`index_order`]'s rule, applied where no caller
/// can bypass it — and only then hands out [`FileId`]s and merges the
/// declarations. So the file ids, the disambiguation order of a name declared
/// twice, and every member table are the path order, whoever calls this and in
/// whatever sequence. (Before 2026-08-27 the ordering was a doc comment asking
/// callers to feed it [`index_order`]'s list, and a caller who did not silently
/// got a different index.)
#[derive(Debug, Clone, Default)]
pub struct IndexBuilder {
/// One record per `add_file` call, in call order. Sorted by `finish`.
files: Vec<FileFacts>,
}
impl IndexBuilder {
/// An empty index to add files to.
pub fn new() -> IndexBuilder {
IndexBuilder::default()
}
/// Parse one file and record what it declares.
///
/// The parse happens here, not in `finish`, so a caller reporting progress
/// between calls is reporting work that has really been done.
pub fn add_file(&mut self, path: PathBuf, src: &str) {
self.add_facts(FileFacts::of(path, src));
}
/// Add one file whose facts are already known — restored from a cache
/// rather than read from the file's text.
///
/// Exactly [`IndexBuilder::add_file`] with the parse already done: the
/// record is what that parse produces, so an index built from records and
/// an index built from text are the same index. Whether the record really
/// describes the file is the caller's business, and the caller answers it
/// by keying its store on the file's content
/// (`docs/features/index-persistence/README.md`).
pub fn add_facts(&mut self, facts: FileFacts) {
self.files.push(facts);
}
/// The finished index: the files sorted by path, then merged.
///
/// `sort_by` is stable and `dedup_by` keeps the first of a run, so a path
/// added twice is one file and the first copy wins — exactly what
/// [`index_order`] does to the list it is handed.
pub fn finish(mut self) -> WorkspaceIndex {
self.files.sort_by(|a, b| a.path.cmp(&b.path));
self.files.dedup_by(|a, b| a.path == b.path);
let mut index = WorkspaceIndex {
files: self.files.iter().map(|facts| facts.path.clone()).collect(),
facts: self.files,
..WorkspaceIndex::default()
};
index.merge(None);
index
}
}
@@ -267,6 +959,11 @@ pub struct IndexCounts {
pub members: usize,
/// `` `define``/`` `undef`` directives recorded across all files.
pub defines: usize,
/// Instantiation sites recorded — one per written statement, inside a
/// module.
pub instantiations: usize,
/// `extends` edges recorded, one per class that names a base.
pub inheritances: usize,
}
/// Parse one file and read its `` `define`` table off the same token stream.
+808 -3
View File
@@ -1,11 +1,11 @@
//! Behavior of the workspace index: cross-file definitions, duplicate names,
//! package members, and the corpus acceptance run.
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, Def, Definition, ExternalTarget, FileId, Resolution, Semantics,
SymbolKind, WorkspaceIndex,
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
Semantics, SymbolKind, WorkspaceIndex,
};
/// Build an index from `(path, source)` literals, as a server would from disk.
@@ -282,6 +282,124 @@ fn the_same_path_twice_is_one_file() {
assert_eq!(ws.units("m").len(), 1);
}
#[test]
fn the_incremental_builder_is_what_build_is_made_of() {
// `WorkspaceIndex::build` is now `index_order` plus a loop over
// `IndexBuilder`, so a caller that runs that loop itself — the server,
// which reports progress between two files — must get the same index down
// to the file ids. Every other test in this file goes through `build` and
// is the other half of the proof: if the two ever disagreed, they would
// all be wrong together.
let files = [
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
("a.sv", "module a; endmodule\n"),
("a.sv", "module never_seen; endmodule\n"),
("m.sv", "module m; a u (); endmodule\n"),
];
let handed: Vec<(PathBuf, &str)> = files.iter().map(|(p, s)| (PathBuf::from(*p), *s)).collect();
// The work list, in the order the index is built in: sorted by path, the
// repeated `a.sv` folded into one — and knowable before any parsing, which
// is what makes a "37 of 200" progress report honest.
let ordered = vlog_semantic::index_order(handed.clone());
let names: Vec<&str> = ordered.iter().filter_map(|(p, _)| p.to_str()).collect();
assert_eq!(names, ["a.sv", "m.sv", "z.sv"], "sorted, and one entry per path");
let mut builder = vlog_semantic::IndexBuilder::new();
for (path, src) in ordered {
builder.add_file(path, src);
}
let built = builder.finish();
let whole = WorkspaceIndex::build(handed);
assert_eq!(built.files(), whole.files(), "same files, same file ids");
assert_eq!(built.counts(), whole.counts());
assert_eq!(built.units("a")[0], whole.units("a")[0], "the first copy of a.sv won, both ways");
assert!(built.units("never_seen").is_empty(), "and the second copy is gone");
assert_eq!(built.member("z", "K").len(), 1);
}
/// Everything an index holds, as text — [`WorkspaceIndex::fingerprint`].
///
/// Two indexes with the same fingerprint answer every query the same way; an
/// index whose file ids, whose duplicate-name order or whose edges moved has a
/// different one. It lives in the crate rather than here because
/// `lucisv_server` proves the same equivalence against the real corpus, and one
/// witness that both crates use cannot drift.
fn fingerprint(index: &WorkspaceIndex) -> String {
index.fingerprint()
}
/// One index built by adding `files` to an `IndexBuilder` in exactly the order
/// given — no `index_order` in sight, which is the whole point.
fn built_in_order(files: &[(&str, &str)]) -> WorkspaceIndex {
let mut builder = vlog_semantic::IndexBuilder::new();
for (path, src) in files {
builder.add_file(PathBuf::from(*path), src);
}
builder.finish()
}
#[test]
fn no_insertion_order_can_change_what_the_builder_produces() {
// The attack QA landed on the previous round (indexing-ux QA log,
// 2026-08-27, MEDIUM): `IndexBuilder` handed out `FileId`s in *call* order,
// so a caller that skipped `index_order` got a different index — different
// ids, and a different winner for a name two files declare. Both callers in
// the tree happened to be correct, which is exactly what makes it a footgun
// rather than a bug. It is closed by construction now: `finish` sorts, so
// this test is the permanent re-attack.
let files = [
("z_late.sv", "module dup (input a); endmodule\n"),
("a_early.sv", "module dup (input b); endmodule\n"),
("pkg/m_mid.sv", "package p;\n localparam K = 1;\n typedef int t;\nendpackage\n"),
("defs.svh", "`define W 8\n`define D 4\n"),
("cls.sv", "package q;\n class c;\n int x;\n endclass\nendpackage\n"),
];
let sorted = built_in_order(&files);
// Reversed, rotated, and the exact pair QA proved flipped the ids.
let mut reversed = files;
reversed.reverse();
let mut rotated = files;
rotated.rotate_left(3);
for (label, order) in [("reversed", reversed), ("rotated", rotated)] {
assert_eq!(
fingerprint(&built_in_order(&order)),
fingerprint(&sorted),
"{label}: the insertion order must not reach the result"
);
}
// And the same index `build` produces, since that is what every other test
// in this file exercises.
assert_eq!(fingerprint(&index(&files)), fingerprint(&sorted), "and `build` agrees");
// Named explicitly, because a fingerprint match is only as good as what it
// covers: the ids and the duplicate-name winner are the two things that
// moved before.
let winner = |ws: &WorkspaceIndex| ws.path(ws.units("dup")[0].file).map(Path::to_path_buf);
assert_eq!(winner(&sorted), Some(PathBuf::from("a_early.sv")), "sorted, not first-added");
assert_eq!(sorted.files()[0], PathBuf::from("a_early.sv"), "and FileId(0) with it");
}
#[test]
fn a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at() {
// `index_order`'s other half — one entry per path, the first copy wins —
// has to survive being applied inside `finish` instead of before the loop,
// including when the duplicate is *not* adjacent to the copy that wins.
let files = [
("a.sv", "module a; endmodule\n"),
("z.sv", "module z; endmodule\n"),
("a.sv", "module never_seen; endmodule\n"),
];
let ws = built_in_order(&files);
assert_eq!(ws.files(), [PathBuf::from("a.sv"), PathBuf::from("z.sv")], "two files, not three");
assert_eq!(ws.units("a").len(), 1, "the first copy won");
assert!(ws.units("never_seen").is_empty(), "the second is gone, not appended");
assert_eq!(fingerprint(&ws), fingerprint(&index(&files)), "exactly what `build` gives");
}
// ----------------------------------------------------------------------
// Queries
// ----------------------------------------------------------------------
@@ -641,6 +759,62 @@ fn an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit() {
assert_eq!(defs[0].kind, SymbolKind::Typedef, "the package's typedef, not the decoy module");
}
// ----------------------------------------------------------------------
// Indexed reference postings
// ----------------------------------------------------------------------
#[test]
fn reference_postings_point_from_a_declaration_to_every_cross_file_use() {
let sources = [
("a.sv", "module top; sub u0 (); sub u1 (); endmodule\n"),
("b.sv", "module other; sub u2 (); endmodule\n"),
("sub.sv", "module sub; endmodule\n"),
];
let ws = index(&sources);
let [definition] = ws.units("sub") else { panic!("one sub declaration") };
let sites: Vec<(&Path, &str)> = ws
.references_to(definition)
.iter()
.map(|site| {
let path = ws.path(site.file).expect("site file");
let source = sources.iter().find(|(held, _)| Path::new(held) == path).unwrap().1;
(path, &source[site.name_span.as_range()])
})
.collect();
assert_eq!(
sites,
vec![(Path::new("a.sv"), "sub"), (Path::new("a.sv"), "sub"), (Path::new("b.sv"), "sub")]
);
assert!(!ws.references_are_ambiguous(definition));
}
#[test]
fn replacing_one_file_rebuilds_reference_postings_without_reparsing_the_others() {
let declaration = "module sub; endmodule\n";
let old_top = "module top; sub u0 (); sub u1 (); endmodule\n";
let new_top = "module top; sub u0 (); endmodule\n";
let mut incremental = index(&[("sub.sv", declaration), ("top.sv", old_top)]);
incremental.update_file(PathBuf::from("top.sv"), new_top);
let rebuilt = index(&[("sub.sv", declaration), ("top.sv", new_top)]);
assert_eq!(incremental.fingerprint(), rebuilt.fingerprint());
let [definition] = incremental.units("sub") else { panic!("one sub declaration") };
assert_eq!(incremental.references_to(definition).len(), 1);
}
#[test]
fn an_ambiguous_external_use_marks_every_possible_declaration() {
let ws = index(&[
("a.sv", "module dup; endmodule\n"),
("b.sv", "module dup; endmodule\n"),
("top.sv", "module top; dup u (); endmodule\n"),
]);
assert_eq!(ws.units("dup").len(), 2);
assert!(ws.units("dup").iter().all(|def| ws.references_are_ambiguous(def)));
}
// ----------------------------------------------------------------------
// Corpus acceptance
// ----------------------------------------------------------------------
@@ -853,3 +1027,634 @@ fn collect(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
}
}
}
// ----------------------------------------------------------------------
// incremental updates (incremental-index, 2026-08-27)
// ----------------------------------------------------------------------
/// The one invariant everything else in this section is an attack on: an index
/// arrived at by updating one file is the index a whole build over the same
/// files would have produced — ids, disambiguation order, member tables, edges
/// and defines alike.
///
/// Asserted by building both and comparing fingerprints, and returning the
/// incremental one so a caller can go on asking it questions.
fn updated(whole: &[(&str, &str)], changed: &str, text: &str) -> WorkspaceIndex {
let without: Vec<(&str, &str)> = whole.iter().copied().filter(|(p, _)| *p != changed).collect();
let mut incremental = index(&without);
incremental.update_file(PathBuf::from(changed), text);
let mut expected: Vec<(&str, &str)> = without;
expected.push((changed, text));
assert_eq!(
incremental.fingerprint(),
index(&expected).fingerprint(),
"updating `{changed}` must give the index a whole build would have"
);
incremental
}
#[test]
fn adding_a_file_gives_the_index_a_whole_build_would_have() {
// The hardest direction: the new file sorts *first*, so every file id after
// it moves and every table that named one has to move with it.
let held = [
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
];
let ws = updated(&held, "a.sv", "module sub;\nendmodule\nclass leaf extends base;\nendclass\n");
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the new file took FileId(0)");
assert_eq!(ws.units("z")[0].file, FileId(2), "and z.sv moved from 1 to 2");
assert_eq!(ws.instantiations_of("sub")[0].file, FileId(1), "m.sv's edge moved with it");
assert_eq!(ws.subclasses_of("base").len(), 1);
}
#[test]
fn replacing_a_file_touches_only_what_that_file_said() {
let held = [
("a.sv", "module a;\n sub u1 ();\nendmodule\n"),
("b.sv", "module b;\n sub u2 ();\nendmodule\n"),
("sub.sv", "module sub;\nendmodule\n"),
];
// `a.sv` stops instantiating `sub` and declares a package instead.
let ws = updated(&held, "a.sv", "package a;\n localparam K = 1;\nendpackage\n");
assert_eq!(ws.instantiations_of("sub").len(), 1, "only b.sv's site is left");
assert_eq!(ws.instantiations_of("sub")[0].owner.name, "b");
assert_eq!(ws.member("a", "K").len(), 1, "and the new package's member is there");
assert_eq!(ws.units("a")[0].kind, SymbolKind::Package, "the module is gone, not shadowed");
assert_eq!(ws.files().len(), 3, "no file came or went");
}
#[test]
fn removing_a_file_gives_the_index_a_whole_build_would_have() {
let held =
[("a.sv", "module dup;\n sub u1 ();\nendmodule\n"), ("z.sv", "module dup;\nendmodule\n")];
let mut ws = index(&held);
assert_eq!(ws.units("dup").len(), 2, "premise: the name is declared twice");
assert!(ws.remove_file(Path::new("a.sv")), "the file was there");
assert_eq!(
ws.fingerprint(),
index(&held[1..]).fingerprint(),
"what is left is the index of what is left"
);
assert_eq!(ws.units("dup").len(), 1, "and the removed declaration is gone");
assert_eq!(ws.units("dup")[0].file, FileId(0), "z.sv renumbered down to 0");
assert!(ws.instantiations_of("sub").is_empty(), "its edges went with it");
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
}
#[test]
fn removing_a_file_moves_the_disambiguation_winner() {
// The sharpest thing a removal can do to a *derived* answer: the file that
// won a duplicate name is the file that goes.
let held = [
("a_early.sv", "module dup (input a);\nendmodule\n"),
("z_late.sv", "module dup (input b);\nendmodule\n"),
];
let mut ws = index(&held);
assert_eq!(ws.path(ws.units("dup")[0].file), Some(Path::new("a_early.sv")), "premise");
assert!(ws.remove_file(Path::new("a_early.sv")));
assert_eq!(
ws.path(ws.units("dup")[0].file),
Some(Path::new("z_late.sv")),
"the loser became the winner, and the member table with it"
);
assert_eq!(ws.member("dup", "b").len(), 1);
assert!(ws.member("dup", "a").is_empty());
assert_eq!(ws.fingerprint(), index(&held[1..]).fingerprint());
}
#[test]
fn a_file_that_redefines_a_name_another_file_declares_lands_in_path_order() {
// The update inserts into a table that already holds the *other* file's
// declaration, so this is where an insert-at-the-end bug would show.
let held =
[("a_early.sv", "module dup;\nendmodule\n"), ("z_late.sv", "package other;\nendpackage\n")];
let ws = updated(&held, "z_late.sv", "module dup;\nendmodule\n");
let files: Vec<Option<&Path>> = ws.units("dup").iter().map(|d| ws.path(d.file)).collect();
assert_eq!(
files,
[Some(Path::new("a_early.sv")), Some(Path::new("z_late.sv"))],
"path order, not update order"
);
// And the other way round: the *early* file gains the duplicate.
let ws = updated(
&[held[0], ("z_late.sv", "module dup;\nendmodule\n")],
"a_early.sv",
"module dup;\nendmodule\n",
);
let files: Vec<Option<&Path>> = ws.units("dup").iter().map(|d| ws.path(d.file)).collect();
assert_eq!(files, [Some(Path::new("a_early.sv")), Some(Path::new("z_late.sv"))]);
}
#[test]
fn a_rename_is_a_remove_and_an_add_and_lands_where_a_build_would_put_it() {
let held = [
("mid.sv", "module m;\n sub u1 ();\nendmodule\n"),
("sub.sv", "module sub;\nendmodule\n"),
];
let mut ws = index(&held);
assert!(ws.remove_file(Path::new("mid.sv")));
ws.update_file(PathBuf::from("aaa.sv"), "module m;\n sub u1 ();\nendmodule\n");
let renamed = [("aaa.sv", "module m;\n sub u1 ();\nendmodule\n"), held[1]];
assert_eq!(ws.fingerprint(), index(&renamed).fingerprint(), "a rename is the two of them");
assert_eq!(ws.instantiations_of("sub")[0].file, FileId(0), "and the edge followed the file");
}
#[test]
fn an_update_survives_every_degenerate_file_there_is() {
let held = [("a.sv", "module a;\nendmodule\n"), ("b.sv", "module b;\nendmodule\n")];
for (label, text) in [
("empty", ""),
("whitespace", "\n\n \n"),
("not verilog", "@@@ !!! not verilog at all\n"),
("does not lex", "module a;\n string s = \"unterminated\n"),
("comment only", "// nothing here\n"),
] {
let ws = updated(&held, "a.sv", text);
assert_eq!(ws.files().len(), 2, "{label}: the file is still a file");
assert_eq!(ws.units("b").len(), 1, "{label}: and the other file is untouched");
}
// An empty index is not a special case either.
let mut empty = WorkspaceIndex::default();
assert!(!empty.remove_file(Path::new("nothing.sv")));
empty.update_file(PathBuf::from("only.sv"), "module only;\nendmodule\n");
assert_eq!(
empty.fingerprint(),
index(&[("only.sv", "module only;\nendmodule\n")]).fingerprint()
);
}
#[test]
fn a_full_build_and_a_build_minus_one_plus_that_one_are_the_same_index() {
// The round's headline invariant, over a fixture with something of every
// kind in it and with **every** file taken out and put back in turn.
let files = [
("a_early.sv", "module dup (input a);\n sub u1 (), u2 ();\nendmodule\n"),
("cls.sv", "class leaf extends mid;\nendclass\nclass mid extends base;\nendclass\n"),
("defs.svh", "`define W 8\n`define D 4\n"),
(
"pkg.sv",
"package p;\n localparam K = 1;\n class base;\n int x;\n endclass\nendpackage\n",
),
("sub.sv", "module sub;\nendmodule\n"),
("z_late.sv", "module dup (input b);\n sub u3 ();\nendmodule\n"),
];
let whole = index(&files);
for (path, text) in files {
let rebuilt = updated(&files, path, text);
assert_eq!(
rebuilt.fingerprint(),
whole.fingerprint(),
"taking `{path}` out and putting it back must change nothing at all"
);
}
}
// ----------------------------------------------------------------------
// the edge tables (incremental-index, 2026-08-27)
// ----------------------------------------------------------------------
#[test]
fn the_instantiation_table_records_the_census_the_hierarchy_counts() {
// Every policy `lens.rs`'s QA tests pin, stated once here at the source of
// the numbers: one edge per written statement however many instances it
// declares, a `generate for` body counted once, both arms of an `` `ifdef``
// counted, a module that instantiates itself counted, a `bind`'s
// instantiation an ordinary edge, a gate primitive not an edge at all, and
// an instantiation at file scope not an edge because nothing calls it.
let files = [
(
"top.sv",
"\
module top;
sub u1 (), u2 ();
generate
for (genvar i = 0; i < 4; i++) begin : g
sub u3 ();
end
endgenerate
`ifdef FOO
sub u4 ();
`else
sub u5 ();
`endif
top u6 ();
and u7 (q, a, b);
bind top sub u8 ();
endmodule
",
),
("loose.sv", "sub u_loose ();\n"),
];
let ws = index(&files);
let sites = ws.instantiations_of("sub");
assert_eq!(
sites.len(),
5,
"one multi-instance statement, one generate body, both ifdef arms, one bind: {sites:#?}"
);
assert!(sites.iter().all(|edge| edge.owner.name == "top"), "all inside `top`: {sites:#?}");
assert!(sites.iter().all(|edge| edge.file == FileId(1)), "and all in top.sv");
assert_eq!(ws.instantiations_of("top").len(), 1, "a module instantiates itself");
assert!(ws.instantiations_of("and").is_empty(), "a gate primitive names no module");
assert!(
!sites.iter().any(|edge| edge.owner.name == "loose"),
"an instantiation at file scope has no caller and is not an edge"
);
// The spans are the ones a hierarchy item is built from: the site names the
// module, the owner's name span names the caller.
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!(sites[0].owner.span.start <= sites[0].owner.name_span.start);
assert!(sites[0].owner.name_span.end <= sites[0].owner.span.end);
}
#[test]
fn the_inheritance_table_records_every_class_that_names_a_base() {
let files = [
("a.sv", "class leaf extends mid;\nendclass\n"),
("b.sv", "package p;\n class mid extends base;\n endclass\n class loner;\n endclass\nendpackage\n"),
("c.sv", "module m;\n class inner extends mid #(8);\n endclass\nendmodule\n"),
];
let ws = index(&files);
let mids: Vec<&str> =
ws.subclasses_of("mid").iter().map(|e| e.subclass.name.as_str()).collect();
assert_eq!(mids, ["leaf", "inner"], "file order; a parameterized base is the bare name");
assert_eq!(ws.subclasses_of("base").len(), 1, "a class inside a package is an edge too");
assert!(ws.subclasses_of("loner").is_empty(), "and a class nothing extends has none");
assert_eq!(ws.counts().inheritances, 3);
assert_eq!(ws.counts().instantiations, 0);
}
#[test]
fn the_edge_tables_are_empty_for_a_workspace_with_no_edges() {
let ws = index(&[("a.sv", "module a;\nendmodule\n")]);
assert!(ws.instantiations_of("a").is_empty());
assert!(ws.subclasses_of("a").is_empty());
assert_eq!(ws.instantiations().count(), 0);
assert_eq!(ws.subclasses().count(), 0);
assert_eq!(WorkspaceIndex::default().instantiations_of("anything").len(), 0);
}
// ----------------------------------------------------------------------
// QA (incremental-index, 2026-08-27): adversarial sequences the dev's own
// tests do not reach — each checked against a fresh build, not just asserted
// on its own terms.
// ----------------------------------------------------------------------
#[test]
fn a_long_interleaved_sequence_matches_a_fresh_build_at_every_step() {
// update A, update B, remove A, re-add A, update B again — the exact
// sequence the round's equivalence claim has to survive, checked after
// *every* step rather than only at the end (a bug that only shows up two
// steps later, e.g. a stale `Affected` set, would pass an end-only check).
let a1 = "module a;\n sub u1 ();\nendmodule\n";
let b1 = "package b;\n localparam K = 1;\nendpackage\n";
let mut incremental = index(&[("a.sv", a1), ("b.sv", b1)]);
let a2 = "module a;\n sub u1 (), u2 ();\nendmodule\nclass leaf extends base;\nendclass\n";
incremental.update_file(PathBuf::from("a.sv"), a2);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a2), ("b.sv", b1)]).fingerprint(),
"step 1: update a"
);
let b2 = "package b;\n localparam K = 2;\n class base;\n endclass\nendpackage\n";
incremental.update_file(PathBuf::from("b.sv"), b2);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a2), ("b.sv", b2)]).fingerprint(),
"step 2: update b"
);
assert!(incremental.remove_file(Path::new("a.sv")), "step 3: remove a");
assert_eq!(
incremental.fingerprint(),
index(&[("b.sv", b2)]).fingerprint(),
"step 3: what a full build over what is left would have"
);
let a3 = "module a;\n sub u3 ();\nendmodule\n";
incremental.update_file(PathBuf::from("a.sv"), a3);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a3), ("b.sv", b2)]).fingerprint(),
"step 4: re-add a"
);
let b3 = "package b;\n localparam K = 3;\nendpackage\n";
incremental.update_file(PathBuf::from("b.sv"), b3);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a3), ("b.sv", b3)]).fingerprint(),
"step 5: update b again"
);
}
#[test]
fn a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it() {
// The ghost hunt: `Affected` for an update is the old record's names
// *and* the new record's names (checked by reading `WorkspaceIndex::
// update_file`'s `Ok(at)` arm), so a name that only the changed file used
// to declare must come back with nothing at all — not a stale one-entry
// `Vec` from before the update, and not silently dropped from the merge's
// `.remove()` and never refilled either.
let held = [("a.sv", "module solo;\nendmodule\n"), ("b.sv", "package other;\nendpackage\n")];
let mut ws = index(&held);
assert_eq!(ws.units("solo").len(), 1, "premise: only a.sv declares it");
ws.update_file(PathBuf::from("a.sv"), "package a;\nendpackage\n");
assert!(ws.units("solo").is_empty(), "the ghost must not survive");
assert_eq!(
ws.fingerprint(),
index(&[("a.sv", "package a;\nendpackage\n"), held[1]]).fingerprint()
);
}
#[test]
fn adding_a_new_file_that_duplicates_an_existing_name_lands_by_path_order_either_direction() {
// `a_file_that_redefines_a_name_another_file_declares_lands_in_path_order`
// covers this for a file the index already holds (the restricted-merge
// `Ok(at)` arm); this is the same attack against the `Err(at)` arm, where
// every id renumbers rather than one record being replaced in place.
let held = [("z_late.sv", "module dup;\nendmodule\n")];
let mut ws = index(&held);
ws.update_file(PathBuf::from("a_early.sv"), "module dup;\nendmodule\n");
let files: Vec<&Path> = ws.units("dup").iter().map(|d| ws.path(d.file).unwrap()).collect();
assert_eq!(
files,
[Path::new("a_early.sv"), Path::new("z_late.sv")],
"the new, earlier-sorting file wins the disambiguation"
);
assert_eq!(
ws.fingerprint(),
index(&[("a_early.sv", "module dup;\nendmodule\n"), held[0]]).fingerprint()
);
let held = [("a_early.sv", "module dup;\nendmodule\n")];
let mut ws = index(&held);
ws.update_file(PathBuf::from("z_late.sv"), "module dup;\nendmodule\n");
let files: Vec<&Path> = ws.units("dup").iter().map(|d| ws.path(d.file).unwrap()).collect();
assert_eq!(
files,
[Path::new("a_early.sv"), Path::new("z_late.sv")],
"and the other way round, the existing file keeps the disambiguation win"
);
assert_eq!(
ws.fingerprint(),
index(&[held[0], ("z_late.sv", "module dup;\nendmodule\n")]).fingerprint()
);
}
#[test]
fn find_define_answers_in_current_file_id_order_after_cross_file_updates() {
// Defines are per-file (`WorkspaceIndex::defines`) and are not part of
// `Affected` at all — `find_define` just walks `self.facts` in current id
// order. The attack is renumbering: adding a file that sorts *before*
// both existing ones must move every entry's `FileId` and keep the answer
// in the new file order, `` `undef``s excluded either way.
let held = [("a.sv", "`define W 8\n"), ("b.sv", "`define W 16\n`undef W\n`define W 32\n")];
let mut ws = index(&held);
let bodies = |ws: &WorkspaceIndex| -> Vec<(u32, String)> {
ws.find_define("W").iter().map(|(f, d)| (f.0, d.body.clone())).collect()
};
assert_eq!(
bodies(&ws),
[(0, "8".to_string()), (1, "16".to_string()), (1, "32".to_string())],
"premise: file order, every definition (not just the latest), undef excluded"
);
ws.update_file(PathBuf::from("a.sv"), "`define W 9\n");
assert_eq!(
bodies(&ws),
[(0, "9".to_string()), (1, "16".to_string()), (1, "32".to_string())],
"the update landed and the order held"
);
ws.update_file(PathBuf::from("0_early.sv"), "`define W 1\n");
assert_eq!(ws.path(FileId(0)), Some(Path::new("0_early.sv")), "premise: it renumbered");
assert_eq!(
bodies(&ws),
[(0, "1".to_string()), (1, "9".to_string()), (2, "16".to_string()), (2, "32".to_string())],
"find_define's ids moved with the renumbering and the order is still file order"
);
}
#[test]
fn updating_a_file_to_empty_text_differs_from_removing_it() {
// Explicitly not the same operation, and not pinned as such anywhere else:
// an emptied file keeps its `FileId` slot (it is still a file the index
// holds, contributing nothing), while a removed file's slot is gone and
// every later id shifts down. Two different fingerprints, on purpose.
let held = [("a.sv", "module a;\nendmodule\n"), ("z.sv", "module z;\nendmodule\n")];
let mut emptied = index(&held);
emptied.update_file(PathBuf::from("a.sv"), "");
let mut removed = index(&held);
assert!(removed.remove_file(Path::new("a.sv")));
assert_ne!(
emptied.fingerprint(),
removed.fingerprint(),
"an emptied file is still a file; a removed one is not the same index at all"
);
assert_eq!(emptied.files().len(), 2, "the empty file still occupies a slot");
assert_eq!(removed.files().len(), 1, "the removed file's slot is gone");
assert_eq!(emptied.path(FileId(1)), Some(Path::new("z.sv")), "z.sv did not renumber");
assert_eq!(removed.path(FileId(0)), Some(Path::new("z.sv")), "z.sv renumbered down to 0");
}
#[test]
fn same_named_files_in_different_directories_updated_alternately_stay_correct() {
// Two files that share a *filename* but not a path are ordinary distinct
// entries to `WorkspaceIndex` (paths, not filenames, are the sort key and
// the identity `binary_search_by` uses) — attacked here by updating first
// one, then the other, then the first again, checking the full
// equivalence at each step so a bug keying off the filename rather than
// the path would show.
let held = [
("dir_a/defs.sv", "module defs_mod;\n sub u1 ();\nendmodule\n"),
("dir_b/defs.sv", "module defs_mod;\n sub u2 ();\nendmodule\n"),
];
let mut ws = index(&held);
assert_eq!(ws.units("defs_mod").len(), 2, "premise: both declare the same name");
// Two separate statements, not one comma-joined one — the census counts
// one edge per `Instantiation` node, so this really is two sites.
let dir_a_v2 = "module defs_mod;\n sub u3 ();\n sub u4 ();\nendmodule\n";
ws.update_file(PathBuf::from("dir_a/defs.sv"), dir_a_v2);
assert_eq!(ws.instantiations_of("sub").len(), 3, "dir_a now has two sites, dir_b still one");
assert_eq!(
ws.fingerprint(),
index(&[("dir_a/defs.sv", dir_a_v2), held[1]]).fingerprint(),
"after updating dir_a alone"
);
let dir_b_v2 = "package other;\nendpackage\n";
ws.update_file(PathBuf::from("dir_b/defs.sv"), dir_b_v2);
assert_eq!(ws.units("defs_mod").len(), 1, "only dir_a's module is left");
assert_eq!(ws.path(ws.units("defs_mod")[0].file), Some(Path::new("dir_a/defs.sv")));
assert_eq!(ws.instantiations_of("sub").len(), 2, "dir_b's site went with it");
assert_eq!(
ws.fingerprint(),
index(&[("dir_a/defs.sv", dir_a_v2), ("dir_b/defs.sv", dir_b_v2)]).fingerprint(),
"after updating dir_b too"
);
let dir_a_v3 = "module defs_mod;\nendmodule\n";
ws.update_file(PathBuf::from("dir_a/defs.sv"), dir_a_v3);
assert!(ws.instantiations_of("sub").is_empty(), "back to dir_a, and its sites go too");
assert_eq!(
ws.fingerprint(),
index(&[("dir_a/defs.sv", dir_a_v3), ("dir_b/defs.sv", dir_b_v2)]).fingerprint(),
"alternating back to the first file"
);
}
// ----------------------------------------------------------------------
// FileFacts as a record: the persistent index cache's format
// ----------------------------------------------------------------------
/// A fixture that exercises every field of a record at once: file-scope
/// units of three kinds, members (including a class nested in a package,
/// which is registered twice), instantiation edges, an inheritance edge,
/// and a `` `define`` table with both an object-like and a function-like
/// macro, an `` `undef``, and a body carrying the characters the format has
/// to escape.
const EVERY_FIELD: &str = concat!(
"`define PLAIN 8\n",
"`define ARGS(a, b = 8) {a, b}\t// a tab and a \\ backslash\n",
"`undef PLAIN\n",
"package p;\n",
" typedef logic [7:0] byte_t;\n",
" class base; endclass\n",
" class derived extends base;\n",
" function void f(); endfunction\n",
" endclass\n",
"endpackage\n",
"typedef int top_t;\n",
"module top;\n",
" sub u_sub ();\n",
" other u_other ();\n",
"endmodule\n",
);
#[test]
fn a_records_every_field_survives_the_round_trip() {
let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD);
let line = facts.encode().expect("an ordinary path encodes");
assert!(!line.contains('\n'), "a record is one line: {line}");
let back = FileFacts::decode(&line).expect("what was written reads back");
// `FileFacts` compares every field it holds — path, defines (kind, name,
// params, body, both spans), units, members, instantiation edges,
// 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");
}
#[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
// give the same index as the files themselves. Checked over a workspace
// with duplicate names and cross-file edges, by fingerprint — ids,
// disambiguation order, member tables, both edge tables, define counts.
let sources = [
("/w/a.sv", EVERY_FIELD),
("/w/b.sv", "module sub; endmodule\nmodule dup; endmodule\n"),
("/w/c.sv", "`define X 1\nmodule dup;\n sub u ();\nendmodule\n"),
("/w/d.sv", "class late extends base; endclass\n"),
];
let fresh = index(&sources);
let mut builder = vlog_semantic::IndexBuilder::new();
for (path, src) in sources {
let line = FileFacts::of(PathBuf::from(path), src).encode().expect("encodes");
builder.add_facts(FileFacts::decode(&line).expect("decodes"));
}
let restored = builder.finish();
assert_eq!(restored.fingerprint(), fresh.fingerprint());
assert_eq!(restored.counts(), fresh.counts());
}
#[test]
fn a_record_that_is_not_exactly_a_record_decodes_to_nothing() {
let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD);
let line = facts.encode().expect("encodes");
let fields: Vec<&str> = line.split('\t').collect();
// Truncation at *every* length, not just at one: a torn write can stop
// anywhere, and every stopping point must be a dropped record rather
// than a plausible one.
for cut in 0..fields.len() {
let truncated = fields[..cut].join("\t");
assert_eq!(
FileFacts::decode(&truncated),
None,
"a record cut to {cut} of {} fields is not a record",
fields.len()
);
}
// And anything left over on the end is not a record either.
assert_eq!(FileFacts::decode(&format!("{line}\textra")), None, "trailing field");
for garbage in [
"",
"garbage",
"\0\0\0",
"/w/a.sv\tD0\tU0\tM0\tI0", // a list marker missing
"/w/a.sv\tD0\tU1\tm\tmodule\t0\t1\tM0\tI0\tS0", // a count that outruns the line
"/w/a.sv\tD0\tU1\tm\tnosuchkind\t0\t1\tM0\tI0\tS0", // a kind no version writes
"/w/a.sv\tD0\tU1\tm\tmodule\tzero\t1\tM0\tI0\tS0", // a number that is not one
"/w/a.sv\tX0\tU0\tM0\tI0\tS0", // the wrong marker
"/w/a\\qb.sv\tD0\tU0\tM0\tI0\tS0", // an escape this format never writes
"/w/a.sv\tD1\td\tM\t-\tbody\t0\t1\t2\tM0\tI0\tS0", // a define's fields cut short
] {
assert_eq!(FileFacts::decode(garbage), None, "{garbage:?} is not a record");
}
}
#[test]
fn a_path_with_a_separator_in_it_is_escaped_like_any_other_string() {
// The path is a string field like the rest, so a tab or a newline in it
// is escaped rather than fatal — the same treatment a macro body gets,
// and it needs it (`EVERY_FIELD` has both).
for path in ["/w/a\tb.sv", "/w/a\nb.sv", "/w/a\\b.sv"] {
let facts = FileFacts::of(PathBuf::from(path), "module m; endmodule\n");
let line = facts.encode().expect("encodes");
assert!(!line.contains('\n'), "still one line: {line}");
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{path:?}");
}
}
#[cfg(unix)]
#[test]
fn a_path_that_is_not_utf_8_is_simply_never_cached() {
// The one path shape that has no record: it cannot be written as text at
// all. `None` rather than a lossy spelling — a record whose path is not
// the file's path would be a record that answers for the wrong file.
// Same answer `lucisv_core::cache` gives the same shape of path.
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let path = PathBuf::from(OsStr::from_bytes(b"/w/\xff\xfe.sv"));
assert_eq!(FileFacts::of(path, "module m; endmodule\n").encode(), None);
}
#[test]
fn a_degenerate_file_still_makes_a_record() {
// The shapes `an_update_survives_every_degenerate_file_there_is` covers,
// through the record format: an empty file, one that does not lex, one
// that is not Verilog at all. Each has a record, and each round-trips.
for src in [
"",
" \n\t\n",
"this is not verilog\n",
"module m;\n \"unterminated\n",
"// just a comment\n",
] {
let facts = FileFacts::of(PathBuf::from("/w/x.sv"), src);
let line = facts.encode().expect("encodes");
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}");
}
}
+31 -7
View File
@@ -68,22 +68,46 @@ computed by, so the lens and the hierarchy view can never disagree (TODO.md
invalidate. Not on a keystroke either — a `didChange` cannot change any
count, since the census is over instantiations in *other* files and a client
re-requests lenses for the buffer it just edited anyway.
- **The count is computed against `Workspace::sources()`**, which reads every
- ~~**The count is computed against `Workspace::sources()`**, which reads every
in-scope file from disk with open buffers overriding it. So an unsaved
instantiation typed into another open buffer *is* counted, and a file
changed on disk that no watcher reported is counted as of this request.
- **The cost is one workspace walk per request, not one per module.**
changed on disk that no watcher reported is counted as of this request.~~
**Superseded (incremental-index, 2026-08-27)** — see the assumption above.
- ~~**The cost is one workspace walk per request, not one per module.**
`hierarchy::callers_of_each` takes a batch precisely because `sources()`
re-reads the whole file set: measured over the 860-file corpus, a
three-module file costs 133 ms against 93 ms for a single name (debug build)
— amortized, not tripled. The absolute number is the honest cost of having
no instantiation-edge table in the index; see Status / TODO.
no instantiation-edge table in the index; see Status / TODO.~~
**Superseded (incremental-index, 2026-08-27): the cost is a lookup.** The
count comes from the index's instantiation-edge table, and the only I/O left
is reading the handful of files that really do instantiate one of the names,
to turn recorded byte spans into ranges — 0.26 ms for the same three-module
file over the same corpus. The batch stays the primitive for the same
reason at a smaller scale: one file instantiating three of the names is read
once.
- **The count is as of the index, which is as of its last build or update**
(incremental-index, 2026-08-27) — superseding the assumption below that the
count is computed against `Workspace::sources()` per request. A save, or any
other rescan trigger, folds every open buffer in and makes an edit count; a
keystroke alone no longer does. The trade and the alternatives considered are
in `docs/features/incremental-index/README.md`.
## Handshakes
### Request to `vlog_semantic` — an instantiation-edge table in the index
Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
**Delivered (incremental-index, 2026-08-27).** `WorkspaceIndex::instantiations_of`
exists with the shape proposed below — plus the owning declaration's name and
full extent, which is what stopped `callers_of_each` re-parsing the file to
find them — and `hierarchy::callers_of_each` is a lookup with its walk-and-parse
body deleted. The census policies carried over by construction: the table is
built by the same `instantiations::sites` walk the handler used to run, which
was lifted into `vlog_semantic` for exactly that reason, and every one of this
feature's QA tests passes unchanged. Measured 92 ms → 0.26 ms for a
three-module file over the corpus. The original request, kept legible:
~~Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
features now pay the same cost: every `textDocument/codeLens` request and
every `callHierarchy/incomingCalls` walks `Workspace::sources()` — a re-read
and tolerant re-parse of every in-scope file — because `WorkspaceIndex`
@@ -100,7 +124,7 @@ pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]
so `hierarchy::callers_of_each` becomes a lookup and its whole
walk-and-parse body is deleted. The census policies (multi-instance
statements = one site, textual not elaborated, both `ifdef` arms) must carry
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.~~
### `lucisv_server::hierarchy` — **changed, deliberately**
@@ -206,7 +230,7 @@ no-showDocument path — verified by running it.
is an instantiation-edge table in `WorkspaceIndex`, built once per
rescan, which would make both this and `incomingCalls` a lookup. That is
a `vlog_semantic` change and belongs in its own round; **request
recorded here, not made.**
recorded here, not made.** — **done, incremental-index, 2026-08-27.**
## Work log
+7
View File
@@ -15,6 +15,13 @@ per notification.
## Assumptions
- **Amended (incremental-index, 2026-08-27): one notification is still one
rescan, but a notification naming exactly one held source file takes the
incremental path** — that file's contribution replaced, no progress bar, no
log lines. A checkout filling the list, and a notification naming the
filelist, are whole rebuilds exactly as before. `watch::one_scope_file` is
the test. See `docs/features/incremental-index/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
+5 -2
View File
@@ -127,8 +127,11 @@ Highest first, resolved on every index rebuild:
| # | Scope | When |
|---|---|---|
| 1 | The files a **filelist** names | `lucisv.filelist` is set (absolute, or relative to the first workspace root), else the workspace root's `lucisv.toml` has a `filelist` key |
| 2 | The **workspace-folder walk** | there is a workspace root — unchanged from before this feature |
| 3 | Each **open file's own directory**, non-recursive | there is no workspace root at all (a single file opened) |
| 2 | The **workspace-folder walk** | ~~there is a workspace root~~ **superseded (index-scope, 2026-08-27): `lucisv.index.scope: "workspace"` asks for it; it is no longer the default** |
| 3 | Each **open file's own directory** | ~~non-recursive; there is no workspace root at all~~ **superseded (index-scope, 2026-08-27): this is now the default rung with a root too, raised `lucisv.index.scopeDepth` levels and walked. The non-recursive read survives unchanged for the rootless session at depth 0. See `docs/features/index-scope/README.md`** |
Rung 1 — this feature — is untouched by that round: a filelist is the project
file, and it still defines the scope exactly, in any session.
Open buffers overlay every rung exactly as they did before: a buffer's text
beats what is on disk, and a buffer whose path the scope does not name is
+9 -1
View File
@@ -51,7 +51,9 @@ parser** a push does, so the two paths cannot drift.
disk in the index by contributing itself (`Workspace::collect_sources` adds
every open document with a path, whatever the scope ladder said). Removing
the *last* folder is not a special case either: the session becomes the
rootless one rung 3 of the scope ladder already describes, where the scope
rootless one rung 3 of the scope ladder already describes (which
index-scope, 2026-08-27, made the default rung for a rooted session as
well), where the scope
is the open buffers' own directories.
- **One set of settings per session, not one per folder.** The pull sends no
`scopeUri`. `ClientSettings` is a single struct read by `format::settings_for`
@@ -72,6 +74,12 @@ parser** a push does, so the two paths cannot drift.
first index is built against the default scope, and a pulled
`lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands.
Nothing is *wrong* in between, it is simply the wider scope.
**2026-08-27:** `lucisv.index.maxFileSize` joins those two — a pulled cap
that differs from the 1 MiB default costs the same one extra rescan — and
`lucisv.index.logFiles` shows the other face of the same fact: the startup
scan narrates itself at the default (on) whatever the user's setting says,
because their answer has not arrived yet. Both are
`docs/features/indexing-ux/README.md`.
## The settings model, stated once
+33 -19
View File
@@ -59,13 +59,19 @@ pair unrolls as far as the user keeps clicking.
`TextRange::contains` excludes the end, which is right for a span of text
and wrong for a caret — that is where a double-click and an end-of-word
motion leave it.
- **The scope ladder decides which files are searched.** `incomingCalls`
reads `Workspace::sources()`, so a file a filelist or an `exclude` keeps out
of the index instantiates nothing, exactly as it references nothing
- **The scope ladder decides which files are searched.** `incomingCalls` reads
the index's instantiation-edge table (incremental-index, 2026-08-27; it read
`Workspace::sources()` before), so a file a filelist or an `exclude` keeps
out of the index instantiates nothing, exactly as it references nothing
(`docs/features/references-nav/README.md`).
- **Open buffers beat disk.** The same `sources()` overlay every other
- ~~**Open buffers beat disk.** The same `sources()` overlay every other
cross-file answer uses, so an instantiation just typed and not yet saved is
already a caller.
already a caller.~~ **Superseded (incremental-index, 2026-08-27): the census
is as of the index.** An index is built and updated from `collect_sources`,
which still overlays every open buffer — so a save, or any other rescan
trigger, makes a just-typed instantiation a caller. A keystroke alone no
longer does. The trade is argued in
`docs/features/incremental-index/README.md`.
- **Nested module declarations.** Legal SystemVerilog; today's parser recovers
them into sibling items rather than nesting them. The walk carries the
innermost enclosing declaration either way, so both spellings attribute
@@ -95,12 +101,13 @@ pair unrolls as far as the user keeps clicking.
- **Consumes `vlog_parser`** — `parse_source_tolerant` for every file that is
not the open buffer, `ast::Module`/`Instantiation` (read-only),
`Item::span`, `LineIndex`. Nothing new is asked of the crate.
- **Consumes `vlog_semantic::WorkspaceIndex`** — `units(name)` and
`path(file)`, to turn a module name into the file that declares it. The
index records what a file *declares* and **not what it instantiates**: there
is no edge table, which is why `incomingCalls` walks files rather than
querying. Adding such a table is a real option and is recorded as backlog
below rather than assumed here.
- **Consumes `vlog_semantic::WorkspaceIndex`** — `units(name)`, `path(file)`
and, since 2026-08-27, `instantiations_of(name)`. The index records what a
file instantiates now as well as what it declares, so `incomingCalls` is a
lookup and the walk-and-parse body it used to have is gone
(`docs/features/incremental-index/README.md`). The walk itself lives in
`vlog_semantic::instantiations` — lifted out of this crate so the index's
census and this module's per-buffer one are the same function.
- **Consumes `crate::state::Workspace`** — `document`, `index`, `text_of`,
`sources`. Nothing in `state.rs` was changed; the workspace stays immutable
through all three handlers, and no cache was added.
@@ -154,7 +161,14 @@ Release build, this machine, the checked-in 860-file corpus:
| `outgoingCalls` for the corpus's densest module (`uart_reg_top.sv`, 63 instantiation sites, 4 distinct resolvable targets) | **2.2 ms** |
| the same `incomingCalls` in a debug build | 106 ms |
Two things the table says. First, `incomingCalls` costs **4× less than M7's
**Superseded (incremental-index, 2026-08-27).** The table above is what the
walk cost; the edge table named below as "the place a future win lives" is
where it went — `incomingCalls` is a lookup, and the only I/O left is reading
the files that really do instantiate the name. The sibling measurement is a
whole file's code lenses over the same corpus, 92 ms → 0.26 ms
(`docs/features/incremental-index/README.md`). The reasoning the table
supported, kept legible:
~~Two things the table says. First, `incomingCalls` costs **4× less than M7's
`textDocument/references`** on the same corpus (218 ms) even though it answers
a superset of the question — it needs the *caller*, not just the span. The
reason is the prefilter: a module that is instantiated somewhere has its name
@@ -163,7 +177,7 @@ before it is parsed, and 834 of 860 files are. Second, what is left is
**almost entirely file I/O** — `sources()` reads every in-scope file whether
it will be parsed or not. That is the shared cost of every cross-file answer
in this server, and the place a future win lives (see backlog); nothing in
this feature can shave it alone.
this feature can shave it alone.~~
`prepare` and `outgoingCalls` never walk the workspace at all: they parse the
buffer and, at most, one file per distinct instantiated module.
@@ -208,12 +222,12 @@ lucisv-server qa_perf_worst_case -- --ignored --nocapture`).
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`,
`cargo test --workspace`, `editors/vscode/smoke.js`
- [x] `docs/features/lucisv-server/README.md` capability table + work log
- [ ] Not done, backlog: an **instantiation edge table in `WorkspaceIndex`**,
built with the index, which would make `incomingCalls` a map lookup and
cost one extra tree walk per file at index time. Worth doing when
something else wants the same edges (a design-tree view, an
unused-module lint); today one request in 56 ms does not justify
widening the index's contract.
- [x] ~~Not done, backlog:~~ **done (incremental-index, 2026-08-27):** an
**instantiation edge table in `WorkspaceIndex`**, built with the index,
which makes `incomingCalls` a map lookup and costs one extra tree walk
per file at index time. What finally wanted the same edges was the code
lens paying the same 56 ms on every request, and a round that had to
touch the index anyway.
- [ ] Not done, deliberately: type hierarchy (`typeHierarchy`) for classes,
interface and program instantiations as their own node kind, and any
whole-tree "show me the design" view — this milestone is exactly the
+682
View File
@@ -0,0 +1,682 @@
# incremental-index
## Goal
Until this round **any** change rebuilt the whole workspace index: a save of
one file re-read, re-tokenized, re-parsed and re-analyzed every file in scope,
rebuilt the completion tables and rebuilt the include graph. On the checked-in
860-file corpus that is 1.5 s of work, in a debug build, on every `didSave`.
This round makes the common case what it should always have been — **when
exactly one in-scope file changed, only that file's contribution is
replaced** — under an invariant strong enough to make the shortcut safe: the
index an update produces is *the index a whole rebuild would have produced*,
byte for byte. The same round lands the two edge tables that were filed as
Handshakes months apart and always wanted the same shape: **who instantiates
module M** and **who extends class C**, recorded as the index is built. With
them, `callHierarchy/incomingCalls`, `textDocument/codeLens` and
`typeHierarchy/subtypes` stop walking the workspace on every request and become
lookups — 92 ms → 0.26 ms for a whole file's code lenses, 82 ms → 0.71 ms for
`subtypes`, measured below.
## Assumptions
- **The equivalence invariant is the round.** For any workspace `W` and any
file `F` in it: `build(W)` and `build(W \ F).update_file(F)` are the *same
index* — same `FileId`s, same disambiguation order, same unit and member
tables, same edge tables, same per-file `` `define`` tables. Not "equivalent
where anything looks", **equal**: `WorkspaceIndex::fingerprint()` renders
every observable and the two fingerprints are compared directly. The same
holds for `remove_file`, and for the two composed into a rename.
- **A `FileId` is a position in the path-sorted file list and nothing else,
which is what it has always been.** The brief allowed interning ids per path
and retiring them, so that an insert or a remove would not renumber. That was
considered and **not** done, and the reason is the invariant above. Interned
ids differ between "a whole build" and "a build minus F, then F added back" —
F would take the next free id rather than its sorted-position one — so the
two histories could only be *equivalent*, never *equal*, and equality would
have to be re-established observable by observable in every consumer that
reads the numeral. Three do: `find_define` returns its hits in `FileId`
order, `candidates.rs` iterates `0..files().len()`, and the crate's own tests
compare `files()`. Renumbering keeps the strongest statement available —
*the same index* — and costs one merge pass over records already in memory,
no file read and no file re-parsed. **Disambiguation was already order-derived
and still is**: a name's declarations are pushed in one loop over the
path-sorted per-file records, so the order is the path order, and the ids
happen to agree with it because they are that same position. Nothing reads a
`FileId` numeral to decide an order.
- **Ids do not survive an add or a remove, and nothing in the tree holds one
across an update.** The only place a `FileId` is stored is a `Def` inside a
buffer's `ExternalResolutions`, and `update_one` refreshes every open
buffer's overlay exactly as `rebuild_index` does. The server is single
threaded and no update can interleave with a request.
- **The index keeps every file's contribution unmerged.** `FileFacts` — the
path, the define table, the file-scope declarations, the members, the
instantiation edges and the inheritance edges — used to live only until
`IndexBuilder::finish` and now lives in the index. (**Since
index-persistence, 2026-08-27** it also lives on *disk*: `FileFacts` is
public, encodable and decodable, and a record put back through
`IndexBuilder::add_facts` gives the index the file's parse would have.) That is what makes the
restricted re-merge possible, and it is the round's honest memory cost: the
same names and spans the merged tables hold, held once more, per file. No
`Semantics` and no source text is retained, exactly as before.
- **The cheap path is "a file the index already holds"**, and everything else
is a whole rebuild. A file *appearing* changes what other files' `` `include``s
resolve to, and answering that needs a walk; a file the index does not hold
is also how a brand-new file gets in at all. So the gate is one membership
test, and it is stated as such rather than guessed at per trigger.
- **A save carries no progress bar any more, and that is the visible protocol
delta.** The bar exists because a whole scan takes perceptible seconds; one
file is one parse. No bar, no per-file log line, and no scope warnings — the
last because warnings come from *resolving* the scope, and the scope was not
re-resolved. Everything else a rebuild does after the scan still happens: the
generation bump, the code-lens refresh, and a republish of every open buffer.
- **The republish stays wholesale.** Every open buffer's diagnostics are
computed against the index, so any of them may have moved; narrowing to "the
buffers that could have changed" needs a cross-file dependency graph this
server does not have. Filed, not guessed at.
- **The census is now as of the index, which is as of its last build or
update.** This is a real behaviour change and it is the one the round argues
hardest for. `hierarchy::callers_of_each` and `type_hierarchy::subtypes` used
to walk `Workspace::sources()` per request, which folds open buffers over
disk — so a keystroke in *another* buffer moved a code-lens count before
anything rebuilt. They read the index's edge tables now, and an index is only
ever as of its last build or update. Both of those fold every open buffer in,
so a save (or any rescan trigger) makes the edit count; a keystroke alone
does not. In exchange the lens, the call hierarchy and every other index-shaped
answer are consistent with each other by construction, and the census costs a
lookup instead of a workspace walk. Pinned from both sides in
`an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it`
and `an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it`.
- **The census *policies* did not move, and could not have**: the tables are
built by the very walks the request handlers used to run. One
`Instantiation` node is one site however many instances it declares; a
`generate for` body is one site, not the elaborated four; both arms of an
`` `ifdef`` are sites; matching is by the name as written; an instantiation at
file scope is not an edge, because nothing calls it; a gate primitive names
no module. Every one of `lens.rs`'s QA tests passes unchanged, and the same
policies are now pinned at the source of the numbers as well
(`the_instantiation_table_records_the_census_the_hierarchy_counts`).
- **An edge's spans are as of the index; the ranges are as of the text now.**
Turning a recorded byte span into a line/character range needs the file's
text, which is read fresh (open buffer beating disk, as always). For a buffer
edited since the last update the two disagree — the same staleness
`item_in_file` has carried since the hierarchy shipped, on the same files,
for the same reason.
- **The include graph's one incremental limit is stated rather than papered
over.** `IncludeGraph::update_file` re-scans the changed file's own edges and
re-learns the known-file and folded-spelling tables from the index's list; it
does **not** re-resolve any *other* file's edges. For the case the server uses
it in — one file's text changed, the file set did not — there is nothing
stale at all. When the update is a removal, another file's `` `include`` of
the removed file keeps its edge until the next whole rebuild. Named here
because it is the only thing in this round that is not exactly a rebuild.
- **The completion word table is exact, and pays for it in memory.**
`Candidates` keeps a per-file word list and a per-word file count, so one
file's words can be given back without re-lexing the other 859. Over the
corpus that is ~40k `String`s of per-file lists (QA measured 39,673 — the
work log's original ~170k estimate was 4.3x high; ~1.38 MB) on top of the
~17k distinct
words — single-digit megabytes, for the difference between "the word table is
correct" and "the word table drifts until something rebuilds".
## Handshakes
### `vlog_semantic` — the index gains an incremental API and two edge tables
```rust
impl WorkspaceIndex {
/// Insert or replace one file. Gives the index a whole build would have.
pub fn update_file(&mut self, path: PathBuf, src: &str);
/// Drop one file, reporting whether it was there.
pub fn remove_file(&mut self, path: &Path) -> bool;
/// Every observable, rendered — the equivalence witness.
pub fn fingerprint(&self) -> String;
pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge];
pub fn subclasses_of(&self, name: &str) -> &[InheritanceEdge];
pub fn instantiations(&self) -> impl Iterator<Item = (&str, &[InstantiationEdge])>;
pub fn subclasses(&self) -> impl Iterator<Item = (&str, &[InheritanceEdge])>;
}
pub struct DeclSite { pub name: String, pub name_span: TextRange, pub span: TextRange }
pub struct InstantiationEdge { pub file: FileId, pub owner: DeclSite, pub site_span: TextRange }
pub struct InheritanceEdge { pub file: FileId, pub subclass: DeclSite }
```
- `InstantiationEdge` carries the owner's whole `DeclSite` rather than just its
name span, because that is what a `CallHierarchyItem` is: `name` is the
item's name, `name_span` its `selectionRange`, `span` its `range`. The
code-lens README's proposed shape asked for "(file, instantiating-module name
span, instance site span)"; the extra two fields are what stopped
`callers_of_each` needing to re-parse the file to find them.
- `IndexCounts` gains `instantiations` and `inheritances`. Additive; every
field is still public and every existing read still compiles.
- **Two modules were lifted into this crate**, because the index now records
what they find and a second copy of either walk would be free to drift from
the one the request handlers use:
- `vlog_semantic::instantiations` — moved verbatim from
`lucisv_server::instantiations`. `hierarchy.rs`, `lens.rs` and `inlay.rs`
import it from here now; its own tests moved with it.
- `vlog_semantic::classes` — the class-declaration walk that was private to
`lucisv_server::type_hierarchy`, plus `extends_name`. `type_hierarchy.rs`
uses it and no longer has a copy.
- `IndexBuilder` is unchanged in shape and still sorts in `finish`; `finish` is
now `merge(None)` over the sorted records, which is the same loop
`update_file` runs restricted to the affected keys. **That is the equivalence
proof**: there is exactly one place any table's order is decided.
### `lucisv_server::state`
- `Workspace::update_one(&mut self, path: &Path) -> bool` — the incremental
rescan for one file. `false` means "not a file this index holds; rebuild".
It patches all four pieces of state a rebuild produces (index, completion
tables, include graph, every open buffer's overlay) and is documented
piece by piece at the function.
**Amended (index-persistence, 2026-08-27):** it also writes the file's new
record through to the on-disk index cache, using
`WorkspaceIndex::facts_for` to take back the record the update just made
rather than parsing anything twice. An hour of saves is an hour of work the
next session does not repeat.
- `Workspace::update_one_checked` is the `#[cfg(test)]` paranoid form: it runs
the update, then rebuilds the whole workspace and asserts the two agree on
the index's fingerprint *and* on the completion word table.
### `lucisv_server::candidates` / `includes`
- `Candidates::update_file(index, path, text)` / `remove_file(index, path)` and
`IncludeGraph::update_file(path, text, known)` / `remove_file(path, known)`.
Both are the incremental forms of their `build`, and both are exact for the
case `update_one` uses them in.
### `lucisv_server::watch`
- `watch::one_scope_file(changes, filelist) -> Option<PathBuf>` — the one file a
watcher notification named, when it named exactly one and that one is not the
filelist. The gate on the fast path for the watcher trigger.
### `lucisv_server::server`
- `reindex_one(&mut self, path) -> bool`, taken by `didSave` and by a
one-file `didChangeWatchedFiles`, falling through to `reindex()` when it
declines.
## The fast-path trigger table
| trigger | path | bar |
|---|---|---|
| `didSave` naming one file the index holds | incremental | none |
| `didSave` naming a file the index does not hold (a new file) | whole rebuild | yes |
| `didChangeWatchedFiles` naming one held source file | incremental | none |
| `didChangeWatchedFiles` naming two or more files (a checkout) | whole rebuild | yes |
| `didChangeWatchedFiles` naming the filelist | whole rebuild | yes |
| `didChangeConfiguration` moving `exclude`/`filelist`/`maxFileSize`/`index.scope`/`index.scopeDepth` | whole rebuild | yes |
| `didOpen` that widened the scope | whole rebuild | yes |
| `didChangeWorkspaceFolders` that moved the root set | whole rebuild | yes |
| `didRenameFiles` / `didDeleteFiles` | whole rebuild | yes |
Pinned by `the_fast_path_is_taken_for_one_held_file_and_for_nothing_else`
(rows 1–5 and the settings row) and by the tests the earlier rounds left on
the remaining rows.
## Derived state, and how each piece is patched
| state | what it reads | on an incremental update |
|---|---|---|
| `WorkspaceIndex.files` / `facts` | the file set | one record replaced, inserted or removed |
| `units`, `members` | every file's declarations | the keys this file declared before or declares now, re-merged from the records in path order |
| `instantiations`, `subclasses` | every file's edges | same, keyed by instantiated module / base class |
| `defines` | this file only | replaced with the record |
| `Candidates::units` / `macros` | the index alone | re-derived from the (already updated) index |
| `Candidates::words` | every file's tokens | this file's words given back and its new ones taken, by per-word file count |
| `IncludeGraph::edges` | this file's `` `include``s | re-scanned for this file; other files' left standing (see Assumptions) |
| `IncludeGraph::known` / `folded` | the file set | re-learned from `index.files()` |
| every open buffer's `ExternalResolutions` | the index | refreshed, as after a rebuild |
| the persistent index cache | this file's new record | written through, from the record `update_file` just made — no second parse (`docs/features/index-persistence/README.md`, 2026-08-27) |
| the diagnostics generation | — | bumped |
| the client's code lenses | the index | refresh requested |
An add or a remove takes the *whole* merge rather than the restricted one,
because every id after the change moves; it is still one pass over records in
memory, with no file read and no file re-parsed.
## Measured
Debug build, this Mac, the checked-in 860-file corpus, printed by the
`#[ignore]`d probes (`cargo test -p lucisv_server -- --ignored --nocapture`).
| | before | after |
|---|---:|---:|
| `textDocument/codeLens`, a three-module file | 92 ms (one workspace walk, then a parse of every file mentioning a name) | **0.26 ms** |
| `typeHierarchy/subtypes`, `core_ibex_base_test` | 82 ms (same shape) | **0.71 ms** |
| rescan after one file changed | 1.50 s (whole rebuild) | **33 ms** (45×) |
The "before" column for the two requests is measured in the same probe as the
"after": `Workspace::sources()` is still there and still costs what it always
did, so the row is one walk of the corpus against the lookup that replaced it,
in the same process on the same run. The reindex row is the whole rebuild and
the one-file update measured back to back over the same workspace.
The 33 ms is dominated by two things that are *not* the file: re-deriving the
completion `units`/`macros` tables from the index (a `workspace_symbols("")`
over ~12k members, sorted) and the merge pass over every file's records. Both
are O(index), not O(files read), and neither parses anything. Making them
O(change) is possible and was not done: 45× is the win that was asked for, and
the next 3× is a bigger change to `Candidates` than this round should carry.
## Status / TODO
- [x] `WorkspaceIndex::update_file` / `remove_file`, exact-equality equivalence
with a whole build, pinned from six directions
- [x] `WorkspaceIndex::fingerprint` as the one equivalence witness, used by
both crates' tests
- [x] Instantiation and inheritance edge tables, built by the walks the request
handlers used to run
- [x] `hierarchy::callers_of_each` is a lookup; its `sources()` walk deleted
- [x] `lens.rs` counts through it unchanged; `type_hierarchy::subtypes` is a
lookup
- [x] The census policies pinned at the source of the numbers as well as at the
lens
- [x] `Workspace::update_one` patching index, completion tables, include graph
and every open buffer's overlay
- [x] `Server::reindex_one`: no bar, no log, no scope warnings; generation
bumped, lenses refreshed, every open buffer republished
- [x] The fast-path trigger table, pinned row by row
- [x] The paranoid corpus sweep: every mutation checked against a whole rebuild
- [x] The three inherited obligations from index-scope's Review
- [ ] **Not done, deliberately:** no narrowing of the republish. A lint reads
the index, so any open buffer's diagnostics may have moved; narrowing
correctly needs a dependency graph this server does not have, and
narrowing incorrectly is a stale red squiggle.
- [ ] **Not done, deliberately:** no incremental path for a file appearing or
vanishing *without* the index already holding it. It is a rebuild, it is
rare, and the include graph's cross-file resolution is what makes it one.
- [ ] **Not done, deliberately:** the index is not updated on `didChange`. A
keystroke would cost a second parse and a second analysis of the buffer
on top of the one `Document::new` already does, per keystroke, to make a
count in *another* file fresher than the file on disk.
- [ ] **Filed, not done:** `Candidates::units`/`macros` are re-derived whole on
every incremental update. They are index-derived and correct; they are
also most of the 33 ms.
- [ ] **Filed, not done:** an incremental update cannot re-resolve another
file's `` `include`` when a file is removed. See Assumptions.
## Work log
### 2026-08-27 — dev agent (incremental single-file updates, the edge tables)
- **The FileId decision was the first one and it went against the brief, with
the invariant as the argument.** The brief asked for interned, retired ids so
that an insert would not renumber. Interning makes ids *stable* but makes the
two histories the round has to compare merely equivalent, and the brief's own
acceptance test says to make the equivalence exact if anything observable
reads the numeral — three things do. Renumbering keeps `FileId` meaning
exactly what it has always meant (a position in the path-sorted list), makes
the comparison a string equality on a fingerprint, and costs one merge pass
over in-memory records. The stability interning would have bought is worth
nothing here: the only `FileId`s that outlive a call are the ones in each
buffer's overlay, and those are refreshed by the update itself.
- **The merge is the equivalence proof, not a test of it.** `IndexBuilder::finish`
and `WorkspaceIndex::update_file` both end in one function, `merge`, which
loops over the path-sorted per-file records pushing what it meets. `merge(None)`
rebuilds every table; `merge(Some(affected))` clears and refills only the keys
the changed file could have moved. Same loop, same order, so a restricted
merge and a whole one cannot disagree — there is nowhere for them to disagree.
That is why the round could afford to keep the per-file records rather than
invent a patching scheme with its own ordering rules.
- **The affected set is coarse on purpose.** `members` is keyed by unit and the
affected set names *units*, not `(unit, member)` pairs: rebuilding one whole
package's member sub-table is a handful of entries, and a finer key would be
a second ordering rule to keep honest.
- **Two walks were lifted into `vlog_semantic` rather than copied.** The
instantiation census is what `lens.rs`'s QA tests pin, so a second copy of
that walk inside the index would have been licence for the numbers to drift.
`instantiations.rs` moved whole (its tests with it) and
`type_hierarchy`'s private class walk became `classes.rs`. Both moves are
mechanical; the census policies are now a property of one function each.
- **The unsaved-buffer census delta is the round's one behaviour loss and it is
argued rather than hidden.** Two tests pinned "a just-typed instantiation in
another buffer counts": they were the walk's own freshness, not a policy, and
they cannot survive a table built at index time. Both are rewritten in the
house style under `// Superseded this round:` to pin the new rule from both
sides — the buffer alone moves nothing, and the update moves it. The three
alternatives were considered and rejected in the README's Assumptions: a
per-keystroke index update (a second parse and analysis per keystroke), an
edges-only per-keystroke update (breaks the equivalence invariant outright —
edges from the buffer, declarations from disk, an index equal to no build at
all), and a live overlay of dirty buffers over the table (needs dirty
tracking the server does not do).
- **Eight progress tests changed, all for the same one reason and none of them
weakened.** A save is the trigger those tests reached for when they needed a
rescan, and a save is exactly what stops being one. Each now uses a trigger
that really does rescan — two files in one watcher event, or a settings
change — and keeps its own subject (the bar goes up and comes down, the bar
is down before the republish, the refresh rides after it, three outstanding
requests answer by id). `a_save_puts_a_bar_up_and_takes_it_down_again` was
renamed to name the trigger it now uses, and the property it used to carry —
that a save reports itself — is replaced by
`a_one_file_save_costs_no_bar_and_no_log_line`, which is the new rule.
- **One lens test's assertion was superseded, and its replacement is stronger.**
`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted
`whole_file < one_name * 2` — "the batch is one walk, not one per module".
There is no walk; both sides are microseconds dominated by one file read
each, so the ratio pins noise. It now asserts what the round actually bought:
a whole file's lenses cost less than a tenth of one workspace walk, measured
in the same loop.
- **The e2e progress transcript lost a bar**, which is the model becoming
visible on the wire again: startup (empty scope, `0 files indexed`), the
widening `didOpen` (`1 file indexed`), and then a save that reports nothing
because it is one parse.
- **The three inherited obligations are pinned as permanent tests**, in
`state.rs` beside the scope tests they belong with: lowering `scopeDepth`
narrows the index on the next rescan (the settings axis moves both ways,
unlike the open axis); a filelist appearing mid-session flips the ladder to
rung 1 *and changes what is indexed*, with the open buffer still overlaid;
and a buffer opened outside every root rides the folder rung like a rootless
one, its own directory at depth 0 and `/` at depth 99.
- Files touched: `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/src/lib.rs`,
`crates/vlog_semantic/src/instantiations.rs` (moved in),
`crates/vlog_semantic/src/classes.rs` (new),
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/{state,server,hierarchy,lens,type_hierarchy,inlay,candidates,includes,watch,main}.rs`,
`crates/lucisv_server/tests/e2e.rs`, `TODO.md`,
`docs/features/{code-lens,type-hierarchy,hierarchy,workspace-index,lucisv-server,indexing-ux,work-done-progress,file-watching}/README.md`,
this README. No new dependency, no version bump, no `docs/site/`, no commits.
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2244
passed, 0 failed, 8 ignored** — measured against a clean `HEAD` worktree's
**2217 passed, 5 ignored**, so 27 new passing tests and 3 new `#[ignore]`d
probes, with 2 superseded in place and 1 renamed.
`cargo test -p vlog_formatter`: 180 passed across its seven binaries (114 of them `verification.rs`), untouched — `verify.rs` never appears in this round's diff. `cargo build && node
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`.
The 30 new tests, and what each is for:
| test | pins |
|---|---|
| `adding_a_file_gives_the_index_a_whole_build_would_have` (vlog_semantic) | the hard direction: the new file sorts first, so every later id and every table naming one moves |
| `replacing_a_file_touches_only_what_that_file_said` (vlog_semantic) | the restricted merge: the other file's edge survives, the replaced file's does not |
| `removing_a_file_gives_the_index_a_whole_build_would_have` (vlog_semantic) | removal, renumbering down, edges going with the file, removing twice |
| `removing_a_file_moves_the_disambiguation_winner` (vlog_semantic) | the sharpest derived answer: the file that won a duplicate name is the file that goes |
| `a_file_that_redefines_a_name_another_file_declares_lands_in_path_order` (vlog_semantic) | insertion into a table that already holds the other file's copy, both directions |
| `a_rename_is_a_remove_and_an_add_and_lands_where_a_build_would_put_it` (vlog_semantic) | the rename-shaped sequence |
| `an_update_survives_every_degenerate_file_there_is` (vlog_semantic) | empty, whitespace, not-Verilog, does-not-lex, comment-only; and an empty index |
| `a_full_build_and_a_build_minus_one_plus_that_one_are_the_same_index` (vlog_semantic) | the headline invariant, over a six-file fixture, with **every** file taken out and put back |
| `the_instantiation_table_records_the_census_the_hierarchy_counts` (vlog_semantic) | every census policy at the source of the numbers, plus the spans a hierarchy item is built from |
| `the_inheritance_table_records_every_class_that_names_a_base` (vlog_semantic) | file order, a parameterized base, a class in a package, a class in a module, the counts |
| `the_edge_tables_are_empty_for_a_workspace_with_no_edges` (vlog_semantic) | the degenerate lookups, and a default index |
| `only_a_file_the_index_already_holds_takes_the_incremental_path` (state) | the gate, from four sides, including a file that becomes held |
| `one_files_edit_reaches_every_table_the_index_answers_from` (state) | declaration, instantiation edge, inheritance edge, completion word, include edge — all five in one update |
| `a_file_the_cap_or_the_disk_takes_away_leaves_the_index` (state) | removal through `update_one`: deleted on disk, and grown past the cap |
| `an_open_buffer_beats_disk_on_the_incremental_path_too` (state) | `collect_sources`'s precedence, for one file |
| `the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus` (state) | the paranoid sweep: 172 real files, 6 mutated five ways, every one checked against a whole rebuild |
| `lowering_the_scope_depth_narrows_the_index_on_the_next_rescan` (state) | inherited obligation (a) |
| `a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one` (state) | inherited obligation (b), on the index's content and not just the rescan |
| `a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one` (state) | inherited obligation (c), at depth 0 and at depth 99 |
| `qa_perf_one_file_against_the_whole_rebuild` (state, `#[ignore]`) | the 45× |
| `the_fast_path_is_taken_for_one_held_file_and_for_nothing_else` (server) | the trigger table, five rows |
| `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses` (server) | what the fast path keeps |
| `a_one_file_save_costs_no_bar_and_no_log_line` (server) | what it drops |
| `a_one_file_save_answers_from_the_file_it_saved` (server) | the edit reaches the index and the rest of the workspace is untouched |
| `a_whole_rescan_puts_a_bar_up_and_takes_it_down_again` (server, renamed) | the bar's own rule, on a trigger that still rescans |
| `qa_perf_lens_lookup_against_the_walk_it_replaced` (lens, `#[ignore]`) | 0.26 ms against 92 ms |
| `qa_perf_subtypes_lookup_against_the_walk_it_replaced` (type_hierarchy, `#[ignore]`) | 0.71 ms against 82 ms |
| `a_save_of_one_file_updates_the_index_over_the_wire` (e2e) | the real binary: the save moves the definition answer, and the untouched file answers exactly what it did |
| `a_class_is_found_wherever_it_may_be_written`, `a_parameterized_base_names_the_bare_class`, `a_declarations_extent_contains_its_own_name` (vlog_semantic `classes`) | the lifted walk, in its new home |
Two tests were superseded in place and are named in the work log above:
`an_unsaved_instantiation_is_a_caller_before_it_is_saved` and
`an_unsaved_extends_is_a_subtype_before_it_is_saved`, both replaced by the
`…counts_from_the_moment_the_index_sees_it` form; and
`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` was renamed and
given the stronger assertion.
## QA log
### 2026-08-27 — QA agent (equivalence attack pass)
**Verdict up front: committable as-is.** No production-code defect found
under any constructed attack. One documentation-accuracy finding (LOW,
non-blocking) in the Assumptions section's memory estimate. Nine new tests
added, all passing, none exposing a bug — they pin behavior that was correct
but unverified against the specific adversarial shapes below.
**Gates, re-run from a clean state (before adding anything):**
`cargo fmt --all -- --check` clean. `cargo clippy --all-targets --workspace`
zero warnings. `cargo test --workspace`: 2244 passed, 0 failed, 8 ignored —
matches the dev's own count exactly. `cargo test -p vlog_formatter`: 180
passed across seven binaries (114 `verification.rs`) — `verify.rs` does not
appear anywhere in `git diff 7266b13` (`git diff --name-only | grep verify`:
empty). `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
`smoke: OK`. After adding the tests below, `cargo test --workspace`: **2253
passed, 0 failed, 8 ignored** (2244 + 9 new), fmt and clippy still clean.
**1. The ghost hunt and the affected-keys verdict — verified clean.**
`WorkspaceIndex::update_file`'s `Ok(at)` arm computes `affected` as
`Affected::of(&self.facts[at])` (the *old* record's names) then
`affected.add(&facts)` (the *new* record's names) — a union of both sides,
read directly at `crates/vlog_semantic/src/workspace.rs:311-315`. That is the
side that matters: a name only the old record declared is still in the
cleared set even though the new record no longer supplies it, so `merge`'s
`self.units.remove(name)` followed by a full re-scan of **every** file's
current facts (not just the changed one, `workspace.rs:422-460`) leaves
nothing behind for it — no stale one-entry `Vec` survives. Constructed the
exact ghost explicitly:
`a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it`
(vlog_semantic `tests/workspace.rs`) — a file that is the *sole* declarer of
`solo` stops declaring it; `units("solo")` comes back empty and the
fingerprint matches a fresh build. Passes. The same union covers edge-table
keys too: `Affected::add` extends `modules` from `facts.instantiations` and
`bases` from `facts.subclasses` (`workspace.rs:487-489`), so a file that stops
instantiating `M` shrinks `M`'s table the same way — already covered by the
dev's own `replacing_a_file_touches_only_what_that_file_said`, re-verified
here by re-running it and by the new sequence test below.
**2. Byte-identical histories, adversarially — six new tests, all pass**
(`crates/vlog_semantic/tests/workspace.rs`):
- `a_long_interleaved_sequence_matches_a_fresh_build_at_every_step` — update
A, update B, remove A, re-add A, update B again, fingerprint-checked after
**every** step (not just at the end, which would miss a bug that only shows
two steps later).
- `a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it`
— the ghost hunt above.
- `adding_a_new_file_that_duplicates_an_existing_name_lands_by_path_order_either_direction`
— the dev's own duplicate-name test only attacks the restricted-merge
(`Ok(at)`) arm; this attacks the whole-merge (`Err(at)`, brand-new file)
arm, both sort directions.
- `find_define_answers_in_current_file_id_order_after_cross_file_updates` —
`` `define``/`` `undef`` shadowing across files, then a renumbering add, then
the answer re-checked in the new id order.
- `updating_a_file_to_empty_text_differs_from_removing_it` — confirmed
**different**, deliberately: `update_file(path, "")` keeps the file's
`FileId` slot (still a file, contributing nothing); `remove_file` drops the
slot and renumbers everything after it. Not pinned anywhere else in the
round's own tests, so pinned here.
- `same_named_files_in_different_directories_updated_alternately_stay_correct`
— two files named `defs.sv` in different directories, updated A then B then
A again, fingerprint-checked at each step (identity is the path,
`binary_search_by` compares `PathBuf`s, never the filename alone).
**3. The moved walks — verbatim, confirmed byte-for-byte.**
`diff` of `crates/lucisv_server/src/instantiations.rs` (at `7266b13`) against
`crates/vlog_semantic/src/instantiations.rs`: the only changes are added doc
comments (the "Lifted from..." note and two new one-line field docs); every
line of code, every test, is identical. `classes.rs` is new but its three
functions (`declarations`, `collect`, `extends_name`) are line-for-line
identical to the private walk `type_hierarchy.rs` used to carry (compared
directly against `git show 7266b13:crates/lucisv_server/src/type_hierarchy.rs`
lines 141-274). `hierarchy::callers_of_each` and `type_hierarchy::subtypes`
were rewritten (not moved) to read the new edge tables instead of walking
`Workspace::sources()`; read both in full. The file-grouping `subtypes` and
`callers_in` rely on ("edges arrive in file order, so one file's are
consecutive") holds by construction: `merge` always fully clears and
rebuilds an affected key's whole vector by iterating `self.facts` in
ascending `FileId` order (never appends to a partial vector across separate
merges), so the grouping invariant cannot be violated by any sequence of
incremental updates, not just the initial build. Re-ran `lens.rs`'s QA policy
tests and `the_instantiation_table_records_the_census_the_hierarchy_counts` /
`the_inheritance_table_records_every_class_that_names_a_base` — unchanged,
passing. `git diff --stat` on `hierarchy.rs`/`type_hierarchy.rs`/`lens.rs`
test bodies: exactly the two superseded freshness tests
(`an_unsaved_instantiation_is_a_caller_before_it_is_saved` →
`an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it`,
and the `extends` equivalent) plus the renamed/strengthened lens ratio test
(`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` →
`..._a_fraction_of_a_workspace_walk`) and one doc-comment-only touch on
`qa_perf_worst_case_common_word_module_name` (no logic change). Each
supersession keeps the original point per house style: both rewritten tests
assert the buffer alone does *not* move the count and then that
`ws.update_one(path)` does — the same "unsaved edit is visible" property the
old tests pinned, restated for a table that is index-fresh rather than
per-request-fresh.
**4. `Candidates::words` exact bookkeeping — two new tests, both pass**
(`crates/lucisv_server/src/candidates.rs`):
`a_shared_word_dropped_from_one_file_is_still_offered_by_the_other` and
`updating_the_same_file_twice_in_a_row_never_double_counts_or_goes_negative`.
Read `set_words` (`candidates.rs:78-99`): it removes the *previous* call's
words for this path before counting the new ones, so calling it twice in a
row for the same path decrements based on the first call's own words, never
double-decrements, and never underflows.
**5. The freshness delta's edges — verified against the code, not just the
docs.** `hover::narrowed_to_the_include_graph` (`hover.rs:84-105`) is the
concrete case: `candidates` come from `find_define`, which only ever
enumerates files the index *currently* holds, while `reachable` comes from
`includes::reachable_from`, whose first hop is resolved live off the buffer's
own current text (`includes.rs:344-350`, "resolved against the buffer's
*current* text rather than looked up in the graph") — buffer-fresh — before
walking the rest of the graph via the index-fresh `IncludeGraph::edges`. The
docs (`code-lens`, `hierarchy`, `type-hierarchy` READMEs, and this feature's
own Assumptions) consistently say which surfaces are index-fresh (lens
counts, `incomingCalls`, `subtypes`) versus buffer-fresh (an include's own
first hop, go-to-definition, document links) — no surface was found
mismarked.
**6. Fast-path discipline.**
- Two saves in one batch: added
`two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates`
(`server.rs`). `process_batch` handles one message at a time
(`for message in batch`, `server.rs:316`), so two `didSave`s in one burst
are **two independent incremental updates**, not coalesced and not a full
rebuild — confirmed: no progress bar, both files' edits land, generation
bumps by 4 (2 saves × 2 bumps each — `set_document` bumps once for the
buffer's own new text, `reindex_one` bumps once more for the fast path;
these are orthogonal and both fire per save, which the test now pins
explicitly since it was not obvious from the docs alone).
- Generation bump / lens refresh / resultId: `reindex_one` bumps `generation`
exactly once and calls `refresh_code_lenses()` exactly once
(`server.rs:1365-1374`), pinned by the dev's own
`a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
`result_id()` is `self.generation.to_string()` (`server.rs:1024-1025`), so
a fast-path update does move a pull-diagnostics client's `resultId` — no
new test needed, it follows directly from the generation bump.
No-bar/no-log: pinned by `a_one_file_save_costs_no_bar_and_no_log_line`,
re-run, passing.
- A save during another operation: the server is single-threaded and
`process_batch` runs to completion before the next receive, so there is no
interleaving to attack — matches the dev's own note.
- A file whose *path* is held but which *is* the filelist: not reachable in
practice — a filelist is a `.f`/similar file, never a `.sv`/`.v`/`.svh`
source, so it is never a member of `self.index.files()` and
`Workspace::update_one`'s gate (`state.rs:36`) returns `false` for it
regardless of the watcher-side `one_scope_file` exclusion
(`watch.rs:27-38`) — the two gates agree by construction rather than by
coincidence, so no separate test was added for this shape.
**7. The include-graph gap — severity-checked, confirmed LOW/harmless
(dangling, not wrong).** Traced every consumer of `IncludeGraph::edges`: only
`reachable`/`reachable_from` read it (`document_links`/`definition` resolve
live off disk via `resolved()`, never consulting `self.edges`). After a file
`B` is removed, another file `A`'s stale forward-edge to `B` can make
`reachable(A)` include `B`'s now-dangling path — but `B` has no `FileId` in
the index any more, so `hover::narrowed_to_the_include_graph`'s filter
(`ws.index().path(*file).is_some_and(|p| reachable.contains(p))`) can never
match a *candidate* against that ghost path, because no surviving file's
current path can equal a path the index no longer assigns to anyone. The
answer is a superset that can only ever be harmlessly too permissive, never
one that manufactures a wrong single-file narrowing. It self-heals the moment
`A` itself is next incrementally updated (`IncludeGraph::update_file`
re-resolves `A`'s own edges fresh off disk). No test added — this is a
reachability argument about aliasing that a unit test would have to
special-case anyway; recorded here for the record instead.
**8. Perf and memory claims — spot-reproduced, one discrepancy found.**
Reproduced all three timing claims on this machine, same corpus, debug build:
`qa_perf_one_file_against_the_whole_rebuild`: 1.517 s → 33.8 ms (45×, matches
the README's 1.50 s → 33 ms exactly). `qa_perf_lens_lookup_against_the_walk_it_replaced`:
67.1 ms → 0.297 ms (README: 92 ms → 0.26 ms — same order of magnitude, machine
variance accounts for the rest). `qa_perf_subtypes_lookup_against_the_walk_it_replaced`:
66.9 ms → 0.720 ms (README: 82 ms → 0.71 ms — very close). All three: **verified
clean.**
**Finding (LOW, documentation accuracy, non-blocking).** The Assumptions
section's memory estimate for `Candidates::per_file` — "Over the corpus that
is ~170k `String`s of per-file lists on top of the ~17k distinct words —
single-digit megabytes" — was checked against the real corpus with a scratch
probe (`Candidates::build` over all 860 corpus files, then
`per_file.values().map(Vec::len).sum()` and a byte estimate from
`String::capacity()`; probe not kept, reproducible in one line from a REPL-ish
test). Measured: **16,750 distinct words** (matches the "~17k" half of the
claim) but **39,673 per-file word entries** — about **4.3× lower** than the
claimed "~170k" — and **~1.38 MB** of per-file `String` storage, itself well
under "single-digit megabytes." The *conclusion* ("single-digit megabytes,"
i.e. the design is memory-cheap enough) is not undermined — if anything the
real number is more favorable than claimed — but the specific "~170k" figure
in the Assumptions section does not match reality and is not pinned by any
test in the round. Not blocking; worth a one-line correction next time this
README is touched.
**9. CLAUDE.md compliance.** No `unwrap()`/`expect()`/`panic!` in library code
in any touched file, checked by grepping each file up to its own
`#[cfg(test)]` module (`workspace.rs`, `instantiations.rs`, `classes.rs`,
`state.rs`, `candidates.rs`, `includes.rs`, `server.rs`, `watch.rs`,
`hierarchy.rs`, `type_hierarchy.rs`, `lens.rs`) — zero matches in all eleven.
No `unsafe` anywhere in the diff. This README has all seven required
sections, each exactly once (plus three extra ones the format allows: the
fast-path trigger table, the derived-state table, Measured). `verify.rs` does
not appear in the diff at all. Every corpus-dependent test checked is
skip-guarded (`if !corpus.is_dir() { ...; return; }`). `TODO.md`'s completed
items are struck through with the original text kept and a note appended,
matching the project's existing convention for closing an item without
deleting it. `docs/site/` diff is empty — untouched, as required. Spot-checked
the struck Handshakes in `code-lens` and `hierarchy` READMEs against the
actual code (`instantiations_of`/`subclasses_of` signatures, the lifted
`vlog_semantic::instantiations`/`classes` modules) — accurate.
**Fixes made:** none to production code — every constructed attack passed.
**Tests added (9, all passing):** the six `vlog_semantic` tests and two
`candidates.rs` tests listed above, plus
`two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates`
in `server.rs`.
## Review
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
(2253 workspace tests, 0 failed), clean. The round's deviation was
better than my brief: keeping FileIds as sorted positions and paying
one in-memory merge per update buys byte-identical histories — the
strongest equivalence there is — where my interned-ids design would
have bought mere observational equivalence plus three consumers to
audit forever. The structural argument (finish and update_file ending
in the one merge over path-sorted records) is the same
one-implementation discipline this codebase now uses everywhere, and
QA's ghost hunt confirmed the affected-keys union reads both the old
and new records, which is the single place the design could have
silently rotted. The moved census walks are byte-for-byte verbatim,
the policy numbers stand, and the freshness delta — counts as of the
index, not of unsaved keystrokes — is the right trade, pinned from
both sides.
The measured wins close two of the audit's oldest filed Handshakes
with a 350x lens speedup and a 45x one-file rescan, on top of the
scope round's narrowing — together these are the large-workarea story
the owner asked for. QA's nine adversarial tests (the long
sequences, define shadowing across renumbering, burst double-saves)
are permanent. I corrected the one LOW finding (the per-file word-list
estimate, 4.3x high; the conclusion stood). The three filed leftovers
(wholesale republish, Candidates re-derivation cost, the include
removal edge) are honest and none blocks. Accepted as shipped.
File diff suppressed because it is too large. Load diff
+606
View File
@@ -0,0 +1,606 @@
# index-scope
## Goal
Open-file-first indexing for a project too big to scan. Until this round the
server had two answers to "which files exist": a filelist, or **every file
under every workspace folder** — and on a large codebase the second one costs
minutes on every save, to answer questions about the handful of folders the
user is actually in. This round makes the walk follow the *open buffers*
instead: `lucisv.index.scope` (`"folder"` by default) scopes the index to the
folders the open files live in, `lucisv.index.scopeDepth` says how far above
each one to start looking for relative files, and opening a file in a folder
the scope does not cover widens it and reindexes. A filelist still outranks
everything — it is the project file — and `"workspace"` restores the old walk
for anyone who wants it. The same round closes the ordering footgun the
previous round's QA found in `vlog_semantic::IndexBuilder`, which is what makes
the second half of the change safe: **the open buffers' files are fed to the
builder first**, so the progress bar completes the user's own files first, and
that is provably a reporting decision with no effect on the index.
## Assumptions
- **The scope ladder is one ladder with a new rung 3.** Highest first:
(1) a filelist — `lucisv.filelist`, else a `filelist` key in a root's config
— defines the scope exactly, unchanged and whole-project;
(2) `lucisv.index.scope: "workspace"` walks every workspace folder, which is
what every session did before this round;
(3) the default: the folders the open buffers live in, each raised
`lucisv.index.scopeDepth` levels, walked. Rung 2 needs a root to mean
anything, so a rootless session is folder-scoped whatever it says.
- **This is a behaviour change for every workspace user, and the honest
statement of it is that cross-file answers are scope-relative.** A symbol in
a folder the scope has not reached does not exist as far as this server is
concerned: `textDocument/definition`, `workspace/symbol`, the call and type
hierarchies, `find_references` and a workspace rename all answer within the
active scope, exactly as they already did within a filelist's. **The
migration line is `"lucisv.index.scope": "workspace"`**, which restores the
old behaviour exactly (pinned by
`the_workspace_scope_setting_restores_the_walk_of_every_root`).
- **The scope only ever grows within a session.** It is derived from every
directory a buffer has been opened *from* (`Workspace::opened_dirs`), not
from the buffers currently open, so `didClose` narrows nothing and costs no
rescan. The alternative — recomputing from the open set — would take a
working answer away at the next unrelated save, which is a worse surprise
than an index that is slightly larger than the editor's tab bar. It is also
the cheap choice: no reindex on close, and no reindex-on-close churn while a
user cycles through files.
- **`didOpen` rebuilds exactly when it widened the scope.** The rule is one
comparison of the scope directories across `set_document`, and it replaces
the old `has_roots()` branch (rootless reindexed, rooted published) with the
question that branch was really asking. Consequences, both deliberate: a
rootless session opening a *second* file in an already-scanned directory no
longer rebuilds (it used to, always), and a session on the filelist or
workspace rung never rebuilds on `didOpen`, because no open buffer can widen
those scopes.
- **The `didOpen` check costs two `scope_dirs()` calls, and each one asks
`filelist_path()` whether rung 1 is in force.** That is a `Discovery` walk up
from each root looking for a config — a handful of `exists()` calls, on an
event that is already about to reanalyze a whole buffer, and orders of
magnitude cheaper than the rebuild it decides against. Named here because it
is the one new per-notification cost this round adds.
- **A workspace folder is a clamp on the folder rung, not a work list.**
Adding one mid-session changes which files exist only once a buffer in it
makes it a scope directory; what it does change immediately is how far the
climb may go (see below). Removing one likewise only loosens the clamp. The
rescan `didChangeWorkspaceFolders` already triggers is unchanged.
- **The climb is clamped at the deepest workspace root containing the
directory** — that is what keeps `scopeDepth: 5` in a two-deep project from
indexing a home directory. **With no root there is nothing to clamp against
and the only floor is `/`**: the loop terminates there rather than spinning,
and the setting means exactly what it says. The rootless default is 0, so
nobody reaches this without asking for it; it is called out in the setting's
own description.
- **The rootless case is unchanged at the default.** A file opened on its own,
at depth 0, still gets a flat one-level read of its directory — no walk, no
`.gitignore` —
(`with_no_workspace_root_the_open_files_own_directory_is_indexed`, untouched
this round). The moment a rootless session raises `scopeDepth` it has named
a tree, so the raised directory is walked instead; that is the one place the
rung's behaviour depends on the depth being non-zero, and it is what stops a
raise from *losing* the file's own siblings.
- **One honest filter gap: a root's `.gitignore` does not reach a walk that
starts below it.** `lucisv_core::walk` reads ignore files from the walk's own
starting directory downwards, so a rule written at the workspace root is not
applied when the folder scope starts at `rtl/`. Every `exclude` pattern —
the config's and the pushed one — is matched against whole paths and is
unaffected. Pinned both ways in
`the_folder_scope_honours_every_exclude_and_the_gitignores_below_it`, rather
than left to be discovered. The fix belongs in `lucisv_core`'s walk (parent
ignore files, as the `ignore` crate does it) and is filed, not done: it is a
change to the CLI's walk semantics too, which is not this round's scope.
- **The startup index is empty, and that is the point.** No buffer is open at
`initialize`, so the folder scope has no folder yet; the first `didOpen`
widens it and rebuilds. On a huge project this is the whole saving. It also
means a client whose settings say `"workspace"` still gets one empty startup
scan and then a rescan when its settings land — the same one extra rescan
`lucisv.exclude` and `lucisv.filelist` have always cost, for the same reason
(neither settings door can deliver before `initialized`).
- **Open buffers still overlay every rung.** A buffer's text beats disk and a
buffer outside the scope still contributes itself, exactly as with a
filelist. Nothing about diagnostics, formatting or any single-file feature
depends on the scope: the per-buffer analysis is bottom-up and instant, and
this round does not touch it.
- **Wrong-typed settings fall back to the *narrow* default**, the same
direction `maxFileSize` falls back to the cap: a misparse must not silently
buy a whole-workspace scan. `"scope"` is matched exactly — `"Workspace"` is
junk — because the enum in `package.json` is what a settings UI offers and
forgiving it here would make a typo mean different things on different
clients.
- **The progress denominator, the cap counts and the output log follow the
active scope for free.** They all read the same work list
(`index_order`'s length, known before the first parse), so nothing was
re-plumbed; verified by `the_bar_names_the_open_file_before_the_rest_of_the_scope`
and by the e2e transcript, whose startup bar honestly ends `0 files indexed`.
## Handshakes
### `vlog_semantic` — `IndexBuilder` is order-insensitive
The previous round shipped `IndexBuilder` as a dumb accumulator whose ordering
contract was a doc comment ("feed it `index_order`'s list"), and its QA proved
that a caller who did not got different `FileId`s and a different winner for a
name two files declare (indexing-ux README, QA log 2026-08-27, MEDIUM). That is
closed by construction:
```rust
pub fn add_file(&mut self, path: PathBuf, src: &str); // parses, keeps FileFacts
pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups, merges
```
- `add_file` parses its file and reads off what it declares into a private
per-file record (`FileFacts`: the path, the `` `define`` table, the file-scope
declarations in declaration order, the members in traversal order). **The
parse still happens in `add_file`**, so a caller reporting progress between
calls is reporting work that has really been done.
- `finish` sorts those records by path — `sort_by` is stable, `dedup_by` keeps
the first of a run, which is exactly `index_order`'s rule — and only then
hands out `FileId`s and merges the declarations into the `units`/`members`
tables. No insertion order can reach the result.
- **`WorkspaceIndex::build` is byte-identical for every existing caller**, and
the proof is that all 31 pre-existing `vlog_semantic` tests are unchanged and
green, including `file_ids_follow_the_sorted_paths_whatever_order_they_arrive_in`,
`a_module_declared_in_two_files_is_ambiguous_in_path_order` and
`the_incremental_builder_is_what_build_is_made_of`. `build` still calls
`index_order` first — not for correctness now, but so a duplicate path is not
parsed twice.
- **Why this shape and not a type-enforced two-phase API.** The alternative the
brief allowed was a builder that cannot be misused because the types forbid
it — an `UnsortedBuilder` that only a `SortedFiles` value can be fed. That is
a second type, a second constructor and a conversion, to protect an invariant
that a five-line `sort_by`/`dedup_by` in `finish` removes outright. Making
the wrong call impossible beats making it a compile error when it costs less.
The cost is memory: the per-file records for the whole workspace are held
until `finish`, which is the same data the finished index holds (names,
spans, kinds), partitioned rather than merged — no `Semantics` and no source
text is retained.
- Permanent re-attack: `no_insertion_order_can_change_what_the_builder_produces`
(the QA pair plus a nested-class/defines fixture, in three orders, compared
by a full fingerprint of files, ids, disambiguation order, member tables and
define counts) and `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at`.
- `index_order` stays public and unchanged: the server needs the work list's
*length* before the first parse for the progress denominator.
### `lucisv_server::settings`
- Two new fields, `index_scope: IndexScope` (`Folder` | `Workspace`, default
`Folder`) and `index_scope_depth: u64` (default 0), parsed from
`lucisv.index.scope` / `lucisv.index.scopeDepth`. Nested under `index` like
the other two, so both settings doors — push and pull — carry them with no
new code (`the_index_settings_come_through_the_pull_door_too`).
- `IndexScope` is public; `state.rs` matches on it.
### `lucisv_server::state`
- `Workspace::scope_dirs() -> Vec<PathBuf>` is **new and public**: the
directories the folder scope walks, or empty when the folder rung is not in
force. `server.rs` compares it across a `didOpen`.
- `Workspace::set_document` now also records the buffer's directory. It is the
one place a directory enters the scope.
- `walked_files` takes the directories to walk instead of reading `self.roots`;
`sibling_files` is a free function taking the same list.
- `has_roots()` is `#[cfg(test)]` now — `didOpen` was its only production
caller.
- Test-only `open_whole_workspace` / `open_whole_workspace_with` are the
one-line spelling of "this test wants the pre-round scope", used by the
dozens of tests across the crate whose subject is a hover or a rename rather
than the scope.
### `lucisv_server::server`
- `didOpen` reindexes when `scope_dirs()` moved, else publishes. One rule for
rootless and rooted; the rebuild rides the existing bar, generation bump,
code-lens refresh and republish.
- `Server::started(connection, roots, abilities, ClientSettings)` is the real
constructor and `Server::new` delegates to it with the defaults. The
parameter exists for the tests, which is stated where it is written: a test
whose subject is not the scope starts from the wide scope rather than driving
a `didChangeConfiguration` and then reasoning about the extra rescan.
### `editors/vscode`
- Two new `contributes.configuration` properties, both carrying the honesty
notes: what stops being answered, that the scope grows and never shrinks,
the migration line, and that a filelist overrides both. No `extension.js`
change — the whole `lucisv` section including the nested `index` object is
already synchronized.
## Status / TODO
- [x] `lucisv.index.scope` (`"folder"` default, `"workspace"` opt-in), both
settings doors, junk → the narrow default
- [x] `lucisv.index.scopeDepth` (default 0), clamped at the deepest containing
workspace root, and at `/` with no root
- [x] Filelist still outranks both; `scope`/`scopeDepth` ignored on rungs 1–2
- [x] `didOpen` widens the scope and reindexes; the rootless branch unified
into the same rule
- [x] Scope only grows within a session; `didClose` costs no rescan
- [x] Both settings join the rescan condition; `logFiles` still does not
- [x] Open buffers' files fed to the builder first; progress reports name them
first
- [x] `IndexBuilder` order-insensitive, with the QA attack as a permanent test
- [x] `package.json` descriptions carry the scope-relative-answers warning and
the migration line
- [x] 19 new tests (12 state, 2 server, 1 e2e, 2 vlog_semantic, 2 settings),
3 existing ones extended, 1 superseded test rewritten; every other test
in the crate that wanted the whole workspace now says so
- [ ] **Not done, deliberately:** no `lucisv.toml` key for either setting. They
are editor-session resource settings — how much of *this machine's* time
to spend — not project style, the same reason `maxFileSize` has none.
- [ ] **Not done, deliberately:** no shrink-on-close, no LRU on the scope, no
time-based eviction. All three are guesses at a problem nobody has
reported; the escape hatch for a session that grew too wide is to
restart it or set a filelist.
- [ ] **Filed, not done:** `lucisv_core::walk` does not read `.gitignore` files
above its starting directory, so a root-level ignore rule does not apply
to a folder-scoped walk. Fixing it changes the CLI's walk too.
- [ ] **Filed, not done:** the folder scope makes the write-path honesty gap
the previous round's QA found sharper — a workspace rename now rewrites
only what is in scope, and says nothing about what is not. The follow-up
task the lead filed for the size cap covers exactly this and should name
the scope too.
## Work log
### 2026-08-27 — dev agent (open-file-first indexing, folder-scoped walk)
- **The builder was hardened first, because the ordering change depends on
it.** Feeding the open files first is only free if insertion order provably
cannot reach the index, so `IndexBuilder` was rewritten to accumulate
`FileFacts` and sort in `finish` *before* anything in the server was
reordered. The five-line sort beat the type-enforced two-phase alternative
on every axis that matters here (one type instead of three, no conversion,
and the misuse becomes impossible rather than merely uncompilable); the price
is that the per-file records live until `finish`, which is the index's own
data partitioned rather than merged. `WorkspaceIndex::add_file`/`add_members`
became the free `facts_of`/`collect_members` with the same traversal, so the
merged tables come out in the same order they always did — which is why all
31 existing tests are byte-identical and green.
- **The scope ladder went in `source_files`'s rung 3, not beside it.** The
filelist rung and the walk are untouched; `default_files` now chooses between
`walked_files(&self.roots)` and `folder_files()`, and `folder_files` is
`walked_files(&scope_dirs())` with the one rootless exception. That kept the
exclude/gitignore/cap plumbing literally the same function, which is what
makes "every filter still applies" a fact rather than a claim.
- **`opened_dirs`, not `docs`, is what the scope is derived from.** This is the
close-shrink decision: the scope grows within a session and never narrows.
Deriving from the open documents would have been one less field, but it makes
`didClose` silently change what the *next* save indexes, which is a worse
surprise than a scope that is a few folders wider than the tab bar. It also
keeps `didClose` free of any rebuild.
- **`didOpen`'s branch is now one comparison, and it subsumes the rootless
rule.** `has_roots()` was answering "can an open buffer widen the scope?" by
proxy; `scope_dirs()` answers it directly and correctly on all three rungs.
Two deliberate deltas fell out and are documented: a rootless session opening
a second file in a directory it already read no longer rebuilds, and a
rootless session with a filelist no longer rebuilds on open either (the
filelist defines the scope; the buffer is overlaid at the next rebuild
regardless).
- **The clamp is the deepest containing root, not the first.** With nested
workspace folders the tighter floor is the honest one — the user opened both,
and the inner one is the more specific statement about that file.
- **The rootless flat read is kept at depth 0 and only at depth 0.** Turning it
into a walk would have changed the "a file opened on its own" case that has
its own documented reason to be shallow; leaving it flat at *every* depth
would have made `scopeDepth: 1` index the parent directory while losing the
file's own siblings, which is worse than either. So: unchanged at the
default, walked the moment the user raises the depth, and both halves pinned.
- **The startup scan indexes nothing now**, because no buffer is open yet. That
reads as alarming and is exactly the feature: the e2e transcript's first bar
ends `0 files indexed`, the `didOpen` bar reports the real file, and that
sequence is asserted on the wire.
- **The blast radius was 151 tests, and the honest fix was to make each of them
say what scope it wants.** Every test across the crate whose subject is not
the scope now calls `Workspace::open_whole_workspace` or `Session::wide`
instead of the plain form — a mechanical, reviewable change that leaves each
test exercising exactly what it exercised before, with the scope no longer a
hidden variable. Four settings pushes inside those tests gained
`"scope": "workspace"` for the same reason a push replaces every field. The
new default's own behaviour is covered by the 22 new tests rather than by
accident.
- **One test was superseded rather than repaired.**
`a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish`
pinned the branch this round deletes; it is replaced by
`a_didopen_rebuilds_exactly_when_it_widens_the_scope`, same case list, under
the rule that replaced it, with an explicit `Superseded this round:` note in
the house style.
- **Two e2e expectations moved, both of them the model becoming visible on the
wire:** `indexing_reports_its_progress_over_the_wire` now shows three bars
(empty startup, the widening `didOpen`, the save) with the honest end
messages, and `a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire`
counts two refreshes because there are now two rescans in its script.
- **The `.gitignore` gap was found by a failing test I had written to assert
the opposite**, and is documented and pinned as a delta rather than papered
over or "fixed" by reaching into `lucisv_core`'s walk, which is the CLI's
too.
- Files touched: `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/settings.rs`, `crates/lucisv_server/src/state.rs`,
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/tests/e2e.rs`,
the test modules of `completion/hierarchy/file_ops/includes/inlay/hover/lens/
nav/ports/rename/type_def/type_hierarchy/signature/symbols` (constructor
swap only), `editors/vscode/package.json`,
`docs/features/lucisv-server/README.md`,
`docs/features/indexing-ux/README.md`, this README. No new dependency, no
version bump, no `CHANGELOG` edit, no `docs/site/`, no commits.
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2217
passed, 0 failed** (2198 on `HEAD`, measured — 19 new). `cargo test -p vlog_formatter`:
green, untouched. `cargo build && node editors/vscode/smoke.js
target/debug/lucisv-server`: `smoke: OK`. `node -e JSON.parse(package.json)`:
parses.
The 19 new tests, the 3 extended and the 1 rewritten, and what each is for:
| test | pins |
|---|---|
| `no_insertion_order_can_change_what_the_builder_produces` (vlog_semantic) | QA's attack, three orders, full fingerprint — ids, disambiguation winner, member tables, defines |
| `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at` (vlog_semantic) | `index_order`'s dedup rule surviving the move into `finish`, non-adjacent duplicate included |
| `the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace` (settings) | the default, both words, six junk values → the narrow default |
| `the_scope_depth_is_zero_until_a_client_raises_it` (settings) | the default, no upper bound, six wrong types |
| `the_index_settings_come_through_the_pull_door_too` (settings) | both new keys through `from_section` as well |
| `the_default_scope_is_the_open_files_own_folder_and_everything_under_it` (state) | the headline: own folder and subtree, no sibling folder, nothing before a buffer opens |
| `a_scope_depth_of_one_reaches_the_folder_beside_it` (state) | the `rtl/` + `../include` layout the setting exists for |
| `the_climb_stops_at_the_workspace_root` (state) | the clamp at depth 99, and the deepest of two nested roots winning |
| `a_rootless_climb_stops_at_the_filesystem_root` (state) | termination at `/` with no root — on the directories, never walking one |
| `a_rootless_session_that_raises_the_depth_walks_instead_of_reading_one_level` (state) | the one exception, from the other side |
| `the_workspace_scope_setting_restores_the_walk_of_every_root` (state) | the migration line, and that the depth is ignored on that rung |
| `a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say` (state) | rung 1 over rung 3, and that no `didOpen` can widen a filelist |
| `closing_a_file_never_narrows_the_scope` (state) | the close decision |
| `the_folder_scope_honours_every_exclude_and_the_gitignores_below_it` (state) | both excludes, the in-scope `.gitignore`, **and** the root-`.gitignore` gap, both scopes |
| `a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened` (state) | folder events × the folder rung |
| `a_scope_or_a_depth_change_asks_for_a_rescan` (state) | both directions, both settings |
| `the_open_files_are_indexed_first_and_the_index_cannot_tell` (state) | the event order **and** that the index equals the plain-order one |
| `a_didopen_rebuilds_exactly_when_it_widens_the_scope` (server) | the unified rule: widens → rebuild, covered → publish only, rootless and rooted |
| `a_new_index_scope_or_depth_rescans_through_the_real_dispatch` (server) | parser + change test + rescan, end to end through `didChangeConfiguration` |
| `the_bar_names_the_open_file_before_the_rest_of_the_scope` (server) | `1/3 m_open.sv` first on the wire |
| `the_folder_scope_widens_when_a_file_in_another_folder_is_opened` (e2e) | the real binary: definition into a sibling folder empty, opening it resolves, and a `"workspace"` client resolves immediately |
| `indexing_reports_its_progress_over_the_wire` (e2e, updated) | the model on the wire: three bars, `0 files indexed` then `1 file indexed` twice |
## QA log
### 2026-08-27 — QA agent (gates, attack surfaces, mechanical-sweep audit)
**Gates, re-run clean on the untouched working tree.** `cargo fmt --all --
--check`: clean. `cargo clippy --all-targets --workspace`: zero warnings.
`cargo test --workspace`: **2217 passed, 0 failed, 5 ignored** (matches the
dev's count exactly). `cargo test -p vlog_formatter`: 114 passed, untouched.
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
`smoke: OK`. Every temporary probe test below was inserted, run alone, and
reverted before the final re-run; the final `git diff` of `state.rs`/`server.rs`
hashes identically to the pre-QA diff, confirming no probe was left behind.
**The 151-test mechanical sweep.** Sampled all 14 non-scope test modules
(`completion`, `file_ops`, `hierarchy`, `hover`, `includes`, `inlay`, `lens`,
`nav`, `ports`, `rename`, `signature`, `symbols`, `type_def`,
`type_hierarchy` — every `.open_roots(` call in them, ~40 sites) plus the
`server.rs`/`state.rs` `Session::wide`/`Workspace::open_whole_workspace`
call sites: **every one is a pure constructor swap** (`open_roots` →
`open_whole_workspace`, or `Session::with`/`Session::new` →
`Session::wide`/`Session::wide_with`, or a `"scope": "workspace"` key added
to a settings push). No sampled assertion changed beyond that. Verdict:
**mechanical sweep is genuinely mechanical**, as claimed.
**The inverse hunt (tests that should have been swapped but weren't) found
one real bug and two weakened premises**, all in `state.rs`'s own test
module, which is the one file that still has bare `.open_roots(` calls
mixed in with the new scope tests:
- **MEDIUM — `a_folder_added_twice_across_two_events_is_absent_after_one_removal`
(`crates/lucisv_server/src/state.rs:851-876`) no longer tests what it
says it does.** It calls `ws.open_roots(...)` but never opens any buffer,
so under the new default (folder scope) `scope_dirs()` is empty for the
entire test and `"x"` is never indexed — not because of the root
add/remove/dedup logic under test, but because nothing is ever in scope.
The final `assert_eq!(indexed(&ws, &["x"]), [])` passes vacuously.
Confirmed by temporarily inserting a premise check
(`assert_eq!(indexed(&ws, &["x"]), ["x"])`) right after the first
`change_roots` add and running the test alone: **it failed**
(`left: [] right: ["x"]`), proving the premise never held. The
`change_roots` return-value assertions (`true`/`false`/`true`) are
unaffected and still test the set-not-multiset behavior correctly — only
the closing `rebuild_index`/`indexed` pair is vacuous. Fix: either open a
buffer in `extra`'s directory before checking, or switch to
`open_whole_workspace` and keep the indexed-content assertion meaningful.
Not fixed directly — it is a one-line-comment-vs-actual-behavior mismatch
that the dev should decide the intended fix for (open a buffer, since the
test's own comment is about indexing, not about scope).
- **LOW — `an_open_buffer_is_indexed_however_big_the_file_is`
(`state.rs:1151-1168`)'s "premise: capped on disk" assertion is now true
regardless of the cap**, because no buffer is open at that point either,
so folder scope is empty and nothing is indexed for that reason first.
The test's actual point (the open buffer overrides the cap after
`set_document`) still holds and is still meaningfully exercised, since
`set_document` adds the directory to scope before the second
`rebuild_index`. Not a false pass on the assertion that matters, but the
premise no longer demonstrates what its comment claims.
- **LOW — stale rung numbers in comments**, not behavior:
`without_a_filelist_there_are_no_incdirs_at_all` (`state.rs:1454-1462`)
says "Rung 2 of the ladder names no include path," and
`a_broken_filelist_leaves_the_include_graph_without_incdirs`
(`state.rs:1464-1475`) implies the same fallback. Both are now rung 3
(folder scope) by default, not rung 2 — the assertions (`None` either way,
since no filelist means no incdirs regardless of which walk rung ran) are
unaffected, but the comments should say "rung 2 or 3" or just "the
fallback."
All other `.open_roots(` calls left bare in `state.rs` were individually
checked and are correct as left: the filelist tests (rung 1 always wins,
scope-independent), the rootless tests (rung 3 is the only rung with no
root, unaffected), and `a_folder_change_that_changes_nothing_asks_for_no_rescan`
/ `a_trailing_slash_in_the_removed_folder_still_matches_the_held_root` (test
`change_roots`'s bookkeeping only, no indexed-content assertion to weaken).
**Scope correctness at the boundaries — all traced and probed, all correct,
none pinned by a permanent test beyond what's listed below:**
- Depth clamping when the open file *is* at the root: `raised()`'s first
loop iteration compares `out == floor` before descending, so a root-level
buffer returns immediately at any depth. Covered by
`the_climb_stops_at_the_workspace_root`.
- Nested roots, deeper clamps tighter: `max_by_key(|root|
root.components().count())` — confirmed by the same test's second half.
- `scopeDepth` past the path depth: terminates at `/` (rootless) or the
containing root (rooted), confirmed by
`a_rootless_climb_stops_at_the_filesystem_root` and the depth-99 case in
`the_climb_stops_at_the_workspace_root`.
- **A file opened from outside every workspace root, with roots present
(folder scope still the active rung): no permanent test covers this.**
Probed with a temporary test (root A open, a buffer opened from an
unrelated tree B): `scope_dirs()` at depth 0 is just B's own directory,
and raising `scopeDepth` to 99 climbs all the way to `/` — exactly the
rootless behavior, because `raised()`'s `floor` is `None` when no root
contains the directory. **Correct, but untested and not called out in the
README's Assumptions** as a distinct case from "rootless session."
Recommend a pinned test plus a sentence in the README.
- Symlinked folders / case differences on macOS: `opened_dirs` dedups by
literal `PathBuf` equality (`seen == dir`), not canonicalized — a symlink
and its target, or `/RTL` vs `/rtl`, are two separate scope directories
that both get walked. **Not a regression**: the pre-round `sibling_files`
deduped the same way. Informational only.
**The grows-only model's costs.** Opening three folders then closing all
three: union sticks, verified with a temporary test (three folders opened,
all three closed, `rebuild_index`, same five packages still indexed) — not
just the dev's one-of-two-closed case. The pathological end (opening files
across many folders converges the walk cost back toward the whole-workspace
walk this round exists to avoid) is **acknowledged only indirectly** — the
README's "Not done, deliberately" section says there's no shrink/LRU/TTL and
names "restart or set a filelist" as the escape hatch, but never states the
asymptotic point plainly. Recommend one sentence owning it, e.g. "a session
that has opened files in most of the project's folders pays close to the
whole-workspace walk on every rescan; that is the trade, not a bug."
**Builder hardening.** `no_insertion_order_can_change_what_the_builder_produces`
and `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at` both
pass. Independently re-derived the "first wins" claim from first principles
rather than trusting the doc comment: wrote a 6-line scratch program
exercising `Vec::sort_by` + `Vec::dedup_by` with the exact closure shape used
in `finish` (`sort_by(|a,b| a.path.cmp(&b.path))` then
`dedup_by(|a,b| a.path == b.path)`) on `[("a",1),("a",2),("b",3)]`; it
produces `[("a",1),("b",3)]`, confirming `dedup_by` really does keep the
first of a run in this position (the docs' phrasing invites an off-by-one
misreading given the reversed-argument-order caveat). `add_file` after
`finish`: prevented at compile time — `finish(mut self)` consumes the
builder, so this is Rust's ownership system doing exactly what a type-state
`SortedFiles` wrapper would do, for free, matching the README's stated
rationale for not building one. Empty builder `finish()`: sorts/dedups an
empty `Vec`, loop body never runs, returns `WorkspaceIndex::default()` — no
panic, consistent with `an_empty_workspace_answers_nothing_and_panics_nowhere`
already covering `WorkspaceIndex::build([])` through the same path.
**Cross-feature interaction sweep — verified clean, and structurally so
rather than by accident.** `symbols.rs`, `lens.rs`, `type_hierarchy.rs` all
read from `ws.index()` directly; `rename.rs` reads from `ws.sources()`,
which is `collect_sources(...).texts`, the exact same `source_files()` ladder
`rebuild_index` uses. There is one scope-aware code path, not one per
feature, so "workspace/symbol, codeLens, typeHierarchy and rename all answer
in-scope only" is a structural fact, not a per-feature promise that could
drift. `workspace/diagnostic` (`server.rs:988` `workspace_report`) iterates
`self.workspace.open_uris()` only — confirmed independent of the index
scope entirely, exactly the "unaffected" claim. The cap composes with scope
by construction too: `collect_sources` applies `max_file_size` to
`scope.files`, which is already the scope-filtered list — no special-casing
needed, none found.
**Migration path.** Rather than diff against a `git stash` baseline binary,
verified the stronger claim algebraically: `default_files()`'s
`walks_the_workspace()` branch calls `self.walked_files(&self.roots)`, and
`walked_files(dirs: &[PathBuf])`'s body is byte-identical to the pre-round
`walked_files(&self)`'s body with `&self.roots` substituted for `dirs` at
every use — confirmed by re-reading the diff hunk line by line. So
`scope: "workspace"` is not merely equal in practice to the pre-round
default, it is the same function called with the same argument, which is a
stronger guarantee than a fixture comparison could give. `from_section`
delegates to `from_payload` with zero new code (`settings.rs:208-210`), so
both settings doors carrying the two new keys is confirmed structurally.
**Own-shapes probes (C), all via temporary tests, all reverted:**
- Rapid `didOpen` across 10 distinct folders: generation increases by
exactly 20 (2 per widening open), completes in ~0.02s — no quadratic
blowup at this scale. `opened_dirs.sort()` runs on every `set_document`
and `scope_dirs()` sorts+dedups again on every call (twice per `didOpen`),
which is O(n log n) per open and O(n² log n) over a session — fine at
realistic folder counts, worth knowing if a future report cites hundreds
of folders in one session.
- Lowering `scopeDepth` mid-session (1 → 0) via `set_client_settings`:
**does narrow the index on the next rebuild**, unlike closing a buffer.
This is correct and is the right answer (a settings change is a
deliberate user action, not the same "never take away an answer" case
`didClose` is), but **no permanent test pins it** and the README's
Assumptions section states "the scope only ever grows" without
distinguishing the open/close axis (grows-only) from the settings axis
(moves either way). Recommend a test plus a clarifying sentence.
- A filelist appearing mid-session (settings push) while folder scope was
active: flips the ladder to rung 1 immediately on the next rebuild
(`folder_scoped()` re-checks `filelist_path()` fresh every call, and
`set_client_settings`'s rescan condition already includes `filelist`
changes). Correct, and covered indirectly by the existing rescan test,
but there is no test that also checks the *index content* actually
changes to the filelist's files rather than just triggering a rescan —
probed with a temporary test, passed.
**CLAUDE.md compliance.** `verify.rs` untouched (no diff, confirmed by
`git diff --name-only`). No new `unwrap()`/`expect()`/`panic!` outside
`#[cfg(test)]` modules in the round's diff (grepped the four core files'
diffs for all three patterns; every hit is inside `mod tests`). Doc comments
present on every new public item (`IndexScope`, `ClientSettings::index_scope`
/`index_scope_depth`, `Workspace::scope_dirs`). `has_roots()` confirmed
genuinely `#[cfg(test)]`-only — grepped every call site in the crate, all
seven are inside `#[test]` functions. README sections present exactly once.
`TODO.md`'s M1 annotation accurately describes the new default and points at
this feature's README. Corpus tests still skip-guarded (`if !corpus.exists()
{ return; }` pattern unchanged, only their `open_roots` calls swapped).
**One item beyond the brief, informational only:** `editors/vscode/package.json`'s
`lucisv.index.scope` description says the pre-round behavior is "as lucisv
did before 0.11" — a forward guess at the next release number. This round
makes no version bump (confirmed: `Cargo.toml` and `package.json` both still
say `0.10.2`). Not wrong today, but it is a claim about a future version
number sitting in a shipped-looking description; worth a quick check by
whoever cuts the next release that it lands on 0.11 and not, say, 0.10.3 or
0.12.
**Not touched:** `docs/site/` (per instructions), no commit, no push
attempted (remote noted as flaky).
**Verdict: committable as-is**, modulo the dev's call on the one MEDIUM
finding (the vacuous `a_folder_added_twice_across_two_events_is_absent_after_one_removal`
assertion — a real but narrow test-coverage gap, not a product bug: nothing
about `change_roots`'s actual dedup/removal behavior is broken, only that
one test no longer demonstrates it). The two LOW-MEDIUM missing-permanent-test
items (out-of-root buffer under folder scope; depth-narrows-on-settings-change)
and the stale-comment LOW items are follow-up hygiene, not blockers — every
behavior they probe was independently verified correct by hand in this
session.
## Review
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
(2217 workspace tests, 0 failed), clean. The round delivers the owner's
model exactly and the two structural decisions are right: scope grows
only along the open axis (recomputing from the open set would take
working answers away on unrelated saves), and the builder hardening
makes the open-files-first ordering provably a reporting nicety — QA
independently re-derived the dedup-keeps-first-copy claim and confirmed
misuse-after-finish is prevented by ownership, which is the cheapest
kind of enforcement there is. The migration path being the same
function rather than an equal-output one is the strongest form of the
"workspace restores today" promise.
Lead actions on QA's findings before commit: the vacuous
folder-add/remove test now runs whole-workspace scope with a
present-while-added assertion restored (the MEDIUM); the big-buffer
cap test's premise is the cap's doing again; the stale rung comments
and the forward-guessed version string in the setting description are
corrected. The behaviors QA verified by hand but left unpinned
(depth-narrowing on a settings change, a mid-session filelist flipping
the ladder, an outside-root buffer on the folder rung) are accepted on
that verification and assigned to round 19's brief as permanent-test
obligations — its dev works in these exact files next. The
gitignore-below-root delta stays filed against lucisv_core. Accepted
as shipped.
+683
View File
@@ -0,0 +1,683 @@
# indexing-ux
## Goal
Three things a user of a *large* workspace has been asking the index for, all
of them about knowing and controlling what the scan is doing. **(1) A per-file
size cap** — `lucisv.index.maxFileSize`, 1 MiB by default: a Verilog file
bigger than a mebibyte is almost always a generated netlist or a dumped trace,
and indexing one costs minutes and answers nothing anybody asked. **(2) A
counting progress bar** — the `$/progress` bar that `work-done-progress` put up
was deliberately indeterminate, because `rebuild_index` was one opaque call;
this round makes the build observable per file, so the bar says `137/860
core_ibex_env.sv` and carries a real percentage. **(3) Per-file status in the
editor's output channel** — `lucisv.index.logFiles`, on by default: one
`window/logMessage` naming each file as it is parsed, plus a line for each file
the cap skipped, so "why is this symbol missing" and "why is this scan slow"
are answerable without a debugger. All three settings ride both settings doors
(push and pull) for free, because `settings.rs` is the one parser for both.
## Assumptions
- **The cap's blast radius is every `sources()` consumer, not just the
index** (QA log, 2026-08-27, lead-expanded): a capped file is invisible to
the workspace index, the hierarchy census (code-lens counts,
incomingCalls), type-hierarchy subtypes, cross-file navigation, rename's
collection sweep, and willRenameFiles' include rewriting. This is the one
coherent reading — "which files exist as far as this server is concerned"
— and nothing dangles, because the file is equally absent from every
layer. The honesty gap QA proved: a rename that would have touched a
capped file leaves its text stale on disk with no warning. Follow-up
filed (see the task the lead spawned): sweeps that WRITE should say when
the cap hid files from them.
- **The cap applies to walked files only; an open buffer is always indexed in
full.** The user opened it deliberately, and an editor that refused to
understand the file on screen because of a size setting would be absurd.
`collect_sources` reads the scope's files (capped) and *then* folds every
open buffer in over the top (uncapped) — the same override that has always
made a buffer beat disk.
**Amended 2026-08-27 by large-file-mode, and this is the one exception:** a
buffer over `lucisv.largeFile.threshold` (4 MiB by default) was never lexed
or parsed at all, so it contributes *nothing* to the index — and it takes
the disk copy of its own path out with it, rather than leaving the index
describing bytes the buffer no longer has. The two settings do not overlap
in intent: this one is about files nobody asked for, that one is about the
file on screen. The interaction table is in
`docs/features/large-file-mode/README.md`.
- **The cap is enforced with `fs::metadata` before the read.** The whole
saving is that a 200 MB netlist is never read into memory; a cap applied
after `read_to_string` would be a cap that costs what it saves. A file whose
metadata cannot be read is not skipped — it simply fails the read, as it
always did.
- **`0` means no cap, and must be exactly today's behaviour.** Pinned against
the real corpus: the index built with the default cap and the index built
with `maxFileSize: 0` are the same files in the same order with the same
counts (`the_default_cap_changes_nothing_about_the_real_corpus`). It is
true today because the largest file in `corpus/` is 94 KB — eleven times
under the cap, and **zero** corpus files exceed 1 MiB — and that test is
what notices if a future corpus or a future default changes it.
- **A wrong-typed cap falls back to 1 MiB, not to 0.** Every other setting in
`settings.rs` drops a bad value and goes silent; here "silent" has to mean
the shipped default, because reading junk as `0` would turn the cap *off*,
which is the failure the setting exists to prevent.
- **The cap is a *server indexing* cap and nothing else.** It is not pushed
into `lucisv_core`'s walk and not into the CLI's formatting path: `lucisv
format` on a 4 MB file must still format it, and a `lucisv.toml` has no
key for this. It lives in `Workspace::collect_sources`, which is the one
place the server decides which files exist.
- **…which means a refactoring sees the cap too.** `Workspace::sources()` —
what a workspace rename and `find_references` read — goes through the same
`collect_sources`. That is the consistent answer rather than an oversight: a
file that is not in the index is not a file this server rewrites. Stated
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 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.
- **`logFiles` defaults to on.** The owner asked for it, and the channel it
lands in is hidden until somebody opens it — `MessageType::LOG` goes through
`vscode-languageclient`'s `default:` branch straight to
`outputChannel.appendLine`, with no popup, no channel reveal and no trace
gate (read out of `node_modules/vscode-languageclient/lib/common/client.js`,
not assumed). A user who minds turns it off.
- **The startup scan runs at the defaults, because settings arrive after it.**
Both doors deliver settings only once `initialized` has been seen, so the
first index build always uses the 1 MiB cap and always logs its files, even
for a user who set neither. A differing cap then costs one extra rescan when
it lands — the same one `lucisv.exclude` has always cost
(`docs/features/folders-and-config/README.md`) — and a `logFiles: false`
takes effect from the second rescan onwards. This is visible in the
measurements below, where the "off" rows still carry the startup scan's 860
lines.
- **The skip *count* survives with the log off.** The skip lines are gated by
`logFiles` like every other per-file line, but the progress `end` message
becomes `"N files indexed, M skipped"` whenever `M > 0`, whatever the log
setting says. A user who silenced the log should still learn that part of
their workspace is not in the index.
- **Changing the cap rescans; changing the log setting does not.**
`max_file_size` changes *which files exist* as far as this server is
concerned, exactly as `exclude` and `filelist` do, so it joins them in
`set_client_settings`'s change test. `log_files` changes only how loudly the
next rescan narrates itself.
- **The completion tables and the include graph are outside the bar's count.**
They are built from the same list after the index, and cost a small fraction
of the parse. A bar that reached 100% and then sat there would be worse than
one that ends.
## Handshakes
### `vlog_semantic` — one addition, `build` redefined over it
`WorkspaceIndex::build` was one opaque call, so nothing outside the crate
could see a rebuild advance. It is now the loop over two new public items,
and its own signature and behaviour are unchanged:
```rust
pub fn index_order<'a>(files: impl IntoIterator<Item = (PathBuf, &'a str)>)
-> Vec<(PathBuf, &'a str)>; // sorted by path, one entry per path
pub struct IndexBuilder; // new() / add_file(path, src) / finish()
pub fn build<'a>(files: …) -> WorkspaceIndex {
let mut builder = IndexBuilder::new();
for (path, src) in index_order(files) { builder.add_file(path, src); }
builder.finish()
}
```
- **Why the builder rather than a callback parameter.** A callback would have
put a `&mut dyn FnMut` in a crate whose whole documented character is
"pure: the same inputs always give the same index". The builder adds no
parameter to anything and no closure to any signature; the caller that wants
to watch simply runs the loop itself.
- **Why `index_order` is public alongside it.** The builder hands out
`FileId`s in call order, and *both* the file ids and the disambiguation
order of a name declared twice are the path order `build` used to establish
privately. Exporting the ordering rule is what keeps a watched build and a
plain `build` the same index — and the server needs the list's length before
the first parse anyway, for the progress denominator. It is the honest
alternative to a comment telling callers to sort.
**Superseded in part (index-scope, 2026-08-27):** ~~the builder hands out
`FileId`s in call order~~ — it sorts inside `finish` now, so feeding it
`index_order`'s list is no longer required for correctness. `index_order`
stays public and unchanged for the denominator, and `build` still calls it so
a duplicate path is not parsed twice.
- **Proof of equivalence: every existing `vlog_semantic` test is unchanged**
and every one of them goes through `build`. One new test
(`the_incremental_builder_is_what_build_is_made_of`) drives the builder path
directly and asserts the same `files()`, the same `counts()`, the same
winning `Def` for a path handed over twice.
- **Noted, not done:** `vlog_refactor::rename::Scope::build` re-derives the
same sort-and-dedup by hand, with a comment saying so
(`crates/vlog_refactor/src/rename.rs:148`). It could now call `index_order`.
Out of this round's scope; filed here.
### `lucisv_server::state`
- `Workspace::rebuild_index_with(&mut dyn FnMut(IndexEvent))` and
`open_roots_with(roots, …)` are the watched forms; `rebuild_index()` and
`open_roots()` keep their exact old signatures and behaviour as the
unwatched forms. `server.rs` always watches, so the unwatched pair is now
reachable from tests alone and is `#[cfg(test)]` — several dozen call sites
across the crate, none of which has an opinion about progress.
- **Amended (incremental-index, 2026-08-27):** a rescan triggered by exactly
one file the index already holds does not go through `rebuild_index_with` at
all — it is `Workspace::update_one`, which reports no events, puts no bar up
and writes no log lines, because one parse is not a scan to narrate. Every
whole rescan is unchanged. The cap still applies, through the same
`oversize` test, and a file that grew past it leaves the index on the
incremental path too.
- `pub enum IndexEvent<'a> { Parsing { done, total, path }, Skipped { path,
size, cap } }`. Numbers and paths only: this module speaks no protocol, and
the wording of every message stays in `server.rs`.
**Amended (index-persistence, 2026-08-27):** a third variant, `Cached {
done, total, path }` — the same three numbers, for a file the persistent
index cache answered for instead of a parse. A new variant rather than a
flag on `Parsing`, so that every consumer is asked by the compiler what it
wants to say about a file that was not parsed.
- `ClientSettings::max_file_size` is read in `collect_sources`; nothing else
in `state.rs` changed.
### `lucisv_server::settings`
- Two new fields, `max_file_size: u64` and `log_files: bool`, parsed from
`lucisv.index.maxFileSize` / `lucisv.index.logFiles`. VS Code nests a dotted
setting id under each segment, so the section arrives as
`{"index": {"maxFileSize": …}}`; an `index` that is missing, `null`, or not
an object leaves both at their defaults.
- **`ClientSettings`'s `Default` is now hand-written.** Two of the fields do
not default to silence (1 MiB, and the log on), which a derive cannot say.
Every other field is its type's zero, exactly as the derive produced, so
every `..Default::default()` in the crate keeps meaning what it meant.
- `DEFAULT_MAX_FILE_SIZE` is public so the tests and the docs name one number.
### `lucisv_server::server`
- `IndexWatch` turns `IndexEvent`s into a `$/progress` report and a
`window/logMessage`, and counts the skips. It holds `&Connection` rather
than `&Server`, because the workspace is borrowed mutably for the whole of
the rebuild it is watching; `Server::new` and `reindex` therefore destructure
`self` into its `connection` and `workspace` fields around the call. Same
value, same operations, same order.
- `Server::notify` and `Server::progress` now delegate to free `notify_on` /
`progress_on` functions taking a `&Connection` — one implementation, two
callers, no duplicated send.
- `end_indexing` takes the skip count and says `"N files indexed, M skipped"`
when it is non-zero.
**Amended (index-persistence, 2026-08-27):** it takes the *cached* count as
well and names it first — `"860 files indexed, 858 from cache, 2 skipped"` —
because a scan that finished suspiciously fast should say why. Same rule as
the skip count: the number is in the end message whether or not the per-file
log is on. `IndexWatch` also grows an arm for `IndexEvent::Cached`, whose log
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.
- `begin` still carries **no** percentage: the first honest one is the first
file's.
### `editors/vscode`
- Two new `contributes.configuration` properties. No `extension.js` change:
`synchronize: { configurationSection: 'lucisv' }` already pushes the whole
section including the nested `index` object, and `new LanguageClient('lucisv',
…)` already owns an output channel that `vscode-languageclient` appends every
`MessageType::LOG` message to verbatim.
- `smoke.js` sends `capabilities: {}` and no `index` section, so it takes the
no-bar path with the log at its default; it passes untouched.
## Cost, measured
Release build, this Mac, 860-file `corpus/`, min of three runs of a session
that does two full scans (startup + one save-triggered rescan):
| progress | logFiles | wall | stdout | log lines | `report`s |
|---|---|---|---|---|---|
| off | off* | 668.8 ms | 1.16 MB | 860 | 0 |
| off | on | 670.9 ms | 1.34 MB | 1720 | 0 |
| on | off* | 687.0 ms | 1.50 MB | 860 | 1720 |
| on | on | 704.9 ms | 1.69 MB | 1720 | 1720 |
\* the settings push lands *after* the startup scan, so the "off" rows still
carry the startup scan's 860 lines; only the second scan is quiet. That is
what makes the rows subtract cleanly.
So, **per 860-file rescan**: 860 log lines ≈ 173 KB (≈ 201 B each, mostly
absolute path), 860 reports ≈ 160 KB (≈ 186 B each). Both features on cost
**≈ 18 ms on a ~690 ms two-scan session — about 2.6%**, and about 333 KB of
extra stdout per rescan.
**Stated honestly: at 10,000 files the log is the part that gets ugly.** The
reports are throttled to at most 1000 per rescan whatever the size, so they
stay at ~190 KB; the log is not, so it would be ~2 MB of JSON on every save.
That is a real number and a real cost, and the follow-up is batching (one
`logMessage` per N files, or per directory) — **filed, not invented here**,
because a batching scheme designed without a user complaining about it would
be guessing at the wrong granularity. The escape hatch exists today: turn
`lucisv.index.logFiles` off.
## The throttle rule
```rust
const MAX_REPORTS: usize = 1000;
fn reports(done: usize, total: usize) -> bool {
let step = total.div_ceil(MAX_REPORTS).max(1);
(done + 1).is_multiple_of(step) || done + 1 == total
}
```
Up to 1000 files, `step` is 1 and every file reports. Past that, every
⌈total/1000⌉-th file reports — at most 1000 per rescan, so the bar still moves
in steps of a tenth of a percent, which is under a pixel. The `|| done + 1 ==
total` is the reason 10,001 files do not leave the bar one file short of the
work it finished. Both regimes are pinned: the rule itself exhaustively for
nine sizes, and a real 1100-file workspace end to end.
## Status / TODO
- [x] `lucisv.index.maxFileSize`, bytes, default 1 MiB, `0` disables
- [x] Enforced on `fs::metadata` before the read, walked files only
- [x] Open buffers exempt, and pinned as such
- [x] A cap change rescans; `logFiles`, `lineLength`, `indent`,
`formatOnSave`, `inlineTemplates` still do not
- [x] `$/progress` `report`s carrying `n/total file.sv` and a real percentage
- [x] Throttled to ≤ 1000 reports per rescan, last file always reported
- [x] The same reports on the startup build and on every reindex trigger
- [x] `window/logMessage` (`MessageType::LOG`) per file, plus skip lines
- [x] Both gated by `lucisv.index.logFiles`, default on; skip **count**
survives with the log off, in the `end` message
- [x] `vlog_semantic::IndexBuilder` + `index_order`, with `build` redefined as
the loop over them and every existing test unchanged
— ~~and the builder's ordering contract carried by a doc comment~~
**superseded (index-scope, 2026-08-27): `finish` sorts, so the contract
is the code**
- [x] `package.json` declares both settings, with the 0-disables semantics and
the open-buffer exemption in the descriptions
- [x] 21 new tests; 7 existing progress tests updated for the reports
- [ ] **Not done, deliberately:** no batching of the log lines. See "Cost,
measured" — the number is stated, the follow-up is named, and the
granularity is not guessed at.
- [ ] **Not done, deliberately:** no cap in `lucisv_core`'s walk or in the
CLI. `lucisv format` on a huge file must still format it.
- [ ] **Not done, deliberately:** no `lucisv.toml` key for the cap. It is an
editor-session resource setting, not a project style decision — the same
reason `serverPath` has no config key.
- [ ] **Filed, not done:** `vlog_refactor::rename::Scope::build` could call
`index_order` instead of re-deriving the sort/dedup.
## Work log
### 2026-08-27 — dev agent (indexing UX: cap, counting bar, per-file log)
- **`vlog_semantic`: builder, not callback — and the reason is `FileId`.**
The brief allowed either and asked for a justification. The builder shape
did *not* fight the code, but it did expose an invariant: `build` sorted and
deduped privately, and both the file ids and a duplicate name's
disambiguation order depend on that. An `IndexBuilder` alone would have
pushed "remember to sort" onto every caller as a comment. Exporting
`index_order` beside it turns that into a call, and the server needed the
ordered list's *length* before parsing anyway (the progress denominator), so
the second public item has a real second use rather than being an
abstraction for a user that does not exist. `build` is now three lines over
the two of them; every existing `vlog_semantic` test is byte-identical and
green, which is the equivalence proof.
- **The cap went in `collect_sources`, one `fs::metadata` ahead of the read.**
That is the one place the walked list becomes text, so it is the cheapest
point and the only one where "never read the netlist" is true. Consequence
found and documented rather than papered over: `Workspace::sources()` — the
refactoring path — shares that function, so the cap reaches a workspace
rename too. That is the consistent reading of "which files exist as far as
this server is concerned", and it is now written down in Assumptions.
- **`ClientSettings::default()` is hand-written now.** Two settings whose
default is not silence (1 MiB, log on) cannot be derived, and pushing them
into `Option`s would have made every use site re-decide what unset means.
Every other field keeps the derive's value, so no existing
`..Default::default()` changed meaning — the whole suite passing unchanged
is the check.
- **A wrong-typed `maxFileSize` falls back to the default, not to 0.** This is
the one place this module's "drop it and go silent" rule needed a direction:
silence here is 1 MiB, because reading junk as 0 would silently un-cap.
- **Nested keys, because VS Code nests them.** `lucisv.index.maxFileSize`
arrives as `{"index": {"maxFileSize": …}}` through both doors; the parser
reads `lucisv.get("index")` once and a non-object `index` is the same as no
`index`. Pinned through `from_section` too, since these are the first nested
keys to go through the pull door.
- **`IndexWatch` holds `&Connection`, not `&Server`.** The workspace is
borrowed mutably for the whole rebuild, so `Server::new` and `reindex`
destructure `self` and hand the watcher the connection field. `notify` and
`progress` were re-pointed at free `notify_on`/`progress_on` functions so
there is still exactly one place a notification is sent.
- **The report message names the file, the log line names the path.** The bar
is a few dozen characters of status bar; the path belongs in the channel
that has room for it.
- **`human_size`, not a fixed MiB.** The first draft printed
`skipped (0.0 MiB > 0.0 MiB cap)` for a 4 KiB file under a 1 KiB cap — the
e2e test caught it. The cap is settable to anything, so the unit adapts:
bytes, KiB, MiB.
- **Seven existing tests were updated, all of them pinning "no report".**
That assumption is exactly what this round removes, so each one gained its
reports rather than being relaxed:
`the_startup_index_build_runs_under_the_first_bar`,
`a_save_puts_a_bar_up_and_takes_it_down_again`,
`the_bar_is_down_before_the_republish`,
`every_rescan_path_gets_its_own_bar_and_its_own_token` (its "no invented
percentages" line became "every report is inside its own bar", which is the
stronger property),
`the_refresh_rides_after_the_indexing_bar_comes_down`,
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
`one_folder_notification_is_one_rescan_with_one_bar_and_one_generation`, plus
the e2e `indexing_reports_its_progress_over_the_wire`.
- **One surprise worth recording:** `package small;` does not index —
`small` is a SystemVerilog keyword (charge strength). Two new fixtures were
renamed to `small_pkg` after that cost ten minutes.
- Files touched: `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/src/lib.rs`, `crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/settings.rs`, `crates/lucisv_server/src/state.rs`,
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/tests/e2e.rs`,
`editors/vscode/package.json`, `TODO.md`,
`docs/features/work-done-progress/README.md`,
`docs/features/lucisv-server/README.md`, this README. No new dependency, no
version bump, no `docs/site/`, no commits.
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
--all-targets`: zero warnings. `cargo test --workspace`: **2197 passed, 0
failed** (2176 on `HEAD` — 21 new). `cargo test -p vlog_formatter`: green.
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
`smoke: OK`. Corpus: 0 of 860 files exceed 1 MiB (largest, `picorv32.v`, is
94 KB), and the default-cap index is identical to the uncapped one — pinned
by a test, not just measured.
The 21 tests, and what each is for:
| test | pins |
|---|---|
| `the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off` (settings) | the default, the empty sub-section, `0`, and no upper bound |
| `a_wrong_typed_size_cap_leaves_the_default_standing` (settings) | six wrong types, and four wrong shapes of `index` itself |
| `the_file_log_is_on_until_a_client_turns_it_off` (settings) | absence, both booleans, five wrong types |
| `the_index_settings_come_through_the_pull_door_too` (settings) | the nesting survives `from_section`, one set of rules |
| `a_walked_file_over_the_cap_is_left_out_of_the_index` (state) | the cap itself |
| `the_default_cap_is_a_mebibyte_and_zero_turns_it_off` (state) | a real >1 MiB file against the shipped default, then `0` |
| `an_open_buffer_is_indexed_however_big_the_file_is` (state) | the exemption |
| `every_skipped_file_is_reported_with_its_size_and_the_cap` (state) | the `Skipped` event's path, size and cap |
| `the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first` (state) | the denominator is post-exclude, post-cap; events are in index order |
| `the_default_cap_changes_nothing_about_the_real_corpus` (state) | cap-on == cap-off over `corpus/`, files and counts |
| `the_bar_counts_the_files_as_it_goes` (server) | `1/2 a.sv` at 50%, `2/2 b.sv` at 100% |
| `the_reports_thin_out_when_the_workspace_is_huge` (server) | 1100 real files: ≤1000 reports, monotonic, last is `1100/1100` |
| `the_report_schedule_never_floods_and_never_stops_short` (server) | the rule at 1, 2, 999, 1000, 1001, 1999, 2000, 12345, 40000 |
| `the_end_message_names_what_the_cap_skipped` (server) | `"1 file indexed, 1 skipped"`, with the log **off** |
| `a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not` (server) | both halves of the cap through the real dispatch |
| `every_indexed_file_is_named_in_the_log_and_so_is_every_skip` (server) | one line per file, `MessageType::LOG`, the skip line's sizes |
| `the_file_log_goes_quiet_when_the_setting_is_off` (server) | not one line, skips included |
| `the_file_log_does_not_wait_for_a_progress_bar` (server) | the log is not gated on the progress capability |
| `a_new_cap_rescans_and_a_new_log_setting_does_not` (server) | the change detection, both directions, through `didChangeConfiguration` |
| `the_incremental_builder_is_what_build_is_made_of` (vlog_semantic) | builder == `build`: files, ids, counts, duplicate-path winner |
| `the_size_cap_and_the_file_log_work_over_the_wire` (e2e) | the real binary: nested setting → rescan → symbol gone, log lines, report and end message decoded off the wire |
## QA log
### 2026-08-27 — QA agent (one round: cap, counting bar, per-file log)
**Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
--workspace`: zero warnings. `cargo test --workspace`: **2197 passed, 0
failed** (matches the dev's number exactly; one incidental failure of an
unrelated pre-existing timing-budget test,
`lens::tests::code_lenses_for_a_whole_file_cost_about_one_workspace_walk`,
during a run made while several other `cargo`/release builds were competing
for CPU in the background — reran clean in isolation twice, not a regression,
not touched by this round). `cargo test -p vlog_formatter`: 114 passed,
`verify.rs` untouched (confirmed via `git status`/`git diff` — it never
appears). `node smoke.js target/debug/lucisv-server`: OK.
All temporary attack code below was added directly to the tracked files
listed, run, and then removed with a diff-identical revert verified against a
saved copy of the original `git diff` before continuing — no attack code
remains in the working tree.
**1. FileId/ordering invariant — VERDICT: safe today, latent risk in the
abstraction.** `WorkspaceIndex::build` and `Workspace::rebuild_index_with`
(the only two callers of `IndexBuilder::add_file` in the tree) both feed it
`index_order`'s list, in order, so the two are provably identical — confirmed
independently by feeding a workspace with a case/depth-nontrivial duplicate
module name (`z_late.sv` / `a_early.sv`, both declaring `dup`) through `build`
and through a manual `index_order` + `IndexBuilder` loop: same `FileId`s, same
disambiguation winner (`a_early.sv` first, both ways).
But **Closed by index-scope, 2026-08-27** (see `docs/features/index-scope/README.md`):
`IndexBuilder::add_file` now keeps its file's declarations to itself and
`finish` sorts them by path before handing out any `FileId`, so no insertion
order can reach the result. QA's construction below is a permanent test,
`no_insertion_order_can_change_what_the_builder_produces`. The finding as
filed, kept legible:
`IndexBuilder` itself enforces nothing — it is a dumb accumulator, and the
ordering guarantee is carried entirely by the doc comment ("Feed it
`index_order`'s list"), not the type system. Direct attack, temporarily added
to `crates/vlog_semantic/tests/workspace.rs` and run:
```rust
let files = [
("z_late.sv", "module dup (input a); endmodule\n"),
("a_early.sv", "module dup (input b); endmodule\n"),
];
let mut wrong = IndexBuilder::new();
for (p, s) in files { wrong.add_file(PathBuf::from(p), s); } // raw order, NOT index_order
let wrong = wrong.finish();
let right = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
assert_eq!(wrong.files(), right.files()); // FAILS
```
Result: `wrong.files() == ["z_late.sv", "a_early.sv"]` vs.
`right.files() == ["a_early.sv", "z_late.sv"]` — `FileId(0)` and the `dup`
disambiguation winner both flip. So insertion order **does** leak into the
result the moment a caller bypasses `index_order`, exactly as the brief
warned. Severity: **MEDIUM, not HIGH** — both current production call sites
are verified correct, so this is not a live bug in this round's shipped code,
but it is a real footgun for the one thing the README itself flags as
"filed, not done" (`vlog_refactor::rename::Scope::build` migrating to
`IndexBuilder` later). Suggest, as a non-blocking follow-up: either have
`IndexBuilder::add_file` debug-assert paths arrive in non-decreasing order,
or fold `index_order` into `IndexBuilder` itself (e.g. buffer-then-sort on
`finish()`) so the invariant can't be bypassed by a future caller who didn't
read the doc comment.
**2. The cap's blast radius through `sources()` — documentation gap, coherent
behavior.** `Workspace::sources()` is also consumed by
`crates/lucisv_server/src/hierarchy.rs:90` (codeLens counts /
`callers_of_each`), `ports.rs:61,87`, `nav.rs:132` (`find_references`), and
`type_hierarchy.rs:112` (subtypes) — not just `rename.rs`/`file_ops.rs`. The
indexing-ux README's Assumptions section and the `lucisv-server` README's new
paragraph name only the rename/refactoring reach ("a refactoring sees the cap
too"); the existing per-endpoint table rows for `callHierarchy/incomingCalls`
and `typeHierarchy/subtypes` (`docs/features/lucisv-server/README.md` lines
46 and 50) are untouched by this diff and say nothing about the cap, even
though those two consumers are exposed identically. The behavior itself is
coherent — a capped file is invisible everywhere consistently, nothing
dangles — but a future reader of those two table rows would not learn that a
netlist over the cap silently vanishes from an instantiation count or a
subtype list too.
Concretely reproduced the rename case as the sharpest instance (temporarily
added to `crates/lucisv_server/src/rename.rs`, run, reverted): a workspace
with `sub.sv` (declares `sub`), `top.sv` (open, instantiates `sub`), and a
4 KB `netlist.sv` over a 1 KiB cap that *also* instantiates `sub`. Renaming
`sub` to `child`:
```rust
let (edit, warnings) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames");
// changes.len() == 2 (sub.sv, top.sv) — netlist.sv is absent
// warnings == [] — nothing at all says netlist.sv exists or was skipped
```
So a rename leaves `netlist.sv` with a stale, now-broken reference to the old
name, **with zero warning anywhere in the rename response** — not in
`refactoring.warnings`, not in any diagnostic. The only place this is ever
surfaced is the output-panel skip line from whichever index build happened to
run earlier (`logFiles` on), which is decoupled in time from the specific
rename and easy to have scrolled past. Severity: **MEDIUM** — the "not
indexed → not rewritten" design is defensible and documented as intentional,
but the complete silence *at the point of the risky action* is a real UX gap.
Suggest as a follow-up: have `rename`/`find_references` check
`ws.sources()` against a cheap re-walk (or thread the skip list through) and
fold "N file(s) over the size cap may also reference this symbol" into
`refactoring.warnings` when the cap is non-zero.
**3. Cap edge semantics.**
- **Exact boundary, pinned by hand (dev's suite doesn't cover it):** a file of
exactly 1024 bytes against a 1024-byte cap is **not** skipped — `oversize`
is `size > cap`, so the cap is inclusive (`≤ cap` survives). Verified with a
temporary test in `state.rs` creating a file measured at exactly 1024 bytes
on disk and confirming it appears in the index under a 1024-byte cap.
Correct and sensible, just untested — worth a permanent test.
- **Metadata failure:** confirmed consistent with the documented behavior —
`oversize`'s `fs::metadata(path).ok()?` returns `None` on failure, so the
file is not reported as skipped; it falls through to
`fs::read_to_string`, which will also fail for the same reason, and the
file is silently absent from `texts` exactly as it always was pre-cap. No
regression, no new silent-failure mode.
- **Growing file mid-scan:** not a race, as claimed — `oversize` and the read
are back-to-back for one file within one scan.
- **Symlinks:** verified directly (a symlink `link.sv` → a 5053-byte
`target_big.sv`, plus a `symlink_metadata` comparison showing 13 bytes for
the link itself vs. 5053 via `fs::metadata`). `oversize` uses `fs::metadata`
(follows the link), and so does the subsequent `fs::read_to_string` — the
cap is measured against the same bytes that would be read, not the
symlink's own size. Coherent, no bug.
**4. Settings parsing.**
- Nested `{"index": {"maxFileSize": …}}` and the wrong-type→default fallback:
verified via the dev's own tests, both green.
- **Flat `{"index.maxFileSize": …}` shape (untested by the dev's suite):**
confirmed by a temporary test that `lucisv.get("index")` looks for a
literal `"index"` key, so a flattened dotted key is invisible to the parser
and silently resolves to the default (1 MiB) — same as `index` being
absent entirely. Coherent with the module's "drop it and go silent"
philosophy, but this specific shape isn't pinned by a test, unlike every
other edge case in this settings addition. Low-severity gap, easy add.
- Pull-door parity (`from_section`): verified via the dev's own test, green.
**5. Throttle honesty.** The dev's own
`the_report_schedule_never_floods_and_never_stops_short` already covers the
rule exhaustively at 1, 2, 999, 1000, 1001, 1999, 2000, 12345, 40000, and
`the_reports_thin_out_when_the_workspace_is_huge` exercises it against 1100
real files end to end. Both ran green in the full-suite run; no gaps found
worth a separate synthesis.
**6. Logging gate.** Verified via the dev's own tests
(`the_file_log_goes_quiet_when_the_setting_is_off`,
`every_indexed_file_is_named_in_the_log_and_so_is_every_skip` asserting
`MessageType::LOG` specifically — not `INFO` — and
`the_file_log_does_not_wait_for_a_progress_bar`). All green. No gaps found.
**7. The 8 updated tests.** Read every diff hunk. Seven of them
(`the_startup_index_build_runs_under_the_first_bar`,
`a_save_puts_a_bar_up_and_takes_it_down_again`,
`the_bar_is_down_before_the_republish`,
`the_refresh_rides_after_the_indexing_bar_comes_down`,
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
`one_folder_notification_is_one_rescan_with_one_bar_and_one_generation`, and
the e2e `indexing_reports_its_progress_over_the_wire`) only insert `"report"`
entries into an already-asserted ordering sequence — their original point
(bar goes up, comes down, in the right place relative to X) is intact.
The eighth, `every_rescan_path_gets_its_own_bar_and_its_own_token`, is the one
whose point *was* "no report is ever invented" — that assumption is exactly
what this round removes, and it is replaced with the strictly stronger "every
report belongs to a currently-open bar" check, under an explicit `// Superseded
this round:` comment. That is the correct way to retire an assumption per
CLAUDE.md's house style, and it is the one case that needed it.
**8. CLAUDE.md compliance.**
- No `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)]` in any touched
non-test code (`server.rs`, `settings.rs`, `state.rs`, `workspace.rs`,
`lib.rs`) — checked directly, clean.
- Every new `pub` item (`index_order`, `IndexBuilder` + its three methods,
`IndexEvent`, `open_roots_with`, `rebuild_index_with`) has a doc comment.
- The feature README has all seven required sections exactly once (plus two
extra informational sections, "Cost, measured" and "The throttle rule",
which CLAUDE.md doesn't forbid).
- The superseded-assumption annotations in `TODO.md`,
`docs/features/work-done-progress/README.md`, and
`docs/features/folders-and-config/README.md` all follow the existing house
style (`~~struck~~` + a dated "Superseded ... by ..." note that keeps the
original reasoning legible) consistently.
- `verify.rs` is untouched — confirmed absent from `git status` and `git
diff` entirely.
- The new corpus-gated tests (`the_default_cap_changes_nothing_about_the_real_corpus`
in `state.rs`) follow the `if !corpus.is_dir() { eprintln!("corpus/ not
checked out — skipping"); return; }` convention exactly as the pre-existing
corpus tests in `vlog_semantic` do.
**C. Beyond the list.**
- **`maxFileSize: 1`** (temporary test in `state.rs`): every walked file
skipped, index ends up with 0 files (not a panic, not an error), and an
opened buffer is still indexed in full afterward. Server stays functional
at the extreme.
- **`logFiles` toggled mid-session:** already covered by the dev's own
`the_end_message_names_what_the_cap_skipped` (toggles `logFiles` false in
the same session as a cap change) and `a_new_cap_rescans_and_a_new_log_setting_does_not`.
Both green; no gap found.
- **Overhead measurement, ~18 ms / 2.6% claim:** attempted an independent
spot-reproduction twice (a release/LTO build that did not finish in
reasonable time in this sandboxed environment, then a debug-mode custom
harness that hit a broken pipe in its own scratch code talking to the real
binary over a hand-rolled 860-file corpus session — a bug in the throwaway
harness, not reproduced against the dev's own passing corpus-based tests).
Not independently re-measured; **not verified numerically**. The mechanism
itself is architecturally sound for the claimed order of magnitude — one
extra `fs::metadata` call and one extra `window/logMessage`/`$/progress`
notification per file, both cheap, no additional passes over file content —
so I have no reason to doubt the figure, but I did not confirm it myself.
- **`human_size` rounding boundary — new finding, LOW-MEDIUM, cosmetic
only.** `human_size(1_048_575)` (one byte under 1 MiB) prints `"1024.0
KiB"` instead of switching to the MiB branch, because `1_048_575.0 / 1024.0
== 1023.999...` is `< MIB` so it takes the KiB arm, then rounds *up* to
`1024.0` at `{:.1}` precision. Same failure mode one level up:
`human_size(1_073_741_823)` (one byte under 1 GiB, which this function has
no branch for) prints `"1024.0 MiB"`. Verified directly:
```
1048575 -> 1024.0 KiB
1073741823 -> 1024.0 MiB
```
This is the same class of bug the e2e test already caught once (`"0.0 MiB >
0.0 MiB"`), just at the opposite (upper) rounding edge, and only reachable
today via a skip line whose size or cap happens to land in one of those
windows — cosmetic, no effect on cap enforcement or index correctness.
Worth a follow-up fix (e.g. bump the branch threshold down by half a unit,
or format then re-check which unit the rounded string actually names).
**Verdict: committable as-is.** No correctness regression, no invariant
violated, all four gates green, 2197/2197 tests passing. Two MEDIUM findings
(the `IndexBuilder` ordering footgun, and the silent rename-blast-radius gap)
are both documented-intentional-behavior-with-an-honesty-gap rather than bugs
in what shipped, and are appropriately deferred as dev follow-ups rather than
blockers. One LOW-MEDIUM new cosmetic finding (`human_size` rounding) and two
LOW test-coverage gaps (exact-boundary cap, flat settings key) are cheap to
add later and do not affect behavior today.
## Review
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
clean. The three features land the way the owner asked and the details
show the right instincts: junk cap values fall back to 1 MiB rather
than 0 (misparse must never un-cap), the denominator is the real work
list known before the first parse, the skip count outlives the log
toggle, and the vlog_semantic change follows the established
redefinition pattern with `index_order` exported so the FileId
ordering rule is a call, not a comment.
Rulings on QA's findings. The builder-ordering footgun (MEDIUM) is
real and correctly assessed as latent — both production callers funnel
through index_order, proven by QA's both-ways construction — and the
fix belongs to the next round, whose scope work is precisely the
future caller at risk: round 18's brief requires making the builder
order-insensitive or formally enforcing the contract, with QA's attack
as the acceptance test. The cap blast radius (MEDIUM) is accepted as
the one coherent reading — absent from every layer equally — and I
have expanded the Assumptions to name every consumer, with the
write-path warning gap (a rename silently leaving a capped file's text
stale) filed as a visible follow-up task rather than buried. The
human_size rounding bug (LOW) I fixed directly with the unit chosen by
what the rounded number reads as, plus the boundary test. The
unreproduced 18 ms overhead claim stands as the dev's measurement with
QA's non-verification noted — the mechanism is sound and the number is
not load-bearing. Accepted as shipped.
File diff suppressed because it is too large. Load diff
+124 -29
View File
@@ -25,15 +25,15 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it |
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md` |
| `textDocument/semanticTokens/full` | `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` |
| `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/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 |
| `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` |
| `textDocument/references` | `WorkspaceIndex::references_to`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port). Saved uses are declaration-to-occurrence postings built with the project index; open buffers overlay live semantics. No request-time project scan; returned spans are converted per touched file in one batch. See `docs/features/references-nav/README.md` |
| `textDocument/documentHighlight` | `pairs::analyze`, else `Semantics::references_of` | A scope keyword highlights its own closer; anything else highlights the symbol's occurrences in this file. Kind is always `Text`; neither answer means `null`, so the editor keeps its word highlighting. Same feature README |
| `textDocument/foldingRange` | `pairs::analyze` + comment trivia | One `Region` per matched scope pair, folded through the line *before* the closer so `end`/`endmodule` stays visible, plus one `Comment` per multi-line block comment. An unmatched opener folds nothing. Same feature README |
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
@@ -43,12 +43,12 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README |
| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` |
| `textDocument/prepareCallHierarchy` | `instantiations::{sites,declarations}`, `WorkspaceIndex::units` | The module under the cursor as a hierarchy node (`SymbolKind::Module`), from its own declaration or from any instantiation of it. Every other position answers `null`; an ambiguous name returns every declaration, as `definition` does. See `docs/features/hierarchy/README.md` |
| `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README |
| `callHierarchy/incomingCalls` | `WorkspaceIndex::instantiations_of` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. A **lookup in the index's instantiation-edge table** since 2026-08-27 (it walked every in-scope file before, 56 ms over the 860-file corpus); only the files that really do instantiate the name are read, to turn recorded spans into ranges. The census is as of the index — its last build or update, both of which fold every open buffer in. Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README |
| `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README |
| `textDocument/prepareTypeHierarchy` | the class walk over `Document.tree`, then `ExternalResolutions::definition_of` | The **class** under the cursor as a type hierarchy node (`SymbolKind::Class`), from its own declaration or from any use of its name (an `extends` base, a property's type, a method local's type). Every other position answers `null`; a name two files declare returns both, as `definition` does. Advertised by hand — `lsp-types` 0.97's `ServerCapabilities` has no `typeHierarchyProvider` field. See `docs/features/type-hierarchy/README.md` |
| `typeHierarchy/supertypes` | `ClassDecl::extends` + `ExternalResolutions::definition_of` | "What X extends": its base class, resolved by the same two layers F12 uses — in-file first, then the workspace overlay — asked at the **last byte** of the extends name, which is the tail of `pkg::base` and the whole of a bare `base`. A parameterized base resolves by its bare name; a base the workspace does not index (every UVM chain top) yields **no** item rather than a guess. Same feature README |
| `typeHierarchy/subtypes` | the class walk over `Workspace::sources` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. Walks the in-scope files — the index holds no inheritance edges — skipping any file whose text does not contain the name (55 ms over the 860-file corpus, 53 ms of it file I/O). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README |
| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same walk asked about every module in the file at once, so the two can never disagree. `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` |
| `typeHierarchy/subtypes` | `WorkspaceIndex::subclasses_of` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. A **lookup in the index's inheritance-edge table** since 2026-08-27 (it walked every in-scope file before, 55 ms over the corpus; 0.71 ms now). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README |
| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same edge table asked about every module in the file at once, so the two can never disagree (92 ms → 0.26 ms for a three-module file, 2026-08-27). `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` |
| `workspace/executeCommand` → `lucisv.showInstantiations` | `hierarchy::callers_of_each` | The code lens's own jump: `["module-name"]` in, every site as a `Location` out — one per site, file-then-position order. For a client that advertised `window.showDocument`, the server also pushes a `window/showDocument` for the **first** site, which is what makes the click navigate; LSP has no server-initiated peek-references, and this repo's extension declares no client-side command. A name with no sites answers `[]`; a missing or empty name is `RequestFailed`. Same feature README |
| `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README |
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
@@ -234,8 +234,9 @@ 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 |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist` (pushed **or** pulled) | full re-scan of the roots |
| 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
@@ -244,10 +245,83 @@ ranges, but a `didChange` still throws the whole `Document` away and builds a
new one — one reparse per notification, which is also the one generation bump
the pull-diagnostics `resultId` depends on.
**Open buffers override disk** in every index rebuild: the roots are walked,
**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
first: a **filelist** defines the scope exactly, as it always has; else
`lucisv.index.scope: "workspace"` walks every workspace folder, which is what
every session did before this round and is now opt-in; else — the default —
the scope is **the folders the open buffers live in**, each raised
`lucisv.index.scopeDepth` levels (0 by default, clamped so it never climbs out
of the workspace folder containing it) and walked with every filter the wide
walk applies. Opening a file in a folder the scope does not cover **widens the
scope and rebuilds**, on the same bar and the same generation bump every other
rescan gets; closing one narrows nothing, ever. The startup index is therefore
empty until the first `didOpen`, which is the whole saving on a large project.
**Stated plainly, because it is what a user notices:** every cross-file answer
in the table above is **scope-relative**. A definition, a `workspace/symbol`
hit, an `incomingCalls` census, a `subtypes` list, a references lookup or
a workspace rename covers the files in scope and no others — a symbol in a
folder the scope has not reached does not exist as far as this server is
concerned, exactly as one outside a filelist never did. Opening a file in that
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`.
**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
disagrees with a buffer the user is looking at.
disagrees with a buffer the user is looking at. The open buffers' own files are
also fed to the index builder **first**, so a long rescan's progress bar
completes them before anything else; the builder sorts by path internally, so
that ordering cannot change the index it produces.
**What a scan learned survives the session, since 2026-08-27**
(index-persistence). Every file a scan parses is written to a store — its
`FileFacts`, the whole of its contribution to the index, under the FNV-1a hash
of the bytes it was read from — and the next scan takes back every record
whose file still holds exactly those bytes instead of parsing it again. So
reopening a workspace, or reopening one whose first scan was interrupted, is a
rescan that costs the reads and not the parses: **181 ms warm against the
328 ms it cost cold** over the 860-file corpus in a release build, with the bar
saying `860 files indexed, 860 from cache` and the output log saying `cached:`
where it says `indexing:`. The store lives in
`initializationOptions.storagePath` (VS Code's per-workspace storage folder),
or wherever `lucisv.index.cachePath` says, or in this platform's cache
directory; `lucisv.index.persist: false` turns it off in both directions and
restores the pre-2026-08-27 behaviour exactly. **It is a performance artifact
and never a correctness input**: every record is verified against the file's
current content before it is used, and a stale, corrupt or foreign record
costs one parse and can change no answer. Rules, the record format and the
crash-safety argument: `docs/features/index-persistence/README.md`.
**A buffer over `lucisv.largeFile.threshold` (4 MiB by default) is never
analyzed at all, since 2026-08-27** (large-file-mode). `Workspace::set_document`
— the one place a `Document` is built — puts it on a fast path that indexes its
*lines* and stops: no lex, no parse, no semantics, no diagnostics, no index
entry. 41 ms for 100 MB, against the 930 ms 10 MB costs through the full
pipeline. Its `Document` holds the analysis of the **empty file**, so every
handler that reads the analysis answers empty without knowing the mode exists;
only the handlers that would read the **text** are gated, in one table in
`Server::large_file_answer`. What still works is colour — `semanticTokens/range`
lexes the requested window and nothing else — plus same-file `definition` and
`references` by one linear scan. `semanticTokens/full` is answered with an
*error*, which is the one shape that leaves VS Code's viewport provider
painting. A file on the fast path leaves the workspace index entirely, which is
the one exception to "an open buffer is never capped". The rules, the
approximations, the dispatch table and the measurements:
`docs/features/large-file-mode/README.md`.
**Walked files over `lucisv.index.maxFileSize` (1 MiB by default) are not read
at all** — the size is taken from `fs::metadata` before the read, so a
generated netlist costs one `stat` rather than minutes of parsing. The cap is
on the *walk* only: an open buffer is folded in above, uncapped, because the
user opened it deliberately. `0` disables the cap, and the skipped count is
named in the progress bar's `end` message. Since the whole cap lives in
`collect_sources`, `Workspace::sources()` sees it too, so a workspace rename
does not rewrite a file the index does not hold. Rules, corpus numbers and the
per-file `window/logMessage` that accompanies a rescan:
`docs/features/indexing-ux/README.md`.
**The staleness window, stated plainly.** The index is rebuilt on save, not on
change. Between editing file A and saving it, file B's cross-file answers
@@ -257,19 +331,24 @@ which the override above keeps current. Rebuilding on every keystroke would
re-parse the whole workspace per character; rebuilding on save is the cheapest
point where the answer is expected to change anyway. Measured cost of a
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
plus the file reads.
plus the file reads — **and about half that when the persistent index cache
answers for the files that have not changed** (index-persistence, below).
**Every rescan is visible since 2026-08-26**, for a client that advertised
`window.workDoneProgress`: the startup build and all three `reindex()` triggers
are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
**Every *whole* rescan is visible since 2026-08-26**, for a client that
advertised `window.workDoneProgress`: the startup build and every whole
`reindex()` trigger are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
begin/end pair on a fresh `lucisv-index-N` token, so a multi-second index on a
big filelist reads as work rather than as a hang. The `begin` does not wait for
the create's answer (the rescan blocks the loop immediately after), the answer
is ignored on the same path the watcher registrations' is, there is no
percentage and no intermediate report — the rescan is one opaque call — and the
`end` names the indexed file count. A client that did not advertise the
capability is sent nothing at all, which the spec requires. Rules and the
startup-legality argument: `docs/features/work-done-progress/README.md`.
capability is sent nothing at all, which the spec requires. **A rescan that
names exactly one file the index already holds puts no bar up** since
2026-08-27: it is one parse, sub-perceptual, and a bar that appears and
vanishes inside a frame is noise rather than progress
(`docs/features/incremental-index/README.md`). Rules and the startup-legality
argument: `docs/features/work-done-progress/README.md`.
**Changes made outside the editor close on the next notification, not on the
next save** (M9, `docs/features/file-watching/README.md`). The server registers
@@ -331,6 +410,15 @@ not see.
drive-letter rule (`file:///C:/x` → `C:\x`) is written and compiled but
**untested on Windows** — it is behind `cfg!(windows)` so it cannot misfire
on a POSIX path legitimately named `/C:`.
- ~~**The workspace walk is plain.** `initialize`'s `workspace_folders`
(falling back to `root_uri`) are walked recursively.~~ **Superseded
(index-scope, 2026-08-27): the folders are the *clamp* now, not the work
list. What is walked by default is the folders the open buffers live in,
raised `lucisv.index.scopeDepth` levels; `lucisv.index.scope: "workspace"`
asks for the walk this paragraph describes. See the model section above and
`docs/features/index-scope/README.md`.** The rest of the paragraph — the
extensions, the `.gitignore` handling, the mid-session folder changes — is
unchanged and still applies to whichever directories are walked.
- **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling
back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`.
~~They are read once and frozen for the session.~~ **Superseded
@@ -373,17 +461,17 @@ spans, and `defines::{collect_defines, Define, DefineTable}`.
reference_at, references_of, document_symbols, symbol, symbols, references,
reference_id_at, scope}`, `Symbol { name, kind, name_span, decl_span, scope,
child_scope }`, `Scope::owner`, `SymbolKind`, `Resolution`, `DocumentSymbol`,
and the workspace layer — `WorkspaceIndex::{build, path, units, member,
find_define, workspace_symbols}`, `resolve_external`,
and the workspace layer — `WorkspaceIndex::{build, path, file_id, units,
member, find_define, references_to, references_are_ambiguous,
workspace_symbols}`, `resolve_external`,
`ExternalResolutions::{definition_of, get}`, `ExternalTarget::best`,
`Definition`, `Def`.
**Consumed from `vlog_refactor`:** `prepare_rename`, `rename`,
`instantiation_plan` and friends, the port refactorings, and — since
references-nav (M7) — `find_references(files, file, offset,
include_declaration) -> Result<Vec<(PathBuf, TextRange)>, String>`, which is
the cross-file half of `textDocument/references`. Every one of them takes the
same `Workspace::sources()` file set.
`instantiation_plan` and friends, and the port refactorings. Rename consumes
the `Workspace::sources()` file set. `find_references` remains available and
is the equivalence oracle for the indexed references test, but is no longer
called by the request handler.
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
Result<String, FormatError>` and `Config { max_width, indent_width }`.
@@ -589,11 +677,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
answering across the workspace means resolving every other file's
references *into* this one — an inverted index the workspace layer does
not build. It is a real feature, not a small addition.~~ Delivered by
**references-nav** (M7). The inverted index was never built: M2's rename
already resolves every *other* file's references and asks whether each
one lands on this declaration, so the answer came from sharing that walk
(`vlog_refactor::find_references`) rather than from new machinery. The
same round added `documentHighlight` for symbols and `foldingRange`.
**references-nav** (M7). It initially shared M2's rename walk; on
2026-08-27 `WorkspaceIndex` gained persisted declaration-to-occurrence
postings and the request moved to indexed lookup, with the old walk kept
as a correctness oracle. The same round added `documentHighlight` for
symbols and `foldingRange`.
`docs/features/references-nav/README.md`.
- [x] ~~**Not done:**~~ `lucisv.toml` discovery, `.gitignore`-aware indexing —
delivered by lucisv-core-lift (both Handshakes below marked DELIVERED).
@@ -635,6 +723,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
3.18 items **parked** with their evidence and re-check triggers: snippet
`WorkspaceEdit` edits and `workspace/textDocumentContent`, neither of
which the pinned `[email protected]` can consume.
- [x] The **large-file fast path** — delivered by **large-file-mode**
(2026-08-27): a buffer over `lucisv.largeFile.threshold` is line-indexed
and nothing else, coloured a viewport at a time by
`semanticTokens/range`, and answers everything else empty.
`docs/features/large-file-mode/README.md`.
- [ ] **Not done:** editor packaging (the VS Code extension and the
`lspconfig` snippet are their own TODO.md §6 item).
@@ -665,12 +758,14 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
is the tail of `pkg::base` and the whole of a bare `base`. That gets in-file
bases, cross-file bases, package-qualified bases and parameterized bases from
one line, and can never disagree with F12 on the same token.
- **`subtypes` is `callers_of_each`'s census in another key**: one
- **`subtypes` is `callers_of_each`'s census in another key**: ~~one
`sources()` pass, a substring prefilter before any parse, a deterministic
sort. 55 ms over the 860-file corpus, 53 ms of it file I/O — the same shape
`incomingCalls` measured, and the same backlog item (an edge table in
`WorkspaceIndex`, now filed for inheritance edges beside the instantiation
ones).
ones).~~ **The backlog item shipped (incremental-index, 2026-08-27):** both
are index lookups now, in the same deterministic sort, at 0.71 ms and
0.26 ms.
- **What the class model lacked:** interface classes. `vlog_parser` rejects
`interface class` outright, so `implements` can never resolve and no item can
carry `SymbolKind::Interface`; both facts are pinned by tests named to force a
+98 -18
View File
@@ -29,22 +29,24 @@ predicate, and three handlers.
edited but not saved, when the file is new) is answered in-file until the
next rebuild. That is the same staleness window every other cross-file
answer already has, documented in `docs/features/lucisv-server/README.md`.
- **A references answer costs what a rename costs.** The cross-file path calls
`Workspace::sources()`, which re-reads every in-scope file, and then
re-analyzes the files that spell the name. Measured at 218 ms over the
860-file corpus (below); the gate above is what keeps a local signal at
1 ms rather than paying that on every request.
- **A references answer is an indexed lookup.** Each `FileFacts` record stores
compact facts for references to externally reachable declarations. The
finished `WorkspaceIndex` resolves those facts once into declaration-to-use
postings, and a request reads only that posting list. Open documents replace
their saved postings with live `Semantics`, preserving unsaved additions and
deletions. The old `Workspace::sources()` + refactor walk remains rename's
correctness engine but is no longer on the references request path.
- **A refusal degrades to the in-file answer, it is not an error.** The shared
engine refuses an ambiguous name (declared in two indexed files) exactly as
a rename does. `textDocument/references` is a read-only convenience, so the
handler sends the file's own occurrences rather than a `RequestFailed`: a
highlight the editor can draw beats a shrug, and the refusal the user
actually needs to see is the one on the rename they then attempt.
- **Reference spans are trusted the way rename trusts them**, minus the edit
safety check: `find_references` still drops any span that does not slice
back to the name it claims, but it does not run the re-parse verification
pass, because it produces no edits and CLAUDE.md invariant #1 is about
output, not about a list of places.
- **Reference spans are produced by the semantic analysis and versioned with
the file facts.** A cache entry is content-addressed, so a saved span cannot
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.
- **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
@@ -56,7 +58,8 @@ predicate, and three handlers.
## Handshakes
**New public API in `vlog_refactor`** — the one handshake this round changes:
**The original public API in `vlog_refactor`**, retained for rename and as the
equivalence oracle in tests:
```rust
pub fn find_references(
@@ -72,7 +75,7 @@ current text, open buffers already overlaying disk). The result is sorted by
path then by position; an `Err` is the sentence a rename at that position
would refuse with.
**Where the sharing lives, and why there.** The collection walk is
**Where the original sharing lives.** The collection walk is
`Scope::collect_occurrences` in `crates/vlog_refactor/src/rename.rs` — lifted
out of `collect_edits`, which now calls it and turns the spans into edits.
`find_references` (`crates/vlog_refactor/src/references.rs`) calls the same
@@ -81,15 +84,24 @@ spans. The alternative considered was lifting the walk into `vlog_semantic`;
it was rejected because the walk is not a semantic query — it needs the
`Scope` cache, the workspace overlay *per file*, and the ambiguity policy,
all of which are refactor-crate concerns, and `lucisv_server` already depends
on `vlog_refactor`. Copy-pasting the walk into the server was never on the
table: a references list that disagreed with what a rename would touch is a
lie about what lucisv is going to do.
on `vlog_refactor`. The indexed implementation is compared directly with this
walk in the server tests, so moving the hot path does not create a second
semantic answer.
**Consumed from `vlog_semantic`** (all pre-existing, nothing requested):
**New public API in `vlog_semantic`:** `WorkspaceIndex::{file_id,
references_to, references_are_ambiguous}`, plus `DefinitionKey` and
`ReferenceSite`. `FileFacts`' encoded shape now includes local and unresolved
external reference facts, and `FACTS_FORMAT` is **2**. A changed file rebuilds
the merged postings from compact in-memory facts; it does not reread or parse
the other files. `Semantics::{symbol_at, reference_at, reference_id_at}` and
`Document::token_at` now use start-sorted position tables and binary search.
**Consumed from `vlog_semantic`:**
`Semantics::{reference_at, reference_id_at, references_of, symbol, symbol_at,
scope}`, `Scope::owner`, `Symbol::{name, scope, name_span}`,
`ExternalResolutions::get`, `ExternalTarget::best`,
`WorkspaceIndex::{units, member}`.
`WorkspaceIndex::{units, member, file_id, references_to,
references_are_ambiguous}`.
**Consumed from `vlog_parser`**: `token::Comment { span }` trivia and
`LineIndex::line_col` for folding.
@@ -108,11 +120,22 @@ and none was made.
## Status / TODO
- [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
hover/definition/references through indexed cursor and location lookups.
Preserve ambiguity refusals and unsaved open-buffer overlays; prove the
indexed answer equals the existing refactor walk before removing that
walk from the request path. Release probe: **0.064 ms/request** over 820
synthetic files and five returned locations, versus **23.431 ms** for
the old walk on the same workspace.
- [x] `Scope::collect_occurrences` factored out of `collect_edits`, with
`collect_edits` rewritten on top of it (no behaviour change; the rename
suite is the regression test).
- [x] `vlog_refactor::find_references`, new module `references.rs`, 7 tests.
- [x] `nav::references` routes through it when the symbol can leave the file.
- [x] `nav::references` routes through `WorkspaceIndex` postings when the
symbol can leave the file; the refactor walk remains its tested oracle.
- [x] `nav::leaves_this_file` — the index-only gate that keeps a local signal
off the workspace walk.
- [x] `nav::document_highlights` — symbol occurrences in this file.
@@ -142,6 +165,42 @@ and none was made.
## Work log
### 2026-08-27 — indexed navigation performance
- Began replacing the per-request `Workspace::sources()` +
`vlog_refactor::find_references` rebuild with reference facts stored in the
existing semantic index. The chosen shape is deliberately not a second
project model: `FileFacts` remains the per-file persistence and incremental
update unit, while `WorkspaceIndex` gains the merged inverted postings.
`FACTS_FORMAT` will bump because the persistent record gains fields; the
cache's version handshake therefore drops old records rather than reading a
partial shape.
- Scope remains the scope ladder's decision (filelist exactly when configured,
otherwise the folder/workspace setting already in force). This round changes
the cost of navigation inside that scope, not which files the user asked the
server to index.
- Completed the inverted index in the existing `FileFacts` /
`WorkspaceIndex` lifecycle. `FACTS_FORMAT` moved from 1 to 2, so an old cache
is discarded safely. Incremental save updates rebuild the postings from
compact facts already in memory; adding/removing files still follows the
index's path-sorted `FileId` contract.
- `nav::references` now resolves the live cursor to one indexed declaration,
reads its posting list, overlays every open buffer's current semantics, and
batches byte-span-to-LSP conversion per touched file. Duplicate declarations
and ambiguous uses still fall back to the in-file answer. Permanent tests
cover module, package-member and port references, cache round trips,
incremental equivalence, ambiguity, unsaved deletions/additions, moved live
declarations, and direct equality with `vlog_refactor::find_references`.
- Cursor hot paths no longer sweep the whole open file: semantic declaration
and reference lookup, plus macro-token hover, use binary-searched position
tables. Include definition inspects only the cursor's line.
- The ignored release latency probe builds 820 files and returns five
locations: **0.064 ms/request** averaged over 200 indexed requests; the old
source collection + refactor walk took **23.431 ms** once on the same files
(about **366×** slower). Command:
`cargo test --release -p lucisv_server
qa_indexed_references_latency_over_a_large_workspace -- --ignored --nocapture`.
### 2026-08-24 — dev agent (M7)
- **Read first**: `CLAUDE.md`, `docs/features/refactor/README.md`'s triage,
@@ -463,6 +522,27 @@ correctness or safety issue in the shipped feature.
## Review
**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
suite green). The design keeps the one-project-model rule: reference
facts live in `FileFacts` (the existing persistence and incremental
unit), postings are merged in `WorkspaceIndex`, and `FACTS_FORMAT` 1→2
plus the cache header's format handshake discards every v1 store whole —
verified in `index_cache.rs:324`. `macro_definitions` filters
`DefineKind::Define`, byte-identical semantics with the
`DefineTable::all` it replaces. Ambiguity is preserved everywhere it
mattered: ambiguous postings are marked, an ambiguous live overlay use
aborts to the in-file answer mid-collection, and the rename refusal
contract survives. The equivalence test pins the indexed answer to the
old `vlog_refactor::find_references` walk, which stays as rename's
engine and the oracle. Lead re-ran the ignored release probe:
0.062 ms/request over 820 files vs 21.7 ms for the old walk (~350×),
consistent with the work log's numbers. No QA-agent pass this round;
the lead review substituted, and the incremental-fingerprint,
unsaved-buffer and ambiguity tests cover the paths a QA attack would
have targeted. Accepted.
**2026-08-24 — lead.** Reviewed after QA's ship verdict (clean first
pass); gates run independently (1330 tests, 0 failures, clippy silent).
The factoring is the right move — `collect_occurrences` peeled out of
+27 -12
View File
@@ -134,16 +134,28 @@ reader — to tell them apart. One item kind, done well.
subtypes}` never panic, never return an item whose `selectionRange` is outside
its `range`, and never return an item for a class the workspace does not
really declare.
- **Requested of `vlog_semantic`, not done here: an inheritance edge table in
`WorkspaceIndex`.** This is the *same* Handshake `docs/features/hierarchy`
filed for instantiation edges and `docs/features/code-lens` rode past — the
index records what a file *declares* and not what it uses, so "who extends X"
has to be a workspace walk. One table keyed by base name, built with the
index, would make `subtypes` a map lookup at the cost of one extra field per
class at index time. Filed together with the instantiation table rather than
separately: the two want the same shape and should land as one round when
something finally justifies widening the index's contract. Today one request
in 55 ms does not.
- **Requested of `vlog_semantic` — delivered (incremental-index,
2026-08-27).** `WorkspaceIndex::subclasses_of` is the table, keyed by base
name and built by the same class walk this module used to run per request —
lifted into `vlog_semantic::classes`, so the census and the declaration a
hierarchy item shows cannot drift apart. `subtypes` is a map lookup and the
`sources()` walk is gone: **82 ms → 0.71 ms** over the corpus for
`core_ibex_base_test`. It landed with the instantiation table, as filed. The
request, kept legible:
~~an inheritance edge table in `WorkspaceIndex`. This is the *same*
Handshake `docs/features/hierarchy` filed for instantiation edges and
`docs/features/code-lens` rode past — the index records what a file
*declares* and not what it uses, so "who extends X" has to be a workspace
walk. One table keyed by base name, built with the index, would make
`subtypes` a map lookup at the cost of one extra field per class at index
time. Filed together with the instantiation table rather than separately: the
two want the same shape and should land as one round when something finally
justifies widening the index's contract. Today one request in 55 ms does
not.~~
- **The answer is as of the index** (incremental-index, 2026-08-27), which is
as of its last build or update — both of which fold every open buffer in. A
keystroke in another buffer no longer moves the subtype list before a save
does; the trade is argued in `docs/features/incremental-index/README.md`.
- **`editors/vscode` needs no change.** `vscode-languageclient` 9.0.1 ships the
type-hierarchy feature and enables it off the advertised capability; the
extension sets no `initializationOptions` that would suppress it, and
@@ -197,12 +209,15 @@ Release build, this machine, the checked-in 860-file corpus, worst of three
| `supertypes` for `core_ibex_debug_intr_basic_test` | **0.69 ms** |
| the same `subtypes` in a debug build | 101 ms |
The shape is the same one `callHierarchy/incomingCalls` measured (56 ms), and
**Superseded (incremental-index, 2026-08-27): `subtypes` is 0.71 ms.** The
table above is what the walk cost; the edge table named as "the place a future
win lives" is where it went. The rest of the paragraph, kept legible:
~~The shape is the same one `callHierarchy/incomingCalls` measured (56 ms), and
for the same reason: what is left after the prefilter is **almost entirely file
I/O**, because `sources()` reads every in-scope file whether it will be parsed
or not. That is the shared cost of every cross-file answer in this server and
the place a future win lives (the edge table above, or a cheaper `sources()`);
nothing in this feature can shave it alone. The prefilter itself is not a
nothing in this feature can shave it alone.~~ The prefilter itself is not a
heuristic — `extends base` has to write `base` — and here it skips 857 of 860
files.
+8
View File
@@ -33,6 +33,7 @@ impl Semantics {
// the LSP queries
fn symbol_at(&self, offset: u32) -> Option<SymbolId>;
fn reference_at(&self, offset: u32) -> Option<&Reference>;
fn reference_id_at(&self, offset: u32) -> Option<ReferenceId>;
fn definition_of(&self, offset: u32) -> Option<&Symbol>;
fn references_of(&self, SymbolId) -> Vec<&Reference>;
fn document_symbols(&self) -> Vec<DocumentSymbol>;
@@ -362,6 +363,8 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
with their paths
- [x] Queries: `symbol_at`, `reference_at`, `definition_of`, `references_of`,
`document_symbols`
- [x] 2026-08-27: declaration/reference cursor queries use start-sorted
position tables and binary search rather than scanning every symbol/use
- [x] `Error` nodes are opaque; tolerant trees analyze without panicking
- [x] Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test
- [x] TODO.md §6 `vlog_semantic` checkbox
@@ -376,6 +379,11 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
## Work log
**2026-08-27 — indexed navigation.** `Semantics` now builds compact sorted
`(TextRange, SymbolId/ReferenceId)` position tables with the analysis.
`symbol_at`, `reference_at` and `reference_id_at` binary-search those tables;
their public answers and half-open span rules are unchanged.
**2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).**
`bind.rs` gains `Target::Type`, emitted by `bind_data_type`'s unqualified arm
and nowhere else, so pass two can tell a type window from an expression.
+29 -8
View File
@@ -15,6 +15,15 @@ scan, one `$/progress` end naming the file count. Gated on the client's own
`window.workDoneProgress` capability, because the spec forbids creating
progress a client never asked for (TODO.md §9b).
**Amended (incremental-index, 2026-08-27): a save is no longer a rescan.**
When a trigger names exactly one file the index already holds — a `didSave`, a
one-file watcher event — only that file's contribution is replaced, in ~33 ms
over the corpus, and **no bar goes up**: the bar exists because a whole scan
takes perceptible seconds, and one parse is not something a user can feel. Every
*whole* rescan below is unchanged, and a save of a file the index does not hold
is still one of them. The tests that used a save as their rescan trigger now use
one that still rescans; see `docs/features/incremental-index/README.md`.
## Assumptions
- **`window.workDoneProgress` is the gate, and there is no fallback.** A client
@@ -36,13 +45,20 @@ progress a client never asked for (TODO.md §9b).
file-watcher (un)registrations use. Nothing is retried and nothing is
remembered: the ids are minted from the one shared `request_ids` counter, so
a progress answer can never be mistaken for an `applyEdit` answer.
- **No percentage, and no intermediate `report`.** `Workspace::rebuild_index`
is one opaque call: it walks the roots, reads every file, builds the index,
the completion tables and the include graph, and returns. There is no
progress to observe without threading a callback through three engine
layers, and an invented percentage — "it is probably about half done" — is a
lie the user would learn to distrust. An indeterminate bar is the honest
shape.
- ~~**No percentage, and no intermediate `report`.**~~ **Superseded
2026-08-27 by `docs/features/indexing-ux/README.md`.** The original reasoning
stands as written and is kept here: `Workspace::rebuild_index` *was* one
opaque call — it walked the roots, read every file, built the index, the
completion tables and the include graph, and returned — so there was no
progress to observe, and an invented percentage ("it is probably about half
done") would have been a lie the user learned to distrust. The indeterminate
bar was the honest shape *for a build nobody could see inside*. What changed
is the premise, not the principle: `vlog_semantic` now exposes
`IndexBuilder`/`index_order`, `rebuild_index_with` drives that loop, and the
bar reports `n/total file.sv` with a percentage that is **counted, not
guessed**. The `begin` still carries no percentage — the first honest one is
the first file's — and the completion tables and include graph, which are
still built opaquely after the index, are still outside the count.
- **The end message is the index's own file count**, read from
`WorkspaceIndex::files().len()` after the scan. That number was already
public and already computed; nothing was plumbed to obtain it. It counts the
@@ -123,6 +139,11 @@ verified by running it.
- [x] Tests: 8 unit (7 in `server.rs`, 1 in `main.rs`), 2 e2e over the wire
- [x] TODO.md §9b checkbox, `docs/features/lucisv-server/README.md` staleness
section
- [x] **Superseded 2026-08-27:** the "no percentage, no report" line above.
The counting reports, the size cap and the per-file log are
`docs/features/indexing-ux/README.md`; the create/begin/end skeleton,
the capability gate, the token scheme and the ordering against the
republish are all unchanged by it.
- [ ] **Not done, deliberately:** no `$/progress` on anything else. Formatting,
a rename across the workspace and `callHierarchy/incomingCalls` are the
other candidates; all three are request-scoped, so they would use the
@@ -184,7 +205,7 @@ The ten tests, and what each is for:
| test | pins |
|---|---|
| `the_startup_index_build_runs_under_the_first_bar` | the startup determination above, as observable traffic |
| `a_save_puts_a_bar_up_and_takes_it_down_again` | create → begin → end, one token, on the save path |
| `a_whole_rescan_puts_a_bar_up_and_takes_it_down_again` (was `a_save_puts_a_bar_up_and_takes_it_down_again`, 2026-08-27) | create → begin → end, one token, on a trigger that still rescans |
| `the_bar_says_how_many_files_were_indexed` | the end message, plural and singular |
| `the_bar_is_down_before_the_republish` | the documented ordering against `publishDiagnostics` |
| `a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all` | zero messages of any kind, at startup and on save |
+49 -7
View File
@@ -9,7 +9,9 @@ paths that could finish it — 19.6 % of every use on cleanly-parsed corpus file
that finishes them. `WorkspaceIndex::build` scans every file in the workspace
once and records what each one *declares* — modules, packages, file-scope
typedefs, each package's and module's exported members, and each file's
`` `define`` table. `resolve_external` walks one file's external candidates
`` `define`` table. Since 2026-08-27 it also records compact reference facts
and merges them into declaration-to-occurrence postings. `resolve_external`
walks one file's external candidates
against that index and answers them in an **overlay** keyed by reference id.
That is what turns `import prim_pkg::*` and `prim_fifo_sync u_fifo (...)` into
a jump into the file that declares them — TODO.md §6's "cross-file resolution
@@ -25,10 +27,18 @@ impl WorkspaceIndex {
fn files(&self) -> &[PathBuf]; // indexed by FileId
fn path(&self, FileId) -> Option<&Path>;
fn file_id(&self, &Path) -> Option<FileId>; // 2026-08-27
fn units(&self, name: &str) -> &[Def]; // module | package | file-scope typedef
fn member(&self, unit: &str, member: &str) -> &[Def];
fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])>;
fn defines(&self, FileId) -> Option<&DefineTable>;
fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]; // 2026-08-27
fn subclasses_of(&self, name: &str) -> &[InheritanceEdge]; // 2026-08-27
fn references_to(&self, def: &Def) -> &[ReferenceSite]; // 2026-08-27
fn references_are_ambiguous(&self, def: &Def) -> bool; // 2026-08-27
fn update_file(&mut self, PathBuf, src: &str); // 2026-08-27
fn remove_file(&mut self, &Path) -> bool; // 2026-08-27
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 counts(&self) -> IndexCounts;
@@ -140,6 +150,11 @@ written"). Ambiguity means something else — see below.
module stays unreachable, which is correct and is a test.
- **`` `define`` tables**: `defines::collect_defines` per file, keyed by
`FileId`, read off the same token stream the parse used.
- **Reference postings**: uses of the externally reachable declarations above.
Each file persists local declaration/use span pairs and unresolved external
candidates; after every build or incremental update, the merged declaration
tables resolve those compact facts into `DefinitionKey -> [ReferenceSite]`.
Ambiguous candidates are marked rather than assigned to a guessed target.
A declaration whose `name_span` is empty (the single-file layer's "I could not
locate this name in the source") is **not** indexed: an editor must never be
@@ -202,9 +217,18 @@ caller does know which file it means.
## Non-goals
- **No incrementality.** `build` is a pure function of its inputs; a changed
- ~~**No incrementality.** `build` is a pure function of its inputs; a changed
workspace means calling it again. TODO.md §6 defers salsa-style
incrementality explicitly, and per-file recompute is fine at Verilog sizes.
incrementality explicitly, and per-file recompute is fine at Verilog sizes.~~
**Superseded (incremental-index, 2026-08-27): one file at a time.**
`WorkspaceIndex::update_file(path, src)` and `remove_file(path)` replace one
file's contribution, and what they produce is *the index a whole `build` over
the same files would have produced* — same `FileId`s, same disambiguation
order, same tables — because the merge they run is `finish`'s own loop
restricted to the keys that file could have moved. `build` is still a pure
function of its inputs and is still what a caller with no reason to be clever
should use. This is not salsa: there is no query graph and no dependency
tracking, just one file's records replaced in a sorted list.
- **No `` `include`` following.** The index does not build the include graph,
so it cannot say which define or which typedef a given file actually sees.
- **No elaboration**: no parameter binding, no instance hierarchy, no
@@ -268,8 +292,10 @@ workspace index: 860 files in 0.68s — 521 modules, 63 packages,
Build time is a debug build, single-threaded, sources already in memory
(reading them costs the caller another ~0.1 s). Well inside the ~2 s budget;
re-running the whole build on every workspace change is affordable, which is
why there is no incrementality.
re-running the whole build on every workspace change is affordable ~~, which is
why there is no incrementality~~ — **but not on every save, which is why there
is now `update_file` (incremental-index, 2026-08-27): one file costs 33 ms
against the whole rebuild's 1.5 s.**
**The headline.** For each file: analyze it, resolve its external candidates
against the index, and count what happened.
@@ -387,11 +413,27 @@ and more than half of all external candidates answered on clean files.
- [x] Corpus acceptance: build time, counts, resolution rate, determinism,
every answer's span slices back to the name
- [x] TODO.md §6 workspace-index checkbox
- [ ] Deferred (non-goals above): `` `include`` graph, incrementality,
elaboration
- [x] 2026-08-27 (`incremental-index`): `update_file`/`remove_file`, exactly
equal to a whole build; instantiation and inheritance edge tables
(`instantiations_of`, `subclasses_of`); `fingerprint` as the equivalence
witness
- [x] 2026-08-27 (`references-nav` performance): persisted reference facts,
declaration-to-occurrence postings, ambiguity markers and indexed macro
lookup; reference postings included in the incremental fingerprint
- [ ] Deferred (non-goals above): `` `include`` graph, elaboration
## Work log
**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
are merged, including on an incremental update, without rereading or reparsing
other files. The public query is `references_to`; ambiguous external uses are
tracked separately so navigation preserves the existing rename refusal. Three
focused tests cover postings, incremental/full-build equivalence, and
ambiguity, while the record round-trip and corpus acceptance cover persistence
and real-source scale.
**2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).**
`resolve_external` gained one arm: an `InheritedCandidate`'s paths are tried
like an external candidate's, and an entry is recorded only when one lands, so
+264
View File
@@ -0,0 +1,264 @@
# Changelog
What each release of the **lucisv — Verilog/SystemVerilog** extension changed
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).
## 0.12.0 — 2026-08-27
The indexed-navigation release.
- **Find All References is now a lookup, not a scan.** The index stores where
every module, package and exported member is used; a references request
reads that list and overlays your unsaved edits — around 0.06 ms on an
820-file workspace where the previous walk took 22 ms.
- **Hover, definition and references respond faster under the cursor** in
large open files: position lookups binary-search sorted tables instead of
sweeping the buffer.
- **One-time index rebuild.** The on-disk index cache format changed; the
first open after updating re-scans the workspace once (watch the progress
bar), then caching resumes as before. No setting changes.
## 0.11.0 — 2026-08-27
The large-workarea release: a project too big to scan is now a project lucisv
keeps up with.
- **Open-file-first indexing.** `lucisv.index.scope` defaults to `folder` — the
index covers the folders your open files live in, and widens as you open
more. `lucisv.index.scopeDepth` starts the climb higher, so a file in `rtl/`
can also index `include/` beside it. Cross-file answers are scope-relative
until the scope reaches a folder; a `lucisv.filelist` still puts the whole
project in scope, and `"lucisv.index.scope": "workspace"` restores the
previous whole-workspace walk exactly.
- **A size cap on the folder scan.** `lucisv.index.maxFileSize` (1 MiB by
default, `0` disables) keeps generated netlists out of the index. A file you
open is always indexed in full.
- **The indexing progress bar counts**, naming the file it is on with a real
`n/total` and percentage instead of an indeterminate spinner.
- **A per-file log in the lucisv output channel**, on by default
(`lucisv.index.logFiles`): every file as it is indexed or restored from
cache, every file the size cap skipped, and a closing count of all three.
- **A save updates one file, not the workspace.** Saving a file the index
already holds replaces only that file's contribution, with no rescan and no
progress bar — ~45× faster on an 860-file workspace (debug build; release is faster still). Instantiation counts,
incoming calls and subtype lists became lookups in the same change, so code
lenses over a whole file cost a fraction of a millisecond.
- **A persistent index cache.** `lucisv.index.persist` (on by default) stores
what indexing each file found, keyed by that file's exact contents, so
reopening a workspace — or reopening it after a crash mid-scan — resumes
instead of restarting. A stale or damaged record costs a re-parse and can
never change an answer. `lucisv.index.cachePath` moves the store; empty means
the extension's own per-workspace storage folder.
- **Large-file mode.** Above `lucisv.largeFile.threshold` (4 MiB) an opened
file is never parsed, analyzed or indexed, so a 100 MB netlist opens
instantly. You keep syntax coloring of the viewport plus go-to-definition and
find-references within that file by text scan; diagnostics, formatting,
symbols, folding, rename, hover and completion answer nothing, and formatting
says so rather than failing quietly.
## 0.10.2 — 2026-08-27
- A seventh package, `all`, carries every platform's server and CLI in one
file — for mixed fleets, internal mirrors, and Alpine, which VS Code never
offers a Linux package to. About 13 MB against 3 MB, and nothing else
changes.
- The Marketplace page is rewritten for end users: install matrix, capability
tables, snippet library, settings ladder, troubleshooting, icon and diagrams.
- Troubleshooting now names the duplicate-hover trap: the pre-rename **vfmt**
extension left installed beside lucisv attaches a second language server, so
every hover and diagnostic appears twice. Uninstall `vfmt` and reload.
## 0.10.1 — 2026-08-27
- **Install in one step.** Five platform packages — `darwin-arm64`,
`darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64` — embed that platform's
`lucisv-server` and `lucisv`. Nothing to build, nothing to put on `PATH`.
- Both Linux packages are statically linked, so they run on any distro;
`linux-arm64` is a new target.
- Server resolution is explicit `lucisv.serverPath` first, then the bundled
binary, then `PATH` — so pointing at your own build still works, and clearing
the setting returns to the bundled server.
- The binary-free universal `.vsix` remains as a fallback for platforms without
a package.
## 0.10.0 — 2026-08-27
- **Go to type definition**: variable to typedef, handle to class, instance to
module, signal to interface, across files.
- **Type hierarchy**: supertypes and subtypes over class `extends`.
- **Linked editing** keeps closing labels (`endmodule : m`, `end : blk`) in
step with their opener.
- **Code lenses** show a workspace-wide instantiation count above every module;
click to jump to a site.
- **On-type formatting**: typing `;` reformats the finished statement, and a
newline indents the new line.
- **Renaming a file rewrites every `` `include`` that resolves to it**, refusing
rather than guessing when no safe spelling exists; directory renames too.
- **Multi-range formatting**, workspace folders added or removed mid-session,
and configuration pulled by modern clients.
- Interface ports written without a direction
(`module m (bus_if bus, input logic clk);`) now parse, so those files format
and analyze.
## 0.9.0 — 2026-08-26
- **Incremental text sync**: a keystroke sends the changed range, not the whole
file.
- **Semantic tokens by range and delta**, so large files color the viewport
first and edits re-send only what moved.
- **An indexing progress bar** on every workspace rescan, with an honest file
count when it comes down.
- **Format on save over the protocol** for editors without a native one, as
`lucisv.formatOnSave` — leave it off in VS Code, which already formats
through lucisv.
- Requests you have already outrun are cancelled instead of computed.
## 0.8.0 — 2026-08-26
- **The port commands actually edit now.** `lucisv.addPort`,
`lucisv.removePort` and `lucisv.propagatePorts` invoked as commands did
nothing in stock clients; they now apply their edit as one labelled,
undoable workspace edit and report a refusal. The lightbulb path was never
affected.
- **Pull diagnostics** for clients that ask for them, from the same parse and
lint pass as the push model — never both for one client.
- **Expand selection** grows from identifier to statement to `begin`/`end` to
process to module to file, and keeps working in half-edited files.
## 0.7.2 — 2026-08-26
- A formatting fix: a stale column measurement after multi-line raw text (a
string across a line break, a `#( ... )` type reference) forced a spurious
break on the rest of the line.
- Documentation corrections across the project README.
## 0.7.1 — 2026-08-26
- **`` `ifdef`` regions whose arms are each half a construct now format**
instead of erroring, preserved as exact source bytes with the first line
re-indented. Real-world corpus coverage went from 97.6% to **99.1%** of 820
files.
- Releases are built and published automatically, with the `.vsix` and
checksums attached to each tag.
## 0.7.0 — 2026-08-25
- **Ghost text lands aligned.** An accepted inline template's `end` no longer
arrives one indent too deep; bodies are placed with the editor's own tab size
and insert-spaces settings.
- **More constructs finish themselves**: `case`/`casez`/`casex` with arms and
`endcase`, `for` with a dialect-correct header, `while`, `always_ff @(` with
a clock, `always @(` offering the clocked shape first (`Alt+]` cycles),
`fork`, `generate`, and `module` with a named `endmodule`.
## 0.6.0 — 2026-08-25
- **Inline templates (ghost text).** Type `if (` and grey `) begin … end`
appears behind the cursor; `Tab` accepts it as a snippet, landing in the
condition first and the body second. Offered only while the construct is
genuinely unclosed, never inside a comment or a string.
`lucisv.inlineTemplates: false` turns it off.
- Scope matching — the rainbow, the missing-`end` diagnostic and the ghost-text
gate — is linear now: 8,000 nested `begin`s went from 629 ms to 2.3 ms per
pass, on a path that runs at every keystroke.
## 0.5.0 — 2026-08-25
The navigation release.
- **Find references across files** for every symbol the workspace index holds —
modules, packages, exported members, ports. Local signals stay local.
- **Document highlights** for a name's declaration and every use of it in the
file, and **folding ranges** for every matched scope pair plus multi-line
block comments.
- **Inlay hints** draw each port and parameter name before the expression it
belongs to in ordered connections — and draw nothing rather than a guess
wherever the site is ambiguous.
- **`` `include`` is clickable**, resolved through the including file's own
directory and the filelist's `+incdir+` rules in order.
- **Module hierarchy** over the call hierarchy view: who instantiates this
module, and what does it instantiate.
- **Hover expands a macro call** one step, with the call site's arguments
substituted into the body.
- The index now follows the disk — a `git pull`, a branch checkout or a
generator's output refreshes it, not just a save.
## 0.4.2 — 2026-08-24
- **`#200` is a delay, not a color.** VS Code's built-in color decorators were
painting RGB swatches on delay controls; the extension now defaults
`editor.defaultColorDecorators` to `never` for `[verilog]` and
`[systemverilog]`. It is a default, so you can override it back.
## 0.4.1 — 2026-08-24
- **Hover cards are syntax highlighted.** The extension now contributes a
TextMate grammar for both languages — comments, strings, based and real
literals, system tasks, directives, macro uses and all 181 keywords — so
hover snippets and completion documentation are colored instead of flat grey.
- The same grammar colors a buffer before the server starts, in files the
server does not index, and in diffs and git previews. Semantic tokens still
win wherever the server is running.
## 0.4.0 — 2026-08-24
- **Completion offers templates, not just words.** `if begin/end`, `if/else`,
`else if`, `case`, `casez`, `for`, `while`, `always_ff` (with and without an
async reset), `always_comb`, `always @(...)`, `initial` and the everyday
declarations, each gated by cursor position and by dialect so a `.v` file is
never offered `logic`.
- The extension's own static snippets shed the nine that would otherwise have
been offered twice; the file-level templates (`module`, `tb`, `fsm`,
`interface`, `guard` and the rest) stay, and still work with no server
running.
## 0.3.1 — 2026-08-24
- **The `begin`/`end` rainbow no longer makes keywords invisible.** It painted
with VS Code's bracket colors, three of which default to fully transparent,
so nesting depths 3–5 vanished. The rainbow now uses its own theme colors,
`lucisv.rainbow1` … `lucisv.rainbow6`, with opaque defaults for dark, light
and high-contrast themes — still overridable in
`workbench.colorCustomizations`.
- **Unmatched delimiters are colored too**, in `lucisv.rainbowUnmatched`: a
fresh `begin` reads as an error until its `end` exists.
## 0.3.0 — 2026-08-24
The refactoring release.
- **Rename across files** for every symbol the semantic layer resolves, from
nets and ports to modules, packages and class members — refusing rather than
guessing on a collision, an invalid identifier, or any file that would stop
parsing.
- **Module signature changes** as code actions and commands: add a port, remove
a port, propagate ports — each updating every affected instantiation.
- **Module instantiation completion**: typing a module name at item position
writes the whole instantiation, with same-named signals already bound and the
rest as tab stops, plus **signature help** inside port and parameter lists.
- **Completion** now offers the scope's own declarations, what the project
declares, every keyword, and finally every identifier used in the project —
never inside a comment or a string.
- **`lucisv.filelist`**: point lucisv at an EDA `.f` filelist and it indexes
exactly the files your build names.
## 0.2.0 — 2026-08-19
The first released version: formatting, linting and a language server for
Verilog-2001 and the synthesizable SystemVerilog subset.
- **Document formatting** with a width-aware, deterministic style — and a
safety net that re-lexes and re-formats every result, discarding it and
leaving the file untouched if anything disagrees. Comments are never dropped;
`// verilog_format: off` / `on` fences are preserved byte for byte.
- **Live diagnostics**: parse errors and lint warnings in one publish per
change, with quick fixes and `source.fixAll.lucisv` for fix-on-save.
- **Navigation and understanding**: hover with declaration snippets and
`` `define`` expansion, go to definition, in-file references, document and
workspace symbols, and semantic highlighting.
- **Waivers** in Verible's spelling, so code already annotated for Verible
lints unedited.
- The extension registers `.v`/`.vh` as `verilog` and `.sv`/`.svh` as
`systemverilog`, and has one setting, `lucisv.serverPath`.
+101 -4
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.10.2**. Its platform packages include both
The current release is **0.12.0**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -156,18 +156,76 @@ enabling both paths formats twice.
| Feature | What you get |
|---|---|
| Project indexing | Indexes a configured EDA filelist, otherwise the workspace folder, otherwise the open file's directory |
| Project indexing | Indexes a configured EDA filelist when you have one; otherwise the folders your open files live in, widening as you work (`lucisv.index.scope`) — or every workspace folder with `"workspace"` |
| Filelist support | Nested `-f`, `+incdir+`, `+define+`, comments, environment variables, and relative paths are understood |
| Matching file discovery | Workspace walks honor `.gitignore`, supported file extensions, and `lucisv.toml`/editor excludes |
| Open-buffer overlay | Unsaved files and edits immediately override disk content in navigation and analysis |
| Incremental sync | Keystrokes send only changed ranges, not the full buffer |
| File and folder watching | Create, change, rename, delete, and multi-root folder updates automatically refresh the index |
| Index progress | Large rescans show an **Indexing Verilog workspace** progress bar and final file count |
| Index progress | Rescans show an **Indexing Verilog workspace** bar counting `n/total` through the files, with a per-file log in the output channel and a closing count of indexed, cached, and skipped files |
| Responsive requests | Cancellation drops stale queued work; semantic token deltas and range responses minimize repeated data |
| Live configuration | Project and editor configuration changes take effect without restarting the server |
![lucisv extension architecture](https://git.luci.ooo/lucio/lucisv/raw/branch/master/editors/vscode/images/architecture.png)
## Large workspaces
Shipped in **0.11.0**. The [changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/editors/vscode/CHANGELOG.md) tracks the details under
**Unreleased**.
A workarea with tens of thousands of files used to pay for a full scan on every
save. That is replaced by a chain of narrower answers:
- **The scan follows your open files.** `lucisv.index.scope` defaults to
`folder`: the index covers the folders your open buffers live in and
everything under them, and opening a file elsewhere widens it. `scopeDepth`
starts the climb one or more folders higher, so a file in `rtl/` can also
index `include/` beside it.
- **Generated netlists stay out of the scan.** `lucisv.index.maxFileSize` caps
a walked file at 1 MiB by default — bigger is almost always machine output
that costs minutes and answers nothing. A file you actually open is always
indexed in full, whatever its size.
- **The progress bar counts.** The **Indexing Verilog workspace** bar names the
file it is on with a real `n/total` and a real percentage instead of an
indeterminate spinner.
- **The output channel says what happened.** With `lucisv.index.logFiles` on,
every file is named as it is indexed, restored from cache, or skipped by the
size cap, and the bar's closing message counts all three —
`860 files indexed, 858 from cache, 2 skipped`. That is what answers "why is
this symbol missing" and "why was that scan slow" without a debugger.
- **A save costs one file.** Saving a file the index already holds replaces
just that file's contribution, with no progress bar and no rescan — measured
at ~45× faster than the whole rebuild it replaces (860-file workspace, debug build — release is faster still).
Instantiation counts, call hierarchy and subtype lists became table lookups
in the same change, so a code lens over a whole file is a fraction of a
millisecond.
- **The index survives a reopen.** `lucisv.index.persist` (on by default)
writes what indexing each file found to a per-workspace store, keyed by that
file's exact contents. Reopening the workspace — or reopening it after a
crash halfway through the first scan — resumes from those records instead of
parsing everything again; a stale or damaged record costs a re-parse and can
never change an answer. `lucisv.index.cachePath` moves the store somewhere
you choose, for example to share one between checkouts of the same tree.
- **A 100 MB netlist opens instantly.** Above
`lucisv.largeFile.threshold` (4 MiB) an opened file is line-counted and
nothing else: never parsed, never analyzed, never indexed. What you keep is
syntax coloring of the screenful you are looking at, painted a window at a
time, plus go-to-definition and find-references within that one file by text
scan. Everything else — diagnostics, formatting, symbols, folding, rename,
hover, completion — answers nothing for such a file, and formatting says so
rather than failing quietly. (VS Code never hands an extension a file over
50 MB at all, so in VS Code this path serves everything from the threshold up
to that limit; the 100 MB case belongs to editors without that rule.)
The honest trade: with the folder scope, cross-file answers are **scope
relative**. A symbol in a folder the scope has not reached yet does not exist
as far as the server is concerned, so go-to-definition, workspace symbol
search, find references, the hierarchies and workspace rename all answer within
the scope you have opened your way into. Point `lucisv.filelist` at your EDA
filelist and the whole project is in scope from the first keystroke; set
`"lucisv.index.scope": "workspace"` and the whole-workspace walk every release
up to 0.10.2 did is back, unchanged.
## Snippet library
Type a prefix and choose the snippet; `Tab` walks its placeholders. Static
@@ -209,9 +267,20 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.indent` | unset | Indent width, 1–8; falls back to the editor tab size, then 2 |
| `lucisv.exclude` | `[]` | Extra index exclusions added to the project's own patterns |
| `lucisv.filelist` | `""` | EDA `.f` filelist to index instead of walking the folder |
| `lucisv.formatOnSave` | `false` | Protocol save hook for editors without native format-on-save; keep off in VS Code |
| `lucisv.index.scope` | `folder` | Index the folders your open files live in, or every workspace folder with `workspace`; answers stay scope-relative until the scope reaches a folder |
| `lucisv.index.scopeDepth` | `0` | How many folders above an open file the `folder` scope starts from; `1` lets a file in `rtl/` index `include/` beside it |
| `lucisv.index.maxFileSize` | `1 MiB` | Largest walked file the index reads, in bytes; `0` removes the cap, and a file you open is always indexed in full |
| `lucisv.index.logFiles` | `true` | Name every indexed, cached, and cap-skipped file in the lucisv output channel |
| `lucisv.index.persist` | `true` | Remember what indexing each file found, so a reopen resumes instead of rescanning |
| `lucisv.index.cachePath` | `""` | Where that store lives; empty means the extension's own per-workspace storage folder |
| `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 |
The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with
the [large workspaces](#large-workspaces) work; everything else ships in
0.10.2.
A nearby `lucisv.toml` is the project source of truth and wins over editor
style settings. Each file discovers configuration upward, so one workspace may
contain projects with different formatting rules.
@@ -251,6 +320,34 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.12.0 highlights
Version 0.12.0 is the indexed-navigation release:
- Find All References reads precomputed declaration-to-use postings and
overlays your unsaved edits — ~0.06 ms on an 820-file workspace where the
previous project walk took 22 ms.
- Cursor lookups (hover, definition, references) binary-search position
tables instead of sweeping large buffers.
- The index cache format changed: the first open after updating re-scans the
workspace once, then persistent caching resumes.
## Release 0.11.0 highlights
Version 0.11.0 is the large-workarea release:
- Indexing starts from the files you open and their folders, not the whole
tree — `lucisv.index.scope`, with a depth knob and a one-line return to the
old whole-workspace walk.
- A save re-indexes one file in milliseconds; instantiation counts and
hierarchy answers come from precomputed tables instead of file walks.
- The index persists per workarea and resumes after a crash or reopen —
cached files fly through the counting progress bar.
- Netlists past `lucisv.largeFile.threshold` open in tens of milliseconds
with viewport syntax highlighting and same-file navigation.
- A size cap (`lucisv.index.maxFileSize`) keeps generated files out of the
index, and the output channel narrates every scan.
## Release 0.10.2 highlights
Version 0.10.2 is the one-step installation release:
+12
View File
@@ -157,6 +157,18 @@ function activate(context) {
// `lucisv.indent` and `lucisv.exclude` from it and ignores the rest
// (docs/features/editor-settings/README.md).
synchronize: { configurationSection: 'lucisv' },
// Where the server may keep its index cache, so that reopening a
// workspace does not re-parse every file it already parsed last time
// (docs/features/index-persistence/README.md). `storageUri` is VS Code's
// own per-workspace folder for exactly this kind of state — it is
// cleaned up when the workspace is forgotten, which is what makes it a
// better answer than a directory the server would have to invent. It is
// `undefined` when no workspace is open, and then the global one stands
// in; the server falls back to this platform's cache directory if
// neither reaches it, and to no cache at all if it cannot work one out.
initializationOptions: {
storagePath: (context.storageUri || context.globalStorageUri || {}).fsPath,
},
};
client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions);
+44 -1
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.10.2",
"version": "0.12.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -234,6 +234,49 @@
"type": "string",
"default": "",
"markdownDescription": "Path to an EDA filelist (`.f`), absolute or relative to the workspace folder. When set, **exactly** the files it names are indexed instead of the whole folder — `-f` nesting, `+incdir+`, `+define+`, `#`/`//` comments and `$VAR` expansion are all understood. Overrides a `filelist` key in the project's `lucisv.toml`; leave it empty to index the workspace folder."
},
"lucisv.index.scope": {
"type": "string",
"enum": ["folder", "workspace"],
"enumDescriptions": [
"Index the folders your open files live in, and everything under them.",
"Index every folder in the workspace, whatever is open."
],
"default": "folder",
"markdownDescription": "How much of your project the workspace index scans. **`folder` (the default) indexes only the folders your open files live in** — plus everything under them — which is what keeps a huge project from costing minutes on every scan. Opening a file in another folder widens the index to that folder as well, so the scope grows as you work; it never shrinks while the editor is open. **Until it reaches a folder, symbols in that folder do not exist as far as the server is concerned**: go-to-definition, workspace symbol search, call and type hierarchy, find-references and rename all answer within the current scope only. Set to `workspace` to index every workspace folder up front, as lucisv always did before this setting existed — the right choice for a small project or a fast machine. A `#lucisv.filelist#` overrides this setting entirely: a project file defines the scope."
},
"lucisv.index.scopeDepth": {
"type": "number",
"default": 0,
"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."
},
"lucisv.index.maxFileSize": {
"type": "number",
"default": 1048576,
"minimum": 0,
"markdownDescription": "Largest file, in bytes, the workspace index will read while scanning your folders. Anything bigger is almost always a generated netlist rather than a design file, and indexing one costs minutes and answers nothing. Set to `0` for no cap. A file you **open** is always indexed in full, however big it is — the cap applies to the folder scan only. Changing this rescans the workspace."
},
"lucisv.index.logFiles": {
"type": "boolean",
"default": true,
"markdownDescription": "Name every file in the lucisv output channel as it is indexed, and every file the size cap skipped. Useful for finding out why a symbol is missing or why a scan is slow; turn it off if you would rather the channel stayed quiet. Files skipped by `#lucisv.index.maxFileSize#` are counted in the progress bar's final message either way. A file restored from the index cache is logged as `cached:` rather than `indexing:`."
},
"lucisv.index.persist": {
"type": "boolean",
"default": true,
"markdownDescription": "Remember what indexing a file found, so that reopening this workspace — or reopening it after a crash halfway through a scan — does not parse every unchanged file again. The store lives in this workspace's extension storage folder unless `#lucisv.index.cachePath#` says otherwise, and holds one entry per file **keyed by that file's exact contents**: an entry is used only for the bytes it was made from, so a stale or damaged one costs a re-parse and can never affect an answer. Turn it off to keep the index entirely in memory, as lucisv did before this setting existed; nothing is then read or written."
},
"lucisv.index.cachePath": {
"type": "string",
"default": "",
"markdownDescription": "Where to keep the index cache `#lucisv.index.persist#` writes — absolute, or relative to the first workspace folder. Empty (the default) means the extension's own per-workspace storage folder, which VS Code cleans up when the workspace is forgotten. Set this to share one cache between checkouts of the same tree, or to keep it somewhere faster. The directory is created on demand and marks itself ignored with a `.gitignore`. Takes effect on the next workspace scan."
},
"lucisv.largeFile.threshold": {
"type": "number",
"default": 4194304,
"minimum": 0,
"markdownDescription": "Size in bytes above which an **opened file** is put on the fast path: it is line-counted and nothing else — never parsed, never analyzed, never indexed — so a 100 MB netlist opens instantly instead of hanging the editor. What you still get is **syntax colouring of what is on screen**, painted a screenful at a time, plus go-to-definition and find-references within that file by text search. Everything else — diagnostics, formatting, symbols, folding, rename, hover, completion — answers nothing at all for such a file, and formatting says so rather than doing nothing quietly. A file on the fast path is left out of the workspace index entirely, so its symbols do not exist for the rest of the project. Set to `0` to analyze every file you open however big it is. Takes effect the next time the file is opened or edited. Not to be confused with `#lucisv.index.maxFileSize#`, which is about files nobody opened."
}
}
}