Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17214ac8db | ||
|
|
d4eb8f48ff | ||
|
|
cf32e92e58 | ||
|
|
097498da23 | ||
|
|
4f7b4a9f91 | ||
|
|
574ab833e3 | ||
|
|
12d0bbad51 | ||
|
|
de8a7e129c | ||
|
|
611dd23069 | ||
|
|
a4f23db2c7 | ||
|
|
d94f9e3de0 | ||
|
|
94b130aca1 | ||
|
|
efe67bde65 | ||
|
|
e70d979e51 | ||
|
|
b2d778eb8d | ||
|
|
27fc216df3 | ||
|
|
4665641e42 | ||
|
|
bc606dd6bd | ||
|
|
5e98b1a669 | ||
|
|
2e258df9a7 | ||
|
|
e4b1f55c12 | ||
|
|
5e4aa7bd6f | ||
|
|
7266b13702 | ||
|
|
8c8cfc538e |
No files matched your search
+192
@@ -4,6 +4,198 @@ 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.13.1 — 2026-08-28
|
||||
|
||||
The F12-latency release: the two costs behind a slow jump out of a big
|
||||
open file, found by measurement and removed, plus a stack-safety hole
|
||||
closed.
|
||||
|
||||
### References stop sweeping the open buffer
|
||||
|
||||
The open-document overlay in find-references did index lookups for
|
||||
every reference in every open buffer. A spelled-name prefilter and a
|
||||
hoisted file lookup take a 70 000-reference open `top.sv` from 3.2 ms
|
||||
to **0.11 ms** per request, both directions; in-file references and
|
||||
occurrence highlighting on a heavily used signal drop ~40 %. Answers
|
||||
are byte-identical — the old refactor walk remains the tested oracle.
|
||||
|
||||
### A rescan reuses what open buffers already analyzed
|
||||
|
||||
Jumping into a folder the index scope had not reached triggered a
|
||||
rescan that re-parsed every open buffer's text twice — once for index
|
||||
facts, once for completion words. Both now come from the analysis the
|
||||
buffer already holds (one implementation per path, byte-identical facts
|
||||
pinned over the corpus): the folder-widening jump drops from **228 ms
|
||||
to 23 ms**, and didSave's incremental update rides the same reuse.
|
||||
|
||||
### The stack now fits the nesting limit by construction
|
||||
|
||||
The parser's 64-level nesting limit only turns over-deep input into an
|
||||
error on a stack big enough to reach level 64 — an assumption that had
|
||||
drifted out from under the 2026-08 measurement (~94 KiB per level in
|
||||
debug under rustc 1.97; a default 2 MiB thread aborted near level 30).
|
||||
`PARSE_STACK_SIZE` (16 MiB) is now applied at every parse-reaching
|
||||
thread, both binaries' work included — the CLI previously aborted under
|
||||
a 1 MiB main stack (`ulimit`, win32 default) on 500 nested `begin`s and
|
||||
now emits an ordinary diagnostic. Deep-nesting suites across four
|
||||
crates pin it, sabotage-verified.
|
||||
|
||||
## 0.13.0 — 2026-08-28
|
||||
|
||||
Editor responsiveness, and hover for old-style ports.
|
||||
|
||||
### Typing costs one reanalysis, not one per keystroke
|
||||
|
||||
`didChange` no longer reparses and re-lints the buffer on every
|
||||
keystroke. The text the server holds is still exactly current after
|
||||
every notification; only the analysis is deferred, and it runs at the
|
||||
first moment anything needs it — the next request, the next
|
||||
non-`didChange` notification, or a 150 ms quiet period. A burst of ten
|
||||
keystrokes in a 10 000-line file therefore costs one 31 ms reanalysis
|
||||
instead of ten. The visible consequence: intermediate diagnostics
|
||||
states are no longer published, so squiggles for a half-typed line that
|
||||
was finished a moment later never appear. Every state that is published
|
||||
is one the buffer really passed through. Closing a file that was
|
||||
mid-edit discards its pending change instead of analyzing it, so it
|
||||
costs one publish — the one that clears its squiggles — and not two.
|
||||
|
||||
The one case this makes slower is a single keystroke followed by
|
||||
nothing at all: it now waits out the quiet period before publishing,
|
||||
164 ms instead of one reanalysis. Editors ask for something after every
|
||||
change — semantic tokens, inlay hints, highlights — and any request
|
||||
flushes the buffer before it is answered, so the latency a user
|
||||
actually meets is 4.4 ms in a 1 000-line file and 37.6 ms in a
|
||||
10 000-line one.
|
||||
|
||||
### Hover shows a non-ANSI port's real declaration
|
||||
|
||||
A port declared the old way — named in the module header, completed in
|
||||
the body by `input signed [31:0] data_in;` — now hovers as two fenced
|
||||
sections: the header line, then the body declaration that carries the
|
||||
direction, the type and the width. Go-to-definition offers both, the
|
||||
body declaration first. It works cross-file, into files that are not
|
||||
open, because the span travels through the workspace index. An
|
||||
old-style task or function argument (`task t(a);` finished by
|
||||
`input [7:0] a;`) reads the same way. Each section also carries every
|
||||
comment that documents it: the lines above it, the comment beside it,
|
||||
and the lines below it when nothing else could claim them — all three
|
||||
at once where all three are written.
|
||||
|
||||
### Faster hover and navigation
|
||||
|
||||
A hover into a closed file reads that file once instead of twice (34 ms
|
||||
→ 16.3 ms on a 31.7 MB file), and resolving a live declaration looks
|
||||
its name up instead of walking every symbol in the buffer. Measurements
|
||||
and how to reproduce them: `docs/perf/README.md`.
|
||||
|
||||
### Cursor-position answers stop walking the whole buffer
|
||||
|
||||
Expand-selection, on-type formatting, the completion scope gates and
|
||||
the inline template trigger each used to scan every token in the file
|
||||
to find the one at the cursor. They now binary-search for it: 77 µs →
|
||||
20 ns in a 10 000-line buffer, and 130 µs → 36 ns for the widest of
|
||||
them. No answer changed — each swap is pinned by a test that compares
|
||||
it against the scan it replaced at every byte of the buffer.
|
||||
|
||||
The persistent index cache's record format changed to carry the new
|
||||
span, so the first session after upgrading rebuilds its index rather
|
||||
than reading the old store.
|
||||
|
||||
## 0.12.1 — 2026-08-27
|
||||
|
||||
Hover shows the cross-file declaration itself. A name declared in
|
||||
another file — a port at an instantiation, a module instance, a package
|
||||
member — now renders its declaration's source line, fenced and
|
||||
highlighted, under the existing "declared in `file:line`" heading:
|
||||
direction, type and width for a port, the header line for a module.
|
||||
Snippets come from the live buffer when the declaring file is open
|
||||
(unsaved edits included) and from disk otherwise, with a
|
||||
boundary-checking guard that drops the snippet rather than ever
|
||||
showing a wrong line, and caps of 5 lines / 400 characters for
|
||||
netlist-sized declarations. No settings and no index format change.
|
||||
|
||||
## 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
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.10.2"
|
||||
version = "0.13.1"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -149,8 +149,8 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
- [x] **[R] Parallel file processing.** ruff's speed story is embarrassing
|
||||
parallelism over files. `main.rs` formats serially; use `rayon`
|
||||
par_iter over the collected file list (formatting is already pure).
|
||||
→ `crates/lucisv/src/main.rs`; pool sizing (8 MiB worker stacks, per the
|
||||
recursion-limit handshake), the reworked panic hook and the
|
||||
→ `crates/lucisv/src/main.rs`; pool sizing (`vlog_parser::PARSE_STACK_SIZE`
|
||||
worker stacks, per the recursion-limit handshake), the reworked panic hook and the
|
||||
ordered-reporting determinism argument in
|
||||
`docs/features/parallel-files/README.md`. `--threads N` pins the worker
|
||||
count; output is byte-identical at any count. 3.6× on 10 cores.
|
||||
@@ -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,28 @@ 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.
|
||||
**A third piece answered without salsa, 2026-08-28**
|
||||
(`docs/features/change-debounce/README.md`): the per-keystroke recompute a
|
||||
query graph would have made unnecessary is instead *not started* — a burst
|
||||
of `didChange`s is coalesced into one reanalysis. Still no query graph and
|
||||
no dependency tracking; the salsa question remains open and deferred.
|
||||
Measured costs for what a recompute actually is are now recorded in
|
||||
`docs/perf/README.md`. **Round 2, 2026-08-28**
|
||||
(`docs/features/interactive-latency/README.md`): that recompute is now
|
||||
broken down stage by stage, and 79 % of it is lexing and parsing. If the
|
||||
salsa question is ever reopened, that is the number it has to beat —
|
||||
incremental *lexing and parsing*, not incremental queries over a whole-file
|
||||
parse, and it lands squarely on `CLAUDE.md`'s hard invariants 1 and 2.
|
||||
- [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 +618,14 @@ 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`.**
|
||||
**Since 2026-08-28 a rescan no longer re-parses the buffers it already
|
||||
analyzed** — an open buffer's index facts and completion words come from the
|
||||
analysis it holds — so a scope-widening `didOpen` with a 1.4 MB buffer open
|
||||
costs ~23 ms rather than ~228 ms.
|
||||
- [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.
|
||||
@@ -703,6 +737,18 @@ and are not gaps.
|
||||
publish — per notification. Advertised as `TextDocumentSyncOptions`
|
||||
with the open/close and `save.includeText: false` values a bare `Kind`
|
||||
already implied, so no client's save behavior moved.
|
||||
**Amended 2026-08-28** (`docs/features/change-debounce/README.md`): a
|
||||
`didChange` now only records the composed text; the reparse, the
|
||||
generation bump and the publish happen at the next *flush* — the next
|
||||
request, the next non-`didChange` notification, or a 150 ms quiet period —
|
||||
so a typing burst costs one of each instead of one per keystroke. The
|
||||
buffer's text is still exactly current after every notification; only its
|
||||
analysis is deferred, and intermediate diagnostics states are no longer
|
||||
published. **Measured 2026-08-28**
|
||||
(`docs/features/interactive-latency/README.md`): a burst of ten keystrokes
|
||||
over the wire produces exactly one `publishDiagnostics`, and a keystroke a
|
||||
request follows — the shape a real editor sends — round-trips in 4.8 ms at
|
||||
1 000 lines and 37 ms at 10 000.
|
||||
- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native
|
||||
format-on-save hook (client-side `editor.formatOnSave` already works;
|
||||
this serves the editors without it).
|
||||
@@ -750,6 +796,34 @@ 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.
|
||||
→ **Extended once more, 2026-08-28**
|
||||
(`docs/features/index-scope/README.md`): a file that went into the index from
|
||||
an open buffer's own finished analysis — no parse, no store — logs
|
||||
`analyzed:` and adds nothing to the `end` message, so "from cache" still
|
||||
means the persistent store alone.
|
||||
→ **The other half of the size story, 2026-08-27**
|
||||
(`docs/features/large-file-mode/README.md`): the walk cap covers files
|
||||
nobody opened, and `lucisv.largeFile.threshold` (4 MiB) now covers the file
|
||||
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 +909,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 +960,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
|
||||
|
||||
+37
-11
@@ -32,12 +32,7 @@ use lucisv_core::config::Discovery;
|
||||
use lucisv_core::filelist;
|
||||
use lucisv_core::walk::{collect_files, EXTENSIONS};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
|
||||
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
|
||||
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
|
||||
/// input that trips the parser's nesting limit; rayon's own default is
|
||||
/// 2 MiB, which would put that crash back.
|
||||
const WORKER_STACK: usize = 8 * 1024 * 1024;
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let opts = match args::parse() {
|
||||
@@ -50,10 +45,40 @@ fn main() -> ExitCode {
|
||||
// Once, before any worker thread exists, so nothing ever races on it.
|
||||
install_panic_hook();
|
||||
|
||||
// Nothing parses on the main thread, because its stack is not ours to
|
||||
// state: 8 MiB on a stock macOS or Linux, whatever `ulimit -s` says in a
|
||||
// container, 1 MiB on Windows. The parser's nesting limit only turns
|
||||
// over-deep input into an error on a stack of at least
|
||||
// `PARSE_STACK_SIZE` — below that the overflow, which aborts the
|
||||
// process, comes first. A thread we spawn is the one stack whose size is
|
||||
// ours to guarantee. The pool's workers cover the file-at-a-time paths
|
||||
// (`build_pool`), but not the ones that never reach it: `-` reads and
|
||||
// formats a buffer right here, and so does `lucisv check -`.
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("lucisv".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || run(&opts));
|
||||
let handle = match spawned {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
eprintln!("error: could not start the worker thread: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match handle.join() {
|
||||
Ok(code) => code,
|
||||
// An uncontained panic, already printed by the hook above. 101 is
|
||||
// what the same panic on the main thread would have exited with.
|
||||
Err(_) => ExitCode::from(101),
|
||||
}
|
||||
}
|
||||
|
||||
/// The run itself, on the stack `main` sized for it.
|
||||
fn run(opts: &Options) -> ExitCode {
|
||||
match opts.command {
|
||||
Command::Format if opts.is_stdin() => run_stdin(&opts),
|
||||
Command::Format => run_files(&opts),
|
||||
Command::Check => run_check(&opts),
|
||||
Command::Format if opts.is_stdin() => run_stdin(opts),
|
||||
Command::Format => run_files(opts),
|
||||
Command::Check => run_check(opts),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,11 +297,12 @@ fn entry_for(content: u64, config: &Config) -> Entry {
|
||||
}
|
||||
|
||||
/// Builds rayon's global pool. Worker stacks are sized for the parser's
|
||||
/// recursion limit (see `WORKER_STACK`); `--threads 0` lets rayon pick.
|
||||
/// recursion limit (`PARSE_STACK_SIZE` — rayon's own default is 2 MiB, which
|
||||
/// would put the overflow back); `--threads 0` lets rayon pick the count.
|
||||
fn build_pool(opts: &Options) -> Result<(), String> {
|
||||
rayon::ThreadPoolBuilder::new()
|
||||
.num_threads(opts.thread_count())
|
||||
.stack_size(WORKER_STACK)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.build_global()
|
||||
.map_err(|e| format!("could not start the worker pool: {e}"))
|
||||
}
|
||||
|
||||
@@ -407,7 +407,8 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
|
||||
// costs two levels), so it parses — and needs several MiB of stack to
|
||||
// do it in a debug build: without the depth limit this family died at
|
||||
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
|
||||
// stack. This test crashes the process if the pool's 8 MiB is dropped.
|
||||
// stack. This test crashes the process if the pool's `PARSE_STACK_SIZE`
|
||||
// is dropped.
|
||||
let deep = format!(
|
||||
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"if (clk) begin\n".repeat(28),
|
||||
@@ -425,6 +426,34 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
|
||||
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash() {
|
||||
// The stdin path never touches the worker pool: it formats on the thread
|
||||
// `main` spawned, which is the only stack whose size lucisv gets to
|
||||
// state. 500 nested blocks are far past the parser's limit, so the run
|
||||
// must end with an ordinary parse error — and not with a SIGABRT, which
|
||||
// is what an unstated stack gives instead.
|
||||
let deep = format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"begin\n".repeat(500),
|
||||
"end\n".repeat(500)
|
||||
);
|
||||
let out = run_with_stdin(&["-"], &deep);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("nesting too deep"), "{}", stderr(&out));
|
||||
assert!(stdout(&out).is_empty(), "a rejected buffer prints nothing: {}", stdout(&out));
|
||||
|
||||
// And the deepest *legal* buffer formats on that same stack.
|
||||
let legal = format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"begin\n".repeat(58),
|
||||
"end\n".repeat(58)
|
||||
);
|
||||
let out = run_with_stdin(&["-"], &legal);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stdout(&out).contains("endmodule"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
|
||||
let dir = TempDir::new("configpar");
|
||||
|
||||
@@ -20,11 +20,11 @@
|
||||
//! 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;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
|
||||
@@ -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 {
|
||||
@@ -63,8 +71,91 @@ impl Candidates {
|
||||
/// `sources` is the list `Workspace::collect_sources` already produced for
|
||||
/// the index, so the files are read once and the only extra work is one
|
||||
/// lex per file — see the measurements in the feature README.
|
||||
pub fn build(index: &WorkspaceIndex, sources: &[(PathBuf, String)]) -> Candidates {
|
||||
Candidates { units: units_of(index), macros: macros_of(index), words: words_of(sources) }
|
||||
///
|
||||
/// `known` holds the words of the files whose token stream the caller
|
||||
/// already has — an open buffer's, lexed when the buffer was analyzed. A
|
||||
/// file listed there is not lexed again; a file absent from it is lexed
|
||||
/// here, exactly as every file used to be. The two produce the same words
|
||||
/// because they are the same function over the same tokens
|
||||
/// ([`words_of_tokens`]).
|
||||
pub fn build(
|
||||
index: &WorkspaceIndex,
|
||||
sources: &[(PathBuf, String)],
|
||||
mut known: HashMap<PathBuf, Vec<String>>,
|
||||
) -> Candidates {
|
||||
let mut out = Candidates {
|
||||
units: units_of(index),
|
||||
macros: macros_of(index),
|
||||
..Candidates::default()
|
||||
};
|
||||
for (path, text) in sources {
|
||||
let words = match known.remove(path) {
|
||||
Some(words) => words,
|
||||
None => words_in(text),
|
||||
};
|
||||
for word in &words {
|
||||
*out.word_files.entry(word.clone()).or_default() += 1;
|
||||
}
|
||||
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.update_words(index, path, words_in(text));
|
||||
}
|
||||
|
||||
/// [`Candidates::update_file`] for a file whose words the caller already
|
||||
/// has — an open buffer's, read off the tokens it was analyzed from.
|
||||
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
|
||||
self.units = units_of(index);
|
||||
self.macros = macros_of(index);
|
||||
self.set_words(path, words);
|
||||
}
|
||||
|
||||
/// 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 +223,34 @@ 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() };
|
||||
words_of_tokens(&tokens)
|
||||
}
|
||||
|
||||
/// [`words_in`] over a token stream the caller already lexed.
|
||||
///
|
||||
/// The whole of `words_in` after the lex, so a caller holding an open buffer's
|
||||
/// tokens gets the same words without lexing the buffer again. A buffer that
|
||||
/// did not lex holds no tokens and contributes nothing here either, which is
|
||||
/// the same all-or-nothing rule from the other side.
|
||||
pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
for (_, 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 +272,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.
|
||||
@@ -218,7 +319,7 @@ mod tests {
|
||||
fn built(files: &[(&str, &str)]) -> Candidates {
|
||||
let sources = sources(files);
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
Candidates::build(&index, &sources)
|
||||
Candidates::build(&index, &sources, HashMap::new())
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -324,4 +425,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, HashMap::new());
|
||||
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(¤t, 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(¤t, 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, HashMap::new());
|
||||
|
||||
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(¤t, 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(¤t, 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(¤t, Path::new("/rtl/a.sv"));
|
||||
assert!(candidates.words("w2").is_empty());
|
||||
candidates.remove_file(¤t, Path::new("/rtl/a.sv"));
|
||||
assert!(candidates.words("w2").is_empty(), "removing an already-removed file is a no-op");
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ use vlog_semantic::{Semantics, Symbol, SymbolKind};
|
||||
|
||||
use crate::candidates::starts_with_ignore_case;
|
||||
use crate::pairs;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::state::{first_token_from, Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::{self, Gate, Template};
|
||||
|
||||
@@ -849,9 +849,12 @@ fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)>
|
||||
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
|
||||
/// `generate begin` reaches `generate`. Whichever comes first decides.
|
||||
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
|
||||
let Some(begin) = tokens.iter().position(|token| token.span.start == offset) else {
|
||||
// A token starting exactly at `offset` is the first one that starts at or
|
||||
// after it: every earlier token starts before, every later token after.
|
||||
let begin = first_token_from(tokens, offset);
|
||||
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
|
||||
return false;
|
||||
};
|
||||
}
|
||||
for token in tokens[..begin].iter().rev() {
|
||||
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
|
||||
return true;
|
||||
@@ -866,7 +869,11 @@ fn is_procedural(tokens: &[Token], offset: u32) -> bool {
|
||||
/// Whether every parenthesis opened between `from` and `at` was closed again.
|
||||
fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
|
||||
let mut depth = 0i32;
|
||||
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
|
||||
// The tokens whose start falls in `[from, at)` are a contiguous run,
|
||||
// because starts rise across the vector — so the filter this replaced was
|
||||
// reading the whole buffer to reach a window the two bounds name outright.
|
||||
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
|
||||
for token in &tokens[window] {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
@@ -898,6 +905,49 @@ module sub #(
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// [`is_procedural`] used to sweep the vector for the token starting at
|
||||
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
|
||||
/// two offsets name. Both now binary-search; both must answer exactly what
|
||||
/// the sweeps answered, at every byte and for every window.
|
||||
#[test]
|
||||
fn the_scope_gates_answer_what_their_sweeps_answered() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
|
||||
let tokens = &doc.tokens;
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = tokens.iter().position(|token| token.span.start == offset);
|
||||
let searched = {
|
||||
let begin = first_token_from(tokens, offset);
|
||||
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
|
||||
};
|
||||
assert_eq!(swept, searched, "the token starting at {offset}");
|
||||
}
|
||||
// Every `begin`/`end` opener in the buffer against a spread of cursors
|
||||
// after it: the two bounds are what pick the window out.
|
||||
let openers: Vec<u32> = tokens
|
||||
.iter()
|
||||
.filter(|t| t.text == "begin" || t.text == "(")
|
||||
.map(|t| t.span.end)
|
||||
.collect();
|
||||
assert!(openers.len() > 20, "premise: plenty of windows to check");
|
||||
for from in openers {
|
||||
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
|
||||
let mut depth = 0i32;
|
||||
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
@@ -948,7 +998,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 +1733,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 +1781,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
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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 = || {
|
||||
|
||||
@@ -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)
|
||||
|
||||
+1096
-25
File diff suppressed because it is too large.
Load diff
@@ -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
@@ -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());
|
||||
|
||||
@@ -281,10 +281,13 @@ fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)>
|
||||
// no trailing newline, nothing typed after it yet — it shares the
|
||||
// trigger token's `span.end`. Skipping it here is what lets a trigger at
|
||||
// the true end of the file still fire (QA find, 2026-08-25).
|
||||
let index = doc
|
||||
.tokens
|
||||
.iter()
|
||||
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset)?;
|
||||
//
|
||||
// Token ends rise across the vector, so the tokens ending at or before
|
||||
// `offset` are a prefix of it: no token outside that prefix could have
|
||||
// satisfied the reverse sweep this replaced, and inside it the sweep's
|
||||
// remaining condition is the `Eof` test alone.
|
||||
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
|
||||
let index = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof)?;
|
||||
let last = doc.tokens.get(index)?;
|
||||
if last.span.end != offset {
|
||||
return None;
|
||||
@@ -412,6 +415,29 @@ mod tests {
|
||||
(ws, uri, position)
|
||||
}
|
||||
|
||||
/// [`triggered`] used to sweep the token vector backwards from its end for
|
||||
/// the last non-`Eof` token ending at or before the cursor. It now bounds
|
||||
/// that sweep with a binary search; the token it lands on must be the same
|
||||
/// one at every byte.
|
||||
#[test]
|
||||
fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc
|
||||
.tokens
|
||||
.iter()
|
||||
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset);
|
||||
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
|
||||
let searched =
|
||||
doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof);
|
||||
assert_eq!(swept, searched, "at offset {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same, in a SystemVerilog buffer.
|
||||
fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) {
|
||||
asking_in("/rtl/top.sv", text, needle)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,15 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
/// An open buffer answers from the line index it already carries; a closed
|
||||
/// file is read and indexed here — which is why a hover that names one file
|
||||
/// twice reads it through the per-request memo in `hover::symbol_hover`, not
|
||||
/// through two calls here.
|
||||
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(doc.line_index.line_col(offset).0);
|
||||
}
|
||||
let text = ws.text_of(path)?;
|
||||
Some(LineIndex::new(&text).line_col(offset).0)
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -28,6 +29,8 @@ mod locate;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
#[cfg(test)]
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod selection;
|
||||
@@ -61,6 +64,8 @@ use lsp_types::{
|
||||
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
};
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
use crate::server::{ClientAbilities, Server};
|
||||
use crate::uri::uri_to_path;
|
||||
|
||||
@@ -72,6 +77,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(¶ms);
|
||||
// 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(¶ms);
|
||||
// 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 +94,23 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
code_lens_refresh: code_lens_refresh_support(¶ms),
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
Server::new(connection, roots, abilities).run()?;
|
||||
// The message loop parses every buffer it is handed, so it does not run
|
||||
// on the main thread: that stack is whatever the OS and `ulimit -s` left
|
||||
// it, and the parser's nesting limit only turns over-deep input into a
|
||||
// diagnostic above `PARSE_STACK_SIZE` (below it the overflow aborts the
|
||||
// whole server, taking the editor session with it). Nothing else here
|
||||
// parses — `lsp-server`'s reader and writer threads move JSON, and the
|
||||
// forwarder in `Server::queue` moves messages.
|
||||
std::thread::Builder::new()
|
||||
.name("lucisv-main".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || Server::new(connection, roots, abilities, storage).run())?
|
||||
.join()
|
||||
.map_err(|_| "the server thread panicked")??;
|
||||
io_threads.join()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -374,6 +396,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 +442,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
|
||||
|
||||
+699
-34
@@ -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};
|
||||
@@ -30,7 +31,19 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
}
|
||||
match path_to_uri_or_self(ws, uri) {
|
||||
Some(target) => {
|
||||
vec![Location { uri: target, range: doc.positions().range(symbol.name_span) }]
|
||||
let positions = doc.positions();
|
||||
// A non-ANSI port's *complete* declaration is the body
|
||||
// `input wire clk;`, so that is where a jump lands first —
|
||||
// the header name it jumped from stays second, exactly the
|
||||
// two sections its hover card shows.
|
||||
let mut locations = Vec::with_capacity(2);
|
||||
if let Some(detail) = symbol.detail_span.filter(|span| !span.is_empty()) {
|
||||
locations
|
||||
.push(Location { uri: target.clone(), range: positions.range(detail) });
|
||||
}
|
||||
locations
|
||||
.push(Location { uri: target, range: positions.range(symbol.name_span) });
|
||||
locations
|
||||
}
|
||||
None => Vec::new(),
|
||||
}
|
||||
@@ -58,17 +71,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 +84,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 +129,204 @@ 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.
|
||||
///
|
||||
/// Shared with `hover.rs`, which walks it the other way round — from an
|
||||
/// indexed `Def` to the live symbol that is it — so a hover snippet is read at
|
||||
/// the declaration's *live* span (`docs/features/hover-declarations/README.md`).
|
||||
pub(crate) fn indexed_def_for_symbol<'a>(
|
||||
ws: &'a Workspace,
|
||||
doc: &Document,
|
||||
offset: u32,
|
||||
symbol: &Symbol,
|
||||
) -> Option<&'a Def> {
|
||||
let file = ws.index().file_id(doc.path.as_deref()?)?;
|
||||
indexed_def_in_file(ws, doc, symbol, file)
|
||||
}
|
||||
|
||||
/// [`indexed_def_for_symbol`] with the document's own [`FileId`] already in
|
||||
/// hand.
|
||||
///
|
||||
/// Split out for `indexed_references`, which asks about every reference in one
|
||||
/// buffer: the path lookup is a binary search whose comparisons are whole path
|
||||
/// `cmp`s, and it answers the same thing for all of them.
|
||||
fn indexed_def_in_file<'a>(
|
||||
ws: &'a Workspace,
|
||||
doc: &Document,
|
||||
symbol: &Symbol,
|
||||
file: vlog_semantic::FileId,
|
||||
) -> Option<&'a Def> {
|
||||
let defs = if symbol.scope == doc.semantics.file_scope() {
|
||||
ws.index().units(&symbol.name)
|
||||
} else {
|
||||
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 };
|
||||
// Every reference in this buffer is answered against the same indexed
|
||||
// file, so the path lookup — a binary search comparing whole paths —
|
||||
// is taken once per buffer rather than once per reference.
|
||||
let file = ws.index().file_id(path);
|
||||
for (id, reference) in doc.semantics.references().iter().enumerate() {
|
||||
// A use can only name `target.def` if it spells the name that
|
||||
// declaration declares, and `target.name` is exactly that name.
|
||||
// One string compare replaces two index lookups and a scope walk
|
||||
// for every *other* name in the buffer, which in a big top is all
|
||||
// but a handful of them. The argument that this changes no answer
|
||||
// is in `docs/features/references-nav/README.md`. The empty-span
|
||||
// check below is deliberately *not* hoisted here: an ambiguous use
|
||||
// aborts the whole collection whether or not it has a span.
|
||||
if reference.name != target.name {
|
||||
continue;
|
||||
}
|
||||
let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) {
|
||||
Some(symbol) => {
|
||||
file.and_then(|file| indexed_def_in_file(ws, doc, symbol, file))
|
||||
== Some(&target.def)
|
||||
}
|
||||
None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) {
|
||||
Some(ExternalTarget::Resolved(def)) => def == &target.def,
|
||||
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(&target.def) => {
|
||||
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| {
|
||||
// Same name-keyed lookup `hover.rs::live_symbol` makes, for
|
||||
// the same reason: only same-named declarations can be this
|
||||
// one, and the order they come in is declaration order either
|
||||
// way, so the first match is unchanged.
|
||||
doc.semantics
|
||||
.symbols_named(&target.name)
|
||||
.filter_map(|id| doc.semantics.symbol(id))
|
||||
.find(|symbol| indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def))
|
||||
.map(|symbol| symbol.name_span)
|
||||
})
|
||||
.unwrap_or(target.declaration_span);
|
||||
found.push((target.declaration_path, span));
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -144,9 +340,14 @@ fn in_file_references(
|
||||
let Some(symbol_id) = symbol_at(&doc.semantics, offset) else { return Vec::new() };
|
||||
let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() };
|
||||
let positions = doc.positions();
|
||||
// `occurrences` sorts, so the spans arrive in the order a walker wants —
|
||||
// the same batch conversion `locations` already does for the cross-file
|
||||
// answer. A signal used ten thousand times in one file is an ordinary
|
||||
// shape, and one-span-at-a-time conversion re-measures a line per span.
|
||||
let mut walker = positions.walker();
|
||||
occurrences(&doc.semantics, symbol_id, include_declaration)
|
||||
.into_iter()
|
||||
.map(|span| Location { uri: target.clone(), range: positions.range(span) })
|
||||
.map(|span| Location { uri: target.clone(), range: walker.range(span) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -168,11 +369,14 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option<Vec<DocumentHi
|
||||
return None;
|
||||
}
|
||||
let positions = doc.positions();
|
||||
// Sorted spans, one walker — see `in_file_references`, which converts the
|
||||
// same list the same way.
|
||||
let mut walker = positions.walker();
|
||||
Some(
|
||||
spans
|
||||
.into_iter()
|
||||
.map(|span| DocumentHighlight {
|
||||
range: positions.range(span),
|
||||
range: walker.range(span),
|
||||
kind: Some(DocumentHighlightKind::TEXT),
|
||||
})
|
||||
.collect(),
|
||||
@@ -214,6 +418,7 @@ fn occurrences(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::perf::mean;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
@@ -309,7 +514,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 +538,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 +560,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 +591,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 +644,334 @@ 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]
|
||||
fn indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member() {
|
||||
// A harder equivalence case than the one above: `W` is a module (a
|
||||
// *unit*, filed in `units`) and, spelled identically, a package
|
||||
// member (filed in `members`) — the prefilter's one string compare
|
||||
// must not let either bucket answer for the other. `top.sv` is also
|
||||
// edited live after opening, so the overlay's answer has to come from
|
||||
// the unsaved buffer, not the file `find_references`'s own oracle
|
||||
// would otherwise re-read from disk.
|
||||
let dir = temp_dir("xrefs_equivalence_unit_and_member");
|
||||
let w_mod = "module W;\nendmodule\n";
|
||||
let w_pkg = "package p;\n localparam W = 4;\nendpackage\n";
|
||||
let top_saved = "module top;\n W u_w ();\n wire [p::W-1:0] x;\nendmodule\n";
|
||||
for (name, text) in [("w.sv", w_mod), ("p.sv", w_pkg), ("top.sv", top_saved)] {
|
||||
fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let top_uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||||
// An unsaved edit: a second live instantiation of `W`, not yet saved.
|
||||
let top_live = "module top;\n W u_w ();\n W u_w2 ();\n wire [p::W-1:0] x;\nendmodule\n";
|
||||
ws.set_document(top_uri, top_live.to_string());
|
||||
let w_uri = path_to_uri(&dir.join("w.sv")).expect("uri");
|
||||
ws.set_document(w_uri.clone(), w_mod.to_string());
|
||||
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
|
||||
ws.set_document(p_uri.clone(), w_pkg.to_string());
|
||||
|
||||
// The module `W`: its declaration and both live instantiations, never
|
||||
// the package member spelled the same way.
|
||||
let module_offset = at(w_mod, "W");
|
||||
let indexed_module = references(&ws, &w_uri, module_offset, true);
|
||||
let walked_module =
|
||||
vlog_refactor::find_references(&ws.sources(), &dir.join("w.sv"), module_offset, true)
|
||||
.expect("the walk answers");
|
||||
assert_eq!(indexed_module, locations(&ws, walked_module));
|
||||
assert_eq!(indexed_module.len(), 3, "declaration + 2 live instantiations, not the member");
|
||||
|
||||
// The package member `W`: its declaration and the one qualified use,
|
||||
// never the module.
|
||||
let member_offset = at(w_pkg, "W");
|
||||
let indexed_member = references(&ws, &p_uri, member_offset, true);
|
||||
let walked_member =
|
||||
vlog_refactor::find_references(&ws.sources(), &dir.join("p.sv"), member_offset, true)
|
||||
.expect("the walk answers");
|
||||
assert_eq!(indexed_member, locations(&ws, walked_member));
|
||||
assert_eq!(indexed_member.len(), 2, "declaration + the one qualified use, not the module");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual indexed-navigation latency probe"]
|
||||
fn qa_indexed_references_latency_over_a_large_workspace() {
|
||||
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);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// latency probes for a big open buffer
|
||||
//
|
||||
// `#[ignore]`d, asserting nothing about duration — the house shape from
|
||||
// `perf.rs`, whose `mean` they borrow so every number in this repo is
|
||||
// taken the same way. The numbers they print are recorded in
|
||||
// `docs/features/references-nav/README.md`.
|
||||
//
|
||||
// cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored \
|
||||
// --nocapture --test-threads=1
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A declaration small enough that nothing about it is the measurement.
|
||||
const PROBE_SUB: &str =
|
||||
"module sub (input logic clk, input logic [31:0] data_in);\nendmodule\n";
|
||||
|
||||
/// A big top level: `blocks` four-line blocks of ordinary RTL — a wire, an
|
||||
/// assign, a register and its update — then `instances` instantiations of
|
||||
/// `sub`. Every block declares two names and uses four, so ten thousand
|
||||
/// blocks is a forty-thousand-line file carrying tens of thousands of
|
||||
/// locally resolved references: exactly the buffer the open-document
|
||||
/// overlay in `indexed_references` has to walk past to answer anything.
|
||||
///
|
||||
/// One `acc` is used by every block, so the file also carries a *local*
|
||||
/// name with thousands of occurrences — the worst case for the in-file
|
||||
/// fallback, which converts one span at a time.
|
||||
///
|
||||
/// Its own generator rather than `perf::generated_module`'s, because that
|
||||
/// one instantiates nothing and a probe about instantiations needs some.
|
||||
fn generated_top(blocks: usize, instances: usize) -> String {
|
||||
let mut src = String::from(
|
||||
"module top (\n input logic clk,\n input logic rst_n,\n \
|
||||
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n \
|
||||
wire acc;\n assign acc = rst_n;\n",
|
||||
);
|
||||
for n in 0..blocks {
|
||||
src.push_str(&format!(
|
||||
" wire [31:0] w_{n};\n \
|
||||
assign w_{n} = data_in ^ {{32{{rst_n}}}} ^ {{32{{acc}}}};\n \
|
||||
reg [31:0] r_{n};\n always @(posedge clk) r_{n} <= w_{n};\n"
|
||||
));
|
||||
}
|
||||
for n in 0..instances {
|
||||
src.push_str(&format!(" sub u_{n} (.clk(clk), .data_in(data_in));\n"));
|
||||
}
|
||||
src.push_str(" assign data_out = data_in;\nendmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// Both directions of a cross-file references request, with a big buffer
|
||||
/// open — the owner's report of 2026-08-28, measured.
|
||||
#[test]
|
||||
#[ignore = "manual references-latency probe — see docs/features/references-nav/README.md"]
|
||||
fn qa_references_latency_with_a_big_open_top() {
|
||||
use std::hint::black_box;
|
||||
|
||||
let dir = temp_dir("refs_big_top");
|
||||
let top_text = generated_top(10_000, 4);
|
||||
let sub_path = dir.join("sub.sv");
|
||||
let top_path = dir.join("top.sv");
|
||||
fs::write(&sub_path, PROBE_SUB).expect("write");
|
||||
fs::write(&top_path, &top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let top_uri = path_to_uri(&top_path).expect("uri");
|
||||
let sub_uri = path_to_uri(&sub_path).expect("uri");
|
||||
ws.set_document(top_uri.clone(), top_text.clone());
|
||||
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
|
||||
|
||||
let use_site = at(&top_text, "sub u_0");
|
||||
let declaration = at(PROBE_SUB, "sub");
|
||||
let local = top_text.rfind("<= w_").expect("a local use") as u32 + 3;
|
||||
let common = top_text.rfind("{32{acc}}").expect("a use of acc") as u32 + 4;
|
||||
let references_in_top =
|
||||
ws.document(&top_uri).map(|doc| doc.semantics.references().len()).expect("top is open");
|
||||
|
||||
// The answers, before any timing: a measurement of a request that
|
||||
// answered nothing is worthless.
|
||||
assert_eq!(references(&ws, &top_uri, use_site, true).len(), 5, "declaration + 4 instances");
|
||||
assert_eq!(references(&ws, &sub_uri, declaration, true).len(), 5, "the same five");
|
||||
assert_eq!(definition(&ws, &top_uri, use_site).len(), 1);
|
||||
assert_eq!(references(&ws, &top_uri, local, true).len(), 3, "one wire, in this file only");
|
||||
assert_eq!(references(&ws, &top_uri, common, true).len(), 10_002, "`acc`, everywhere");
|
||||
|
||||
let runs = 20;
|
||||
let from_use = mean(runs, || {
|
||||
black_box(references(&ws, &top_uri, black_box(use_site), true));
|
||||
});
|
||||
let from_declaration = mean(runs, || {
|
||||
black_box(references(&ws, &sub_uri, black_box(declaration), true));
|
||||
});
|
||||
let to_definition = mean(runs, || {
|
||||
black_box(definition(&ws, &top_uri, black_box(use_site)));
|
||||
});
|
||||
let in_file = mean(runs, || {
|
||||
black_box(references(&ws, &top_uri, black_box(local), true));
|
||||
});
|
||||
let in_file_common = mean(runs, || {
|
||||
black_box(references(&ws, &top_uri, black_box(common), true));
|
||||
});
|
||||
let highlights = mean(runs, || {
|
||||
let doc = ws.document(&top_uri).expect("open");
|
||||
black_box(document_highlights(doc, black_box(common)));
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"big open top ({} KB, {references_in_top} references): \
|
||||
references from the use site {from_use:?}, \
|
||||
from the declaration {from_declaration:?}, \
|
||||
definition from the use site {to_definition:?}, \
|
||||
references on a local wire used 3× (the in-file fallback) {in_file:?}, \
|
||||
on one used 10 001× {in_file_common:?}, \
|
||||
documentHighlight on that one {highlights:?}",
|
||||
top_text.len() / 1000,
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The other half of the owner's report: what jumping *into* a file costs
|
||||
/// when the folder it lives in was not in the index's scope yet.
|
||||
#[test]
|
||||
#[ignore = "manual didOpen/scope-widening latency probe — see docs/features/references-nav/README.md"]
|
||||
fn qa_didopen_latency_when_a_new_folder_widens_the_scope() {
|
||||
use std::hint::black_box;
|
||||
|
||||
let dir = temp_dir("didopen_scope");
|
||||
fs::create_dir_all(dir.join("rtl")).expect("rtl dir");
|
||||
fs::create_dir_all(dir.join("lib")).expect("lib dir");
|
||||
for n in 0..400 {
|
||||
fs::write(
|
||||
dir.join("rtl").join(format!("m{n}.sv")),
|
||||
format!("module m{n};\n wire w;\n assign w = 1'b0;\nendmodule\n"),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
fs::write(dir.join("lib").join("sub.sv"), PROBE_SUB).expect("write");
|
||||
let top_text = generated_top(10_000, 4);
|
||||
let top_path = dir.join("rtl").join("top.sv");
|
||||
fs::write(&top_path, &top_text).expect("write");
|
||||
|
||||
// The default rung: the folder scope. Nothing is in scope until a
|
||||
// buffer is opened, so the first `didOpen` is itself a widening.
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let top_uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(top_uri.clone(), top_text.clone());
|
||||
ws.rebuild_index();
|
||||
let covered = ws.index().files().len();
|
||||
|
||||
// A `didOpen` the scope already covers: one `Document::new` and a
|
||||
// publish, and `server.rs` runs no rescan at all.
|
||||
let sibling = dir.join("rtl").join("m0.sv");
|
||||
let sibling_uri = path_to_uri(&sibling).expect("uri");
|
||||
let sibling_text = fs::read_to_string(&sibling).expect("read");
|
||||
let inside = mean(20, || {
|
||||
ws.set_document(sibling_uri.clone(), sibling_text.clone());
|
||||
});
|
||||
|
||||
// A `didOpen` in a folder the scope does not cover: the same
|
||||
// `Document::new`, and then the whole rescan `server.rs` runs when
|
||||
// `scope_dirs()` moved — which re-reads and re-parses every file in
|
||||
// the widened scope. Until 2026-08-28 the open big buffer was one of
|
||||
// them; it now goes in from the analysis it already holds, which is
|
||||
// what the last two pairs of numbers below are about
|
||||
// (`docs/features/index-scope/README.md`).
|
||||
let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri");
|
||||
let widening = mean(5, || {
|
||||
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
|
||||
black_box(ws.rebuild_index());
|
||||
});
|
||||
let rescan = mean(5, || {
|
||||
black_box(ws.rebuild_index());
|
||||
});
|
||||
// Where the buffer's share goes, on the same buffer: what a rescan
|
||||
// used to pay for one open file — a whole parse for the index facts,
|
||||
// then a second lex for the completion words — against what it pays
|
||||
// since 2026-08-28, which is the two walks over the analysis and the
|
||||
// token stream the buffer already holds.
|
||||
let (reparse, reused, relex, rewords) = {
|
||||
let doc = ws.document(&top_uri).expect("open");
|
||||
(
|
||||
mean(3, || {
|
||||
black_box(vlog_semantic::FileFacts::of(top_path.clone(), &top_text));
|
||||
}),
|
||||
mean(3, || {
|
||||
black_box(doc.facts(top_path.clone()));
|
||||
}),
|
||||
mean(3, || {
|
||||
let tokens = vlog_parser::tokenize(&top_text).expect("it lexes");
|
||||
black_box(crate::candidates::words_of_tokens(&tokens));
|
||||
}),
|
||||
mean(3, || {
|
||||
black_box(doc.words());
|
||||
}),
|
||||
)
|
||||
};
|
||||
|
||||
// The same rescan with the big buffer closed, so its share of the
|
||||
// rescan is a subtraction rather than a guess.
|
||||
ws.close_document(&top_uri);
|
||||
let without = mean(5, || {
|
||||
black_box(ws.rebuild_index());
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"didOpen with a {} KB buffer already open, {covered} files in scope: \
|
||||
a file the scope already covers {inside:?}; \
|
||||
one in a new folder (didOpen + rescan) {widening:?}; \
|
||||
the rescan alone {rescan:?}, and {without:?} with the big buffer closed. \
|
||||
That buffer's own share: facts {reparse:?} parsed vs {reused:?} reused, \
|
||||
words {relex:?} re-lexed vs {rewords:?} reused",
|
||||
top_text.len() / 1000,
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn include_declaration_drops_the_declaration_and_nothing_else() {
|
||||
let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv");
|
||||
@@ -460,7 +993,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 +1022,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 +1050,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 +1079,138 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_named_port_in_another_open_buffer_is_a_different_symbol() {
|
||||
// The name prefilter's risk case, asserted from both sides: two
|
||||
// modules declare a port `clk`, both files are open, and each port's
|
||||
// references are its own. A prefilter that let a spelling stand in for
|
||||
// an identity would merge these two answers.
|
||||
let dir = temp_dir("xrefs_same_name");
|
||||
let sub = "module sub (input logic clk);\nendmodule\n";
|
||||
let top = "module top;\n sub u_a (.clk(1'b0));\nendmodule\n";
|
||||
let other = "module other (input logic clk);\n wire w;\n assign w = clk;\nendmodule\n";
|
||||
for (name, text) in [("sub.sv", sub), ("top.sv", top), ("other.sv", other)] {
|
||||
fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let mut uri_of = |name: &str, text: &str| {
|
||||
let uri = path_to_uri(&dir.join(name)).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
uri
|
||||
};
|
||||
let sub_uri = uri_of("sub.sv", sub);
|
||||
uri_of("top.sv", top);
|
||||
let other_uri = uri_of("other.sv", other);
|
||||
|
||||
assert_eq!(
|
||||
places(&references(&ws, &sub_uri, at(sub, "clk"), true)),
|
||||
vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)],
|
||||
"`sub`'s port: its declaration and the connection to it"
|
||||
);
|
||||
assert_eq!(
|
||||
places(&references(&ws, &other_uri, at(other, "clk"), true)),
|
||||
vec![("other.sv".to_string(), 0), ("other.sv".to_string(), 2)],
|
||||
"`other`'s port: its declaration and its own use"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_packages_declaring_one_name_keep_their_references_apart() {
|
||||
// The same attack through the member table rather than the port table:
|
||||
// `p::WIDTH` and `q::WIDTH` spell one name and are two declarations,
|
||||
// and the file using both is open.
|
||||
let dir = temp_dir("xrefs_two_packages");
|
||||
let p = "package p;\n localparam WIDTH = 8;\nendpackage\n";
|
||||
let q = "package q;\n localparam WIDTH = 16;\nendpackage\n";
|
||||
let a = "module a;\n wire [p::WIDTH-1:0] x;\n wire [q::WIDTH-1:0] y;\nendmodule\n";
|
||||
for (name, text) in [("p.sv", p), ("q.sv", q), ("a.sv", a)] {
|
||||
fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri");
|
||||
ws.set_document(a_uri.clone(), a.to_string());
|
||||
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
|
||||
ws.set_document(p_uri.clone(), p.to_string());
|
||||
|
||||
assert_eq!(
|
||||
places(&references(&ws, &p_uri, at(p, "WIDTH"), true)),
|
||||
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)],
|
||||
"`p`'s WIDTH only — `q::WIDTH` on the next line is another symbol"
|
||||
);
|
||||
// And from the use side, the same set.
|
||||
assert_eq!(
|
||||
places(&references(&ws, &a_uri, at(a, "p::WIDTH") + 3, true)),
|
||||
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)]
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_in_file_occurrence_is_converted_against_its_own_line() {
|
||||
// The in-file fallback converts its spans with one walker now. A
|
||||
// walker handed an out-of-order span answers a stale column, so the
|
||||
// shape that would catch it: many occurrences, each on a line with a
|
||||
// wide character before it, plus one on the same line as another.
|
||||
let mut text = String::from("module m;\n wire a;\n");
|
||||
for n in 0..20 {
|
||||
text.push_str(&format!(" // é 🎉 {n}\n assign b{n} = a + a;\n"));
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
let (ws, uri) = document(&text);
|
||||
let found = references(&ws, &uri, at(&text, "wire a") + 5, true);
|
||||
assert_eq!(found.len(), 41, "the declaration and two uses per block");
|
||||
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let positions = doc.positions();
|
||||
for location in &found {
|
||||
let line = location.range.start.line as usize;
|
||||
let offset = positions.offset(location.range.start);
|
||||
assert_eq!(
|
||||
text.get(offset as usize..offset as usize + 1),
|
||||
Some("a"),
|
||||
"line {line} must point at the name"
|
||||
);
|
||||
assert_eq!(location.range.end.character, location.range.start.character + 1);
|
||||
}
|
||||
|
||||
// documentHighlight walks the same list and must agree with it.
|
||||
let highlights = document_highlights(doc, at(&text, "wire a") + 5).expect("a symbol");
|
||||
let ranges: Vec<_> = highlights.iter().map(|h| h.range).collect();
|
||||
assert_eq!(ranges, found.iter().map(|l| l.range).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() {
|
||||
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv");
|
||||
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 +1280,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());
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ use vlog_parser::token::{Token, TokenKind};
|
||||
|
||||
use crate::format;
|
||||
use crate::pairs;
|
||||
use crate::state::Document;
|
||||
use crate::state::{first_token_from, first_token_reaching, Document};
|
||||
|
||||
/// The character the client is told to trigger on. A newline is the one
|
||||
/// keystroke that opens a line whose indentation nobody has chosen yet.
|
||||
@@ -71,8 +71,14 @@ fn statement_edit(doc: &Document, position: Position, config: &Config) -> Option
|
||||
let offset = doc.positions().offset(position);
|
||||
// The character the client named has to actually be there, and it has to
|
||||
// be a `;` the lexer sees: one inside a string or a comment ends no
|
||||
// statement, and re-laying-out its line would be a guess.
|
||||
let typed = doc.tokens.iter().find(|token| token.span.end == offset)?;
|
||||
// statement, and re-laying-out its line would be a guess. A token that
|
||||
// ends exactly at `offset` is the first one that *reaches* it — everything
|
||||
// before ends earlier, everything after ends later — so a binary search
|
||||
// finds what the sweep this replaced found.
|
||||
let typed = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|t| t.span.end == offset)?;
|
||||
if !typed.is_sym(SEMICOLON) {
|
||||
return None;
|
||||
}
|
||||
@@ -264,9 +270,12 @@ fn inside_a_comment(token: &Token, at: u32) -> bool {
|
||||
/// line the user has just opened has none.
|
||||
fn first_on_line(doc: &Document, content: u32) -> Option<&Token> {
|
||||
let line = doc.line_index.line_col(content).0;
|
||||
doc.tokens
|
||||
// Every token before this index starts before `content`, so none of them
|
||||
// could have satisfied the sweep this replaced; within the tail the sweep's
|
||||
// remaining condition is the `Eof` test alone.
|
||||
doc.tokens[first_token_from(&doc.tokens, content)..]
|
||||
.iter()
|
||||
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
|
||||
.find(|token| token.kind != TokenKind::Eof)
|
||||
.filter(|token| doc.line_index.line_col(token.span.start).0 == line)
|
||||
}
|
||||
|
||||
@@ -646,6 +655,43 @@ mod tests {
|
||||
f(ws.document(&uri).expect("open"))
|
||||
}
|
||||
|
||||
/// The `;` handler used to sweep the token vector for the token ending at
|
||||
/// the cursor. Every byte of a buffer full of touching tokens must still
|
||||
/// name the same token — or no token, where the sweep found none.
|
||||
#[test]
|
||||
fn the_token_ending_at_the_cursor_is_the_one_the_sweep_returned() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
with(&text, |doc| {
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc.tokens.iter().find(|token| token.span.end == offset);
|
||||
let searched = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|t| t.span.end == offset);
|
||||
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The same, for the indent handler's "first token at or after this byte":
|
||||
/// [`first_on_line`] is compared against the sweep it was written as.
|
||||
#[test]
|
||||
fn the_first_token_on_a_line_is_the_one_the_sweep_returned() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
with(&text, |doc| {
|
||||
for content in 0..=text.len() as u32 {
|
||||
let line = doc.line_index.line_col(content).0;
|
||||
let swept = doc
|
||||
.tokens
|
||||
.iter()
|
||||
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
|
||||
.filter(|token| doc.line_index.line_col(token.span.start).0 == line);
|
||||
let searched = first_on_line(doc, content);
|
||||
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at byte {content}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn config(indent_width: usize) -> Config {
|
||||
Config { indent_width, ..Config::default() }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
//! Perf measurements for the paths a keystroke and a hover run through.
|
||||
//!
|
||||
//! Not a benchmark harness: every test here is `#[ignore]`d, asserts nothing
|
||||
//! about how long anything took, and exists only to print a number an agent
|
||||
//! can compare against the numbers recorded in `docs/perf/README.md`. The
|
||||
//! shape is the one the hover QA round already used — `Instant` plus
|
||||
//! `eprintln!` — because a real benchmark crate would be a new dependency,
|
||||
//! and a dependency needs a written justification this does not have.
|
||||
//!
|
||||
//! Run them all with:
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo test --release -p lucisv_server perf:: -- --ignored --nocapture \
|
||||
//! --test-threads=1
|
||||
//! ```
|
||||
//!
|
||||
//! `--test-threads=1` is not optional: the default harness runs these tests
|
||||
//! concurrently with each other and with the rest of the suite, and a
|
||||
//! measurement taken while three other tests fight it for a core is noise.
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vlog_parser::defines::collect_defines;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
|
||||
use vlog_semantic::{analyze, resolve_external, WorkspaceIndex};
|
||||
|
||||
use crate::hover::hover;
|
||||
use crate::state::{first_token_from, first_token_reaching, Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// The two input sizes every measurement is taken at: a large-ish real module
|
||||
/// and a file nobody enjoys opening.
|
||||
const SIZES: [usize; 2] = [1_000, 10_000];
|
||||
|
||||
/// A generated module of about `lines` lines: an ANSI header, then repeated
|
||||
/// four-line blocks of the shapes RTL is mostly made of — a wire, an assign, a
|
||||
/// register and its update. Every block declares two names and uses four, so
|
||||
/// what is measured is ordinary declaration and resolution work rather than
|
||||
/// one pathological construct.
|
||||
fn generated_module(name: &str, lines: usize) -> String {
|
||||
let mut src = format!(
|
||||
"module {name} (\n input logic clk,\n input logic rst_n,\n \
|
||||
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n"
|
||||
);
|
||||
for n in 0..lines.saturating_sub(8) / 4 {
|
||||
src.push_str(&format!(
|
||||
" wire [31:0] w_{n};\n \
|
||||
assign w_{n} = data_in ^ {{32{{rst_n}}}};\n \
|
||||
reg [31:0] r_{n};\n \
|
||||
always @(posedge clk) r_{n} <= w_{n};\n"
|
||||
));
|
||||
}
|
||||
src.push_str(" assign data_out = data_in;\nendmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// The mean of `runs` runs. One run of a millisecond-scale operation is mostly
|
||||
/// scheduling noise; a mean of a handful is the number worth writing down.
|
||||
///
|
||||
/// `pub(crate)` so the probes that live beside the code they measure —
|
||||
/// `nav.rs`'s references-latency probes — time themselves the same way these
|
||||
/// do, rather than each growing its own stopwatch.
|
||||
pub(crate) fn mean(runs: u32, mut body: impl FnMut()) -> Duration {
|
||||
let start = Instant::now();
|
||||
for _ in 0..runs {
|
||||
body();
|
||||
}
|
||||
start.elapsed() / runs
|
||||
}
|
||||
|
||||
/// A scratch directory holding the generated files a measurement needs,
|
||||
/// removed when the measurement is done.
|
||||
fn scratch(tag: &str, files: &[(&str, &str)]) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_{tag}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
for (name, text) in files {
|
||||
std::fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::analyzing -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn analyzing_a_generated_module() {
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let (tree, _) = parse_source_tolerant(&src);
|
||||
let took = mean(10, || {
|
||||
black_box(analyze(black_box(&tree), black_box(&src)));
|
||||
});
|
||||
let symbols = analyze(&tree, &src).symbols().len();
|
||||
eprintln!(
|
||||
"analyze: {lines} lines ({} KB, {symbols} symbols) took {took:?}",
|
||||
src.len() / 1000
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::opening -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn opening_a_buffer_end_to_end() {
|
||||
// What one flushed keystroke costs: lex, parse, analyze, resolve against
|
||||
// the index. The index holds the same file, so `resolve_external` has
|
||||
// something real to answer from rather than an empty table.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let path = PathBuf::from("gen.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), src.as_str())]);
|
||||
let took = mean(10, || {
|
||||
black_box(Document::new(Some(path.clone()), src.clone(), &index));
|
||||
});
|
||||
eprintln!("Document::new: {lines} lines ({} KB) took {took:?}", src.len() / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::breaking_down -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn breaking_down_one_flushed_keystroke() {
|
||||
// `opening_a_buffer_end_to_end` says what a flush costs; this says where
|
||||
// that cost is, stage by stage, in the order `Document::new` runs them —
|
||||
// plus the diagnostics pass, which is *not* inside `Document::new` but
|
||||
// runs on every publish, so a flush is the sum of the two.
|
||||
//
|
||||
// `parse_tolerant` consumes its token vector, so each run of the parse
|
||||
// needs a fresh clone; the clone is measured on its own line and the parse
|
||||
// line is reported with the clone still in it. Subtracting one from the
|
||||
// other is the honest reading, and it is what `Document::new` really pays.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let path = PathBuf::from("gen.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), src.as_str())]);
|
||||
let tokens = tokenize(&src).expect("the generated module lexes");
|
||||
let (tree, _) = parse_tolerant(tokens.clone(), &src);
|
||||
let semantics = analyze(&tree, &src);
|
||||
let doc = Document::new(Some(path.clone()), src.clone(), &index);
|
||||
|
||||
let lex = mean(20, || {
|
||||
black_box(tokenize(black_box(&src)).is_ok());
|
||||
});
|
||||
let clone = mean(20, || {
|
||||
black_box(tokens.clone());
|
||||
});
|
||||
let parse = mean(20, || {
|
||||
black_box(parse_tolerant(black_box(tokens.clone()), black_box(&src)));
|
||||
});
|
||||
let defines = mean(200, || {
|
||||
black_box(collect_defines(black_box(&tokens)));
|
||||
});
|
||||
let analyzing = mean(20, || {
|
||||
black_box(analyze(black_box(&tree), black_box(&src)));
|
||||
});
|
||||
let external = mean(200, || {
|
||||
black_box(resolve_external(black_box(&semantics), black_box(&index)));
|
||||
});
|
||||
let line_index = mean(200, || {
|
||||
black_box(LineIndex::new(black_box(&src)));
|
||||
});
|
||||
let lint = mean(20, || {
|
||||
black_box(crate::diagnostics::all(black_box(&doc)));
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"flush breakdown, {lines} lines ({} tokens): tokenize {lex:?}, \
|
||||
tokens.clone() {clone:?}, parse_tolerant (clone included) {parse:?}, \
|
||||
collect_defines {defines:?}, analyze {analyzing:?}, \
|
||||
resolve_external {external:?}, LineIndex::new {line_index:?}, \
|
||||
diagnostics::all {lint:?}",
|
||||
tokens.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::finding_one_token -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn finding_one_token_against_sweeping_the_stream() {
|
||||
// The before/after of the interactive handlers' token lookups, on the
|
||||
// lookup alone. Both halves run in the same measurement, against the same
|
||||
// stream, so neither number depends on remembering an earlier run.
|
||||
//
|
||||
// The cursor sits three quarters of the way down the file. A sweep costs
|
||||
// the distance from token zero, so measuring at the top would flatter it
|
||||
// and measuring at the very end would flatter it in the other direction;
|
||||
// three quarters is an ordinary place for a cursor to be.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let tokens = tokenize(&src).expect("the generated module lexes");
|
||||
let at = tokens[tokens.len() * 3 / 4].span.start;
|
||||
|
||||
// `selection.rs`: the innermost step of an expand-selection chain.
|
||||
let covers = |span: vlog_parser::TextRange| span.start <= at && at <= span.end;
|
||||
let sweep = mean(1_000, || {
|
||||
black_box(tokens.iter().find(|t| covers(t.span)).map(|t| t.span));
|
||||
});
|
||||
let search = mean(1_000, || {
|
||||
black_box(
|
||||
tokens.get(first_token_reaching(&tokens, black_box(at))).filter(|t| covers(t.span)),
|
||||
);
|
||||
});
|
||||
|
||||
// `completion.rs`: the balanced-parenthesis window between an opener
|
||||
// and the cursor. This one swept the *whole* stream — the filter has
|
||||
// no upper bound to break on — to reach a window two offsets name.
|
||||
let from = tokens[tokens.len() / 2].span.end;
|
||||
let window_sweep = mean(1_000, || {
|
||||
black_box(tokens.iter().filter(|t| t.span.start >= from && t.span.start < at).count());
|
||||
});
|
||||
let window_search = mean(1_000, || {
|
||||
let window = first_token_from(&tokens, black_box(from))..first_token_from(&tokens, at);
|
||||
black_box(tokens[window].len());
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"one token among {}: sweeping {sweep:?}, binary search {search:?}; \
|
||||
the balanced-paren window: sweeping {window_sweep:?}, \
|
||||
binary search {window_search:?}",
|
||||
tokens.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::hovering_a_local -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn hovering_a_local_declaration() {
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let dir = scratch(&format!("local{lines}"), &[("gen.sv", src.as_str())]);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&dir.join("gen.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), src.clone());
|
||||
// The last block's `w_n` use, so the answer is as far into the file as
|
||||
// this file goes.
|
||||
let offset = src.rfind("<= w_").expect("a use") as u32 + 4;
|
||||
let took = mean(20, || {
|
||||
black_box(hover(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
assert!(hover(&ws, &uri, offset).is_some(), "the offset must be a name");
|
||||
eprintln!("hover, local target: {lines} lines took {took:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::hovering_across -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn hovering_across_files_into_a_closed_file() {
|
||||
// The disk path: the target file is closed, so the card's heading line and
|
||||
// its snippet both come out of one read (`hover::disk_view`). The second
|
||||
// read that memo removed is measured beside it — it is the whole file
|
||||
// again, plus a whole `LineIndex` again.
|
||||
for lines in SIZES {
|
||||
let sub = generated_module("sub", lines);
|
||||
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
|
||||
let dir = scratch(&format!("cross{lines}"), &[("sub.sv", sub.as_str()), ("top.sv", top)]);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = top.find("data_in(").expect("a port connection") as u32;
|
||||
let took = mean(20, || {
|
||||
black_box(hover(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
let path = dir.join("sub.sv");
|
||||
let one_read = mean(20, || {
|
||||
let text = ws.text_of(black_box(&path)).expect("readable");
|
||||
black_box(LineIndex::new(&text));
|
||||
});
|
||||
// The card really is the cross-file one, read off that file's disk
|
||||
// text — a measurement of a hover that answered nothing is worthless.
|
||||
let card = hover(&ws, &uri, offset).expect("a cross-file card");
|
||||
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
|
||||
eprintln!(
|
||||
"hover, closed cross-file target: {lines} lines took {took:?} \
|
||||
(one read + LineIndex of that file: {one_read:?}, which is what the memo saves)"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::reindexing -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn reindexing_one_changed_file() {
|
||||
// What a save costs the index: one file re-parsed and merged, against a
|
||||
// workspace of twenty files of the same size.
|
||||
for lines in SIZES {
|
||||
let sources: Vec<(PathBuf, String)> = (0..20)
|
||||
.map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), lines)))
|
||||
.collect();
|
||||
let index = WorkspaceIndex::build(
|
||||
sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::<Vec<_>>(),
|
||||
);
|
||||
let (path, src) = &sources[7];
|
||||
let took = mean(10, || {
|
||||
let mut index = index.clone();
|
||||
index.update_file(black_box(path.clone()), black_box(src));
|
||||
black_box(index);
|
||||
});
|
||||
let clone = mean(10, || {
|
||||
black_box(index.clone());
|
||||
});
|
||||
eprintln!(
|
||||
"WorkspaceIndex::update_file: 20 files of {lines} lines took {took:?} \
|
||||
(of which {clone:?} is the clone this measurement needs to repeat itself)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::looking_up -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn looking_up_one_name_against_scanning_every_symbol() {
|
||||
// The before/after of the name-keyed lookup, on the lookup alone. What
|
||||
// `hover::live_symbol` actually saves is larger: every symbol the scan
|
||||
// used to reach and reject by name is also an `indexed_def_for_symbol`
|
||||
// call it no longer makes — two index lookups apiece.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let (tree, _) = parse_source_tolerant(&src);
|
||||
let semantics = analyze(&tree, &src);
|
||||
let name = format!("w_{}", lines / 8);
|
||||
let scan = mean(1_000, || {
|
||||
let name = black_box(name.as_str());
|
||||
black_box(semantics.symbols().iter().filter(|s| s.name == name).count());
|
||||
});
|
||||
let keyed = mean(1_000, || {
|
||||
black_box(semantics.symbols_named(black_box(&name)).count());
|
||||
});
|
||||
eprintln!(
|
||||
"one name among {} symbols: scanning {scan:?}, keyed lookup {keyed:?}",
|
||||
semantics.symbols().len()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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![
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -13,7 +13,7 @@ use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind}
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::pairs::analyze;
|
||||
use crate::state::Document;
|
||||
use crate::state::{first_token_reaching, Document};
|
||||
|
||||
/// One chain per requested position, in the order they were asked for.
|
||||
///
|
||||
@@ -41,7 +41,17 @@ fn chain(doc: &Document, offset: u32) -> SelectionRange {
|
||||
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
|
||||
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
|
||||
let mut spans = Vec::new();
|
||||
if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) {
|
||||
// The first token that reaches `offset` is the first that can cover it,
|
||||
// and — because the tokens after it all start no earlier — the only one
|
||||
// the sweep this replaced could ever have returned. Note that `covers`
|
||||
// takes `span.end` inclusively, so this is deliberately *not*
|
||||
// `Document::token_at`: at a byte two adjacent tokens share, the sweep
|
||||
// answered with the earlier one and so does this.
|
||||
if let Some(token) = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|token| covers(token.span, offset))
|
||||
{
|
||||
spans.push(token.span);
|
||||
}
|
||||
items(&doc.tree.items, offset, &mut spans);
|
||||
@@ -219,6 +229,26 @@ mod tests {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
/// The innermost step of a chain used to come from a sweep of the whole
|
||||
/// token vector; it now comes from a binary search. `covers` takes
|
||||
/// `span.end` inclusively, so at a byte two adjacent tokens share the
|
||||
/// sweep answered with the earlier of the two — this pins that the search
|
||||
/// answers with the earlier one too, at every byte of a buffer written to
|
||||
/// have plenty of them.
|
||||
#[test]
|
||||
fn the_innermost_step_is_the_token_the_sweep_returned_at_every_offset() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let doc = doc_of(&text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc.tokens.iter().find(|token| covers(token.span, offset));
|
||||
let searched = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|token| covers(token.span, offset));
|
||||
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The chain for the first occurrence of `needle`, as the source text of
|
||||
/// each step, innermost first.
|
||||
fn steps(text: &str, needle: &str) -> Vec<String> {
|
||||
|
||||
+2039
-133
File diff suppressed because it is too large.
Load diff
@@ -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(§ion);
|
||||
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" } }));
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2628
-81
File diff suppressed because it is too large.
Load diff
@@ -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();
|
||||
|
||||
@@ -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`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
@@ -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())
|
||||
@@ -2184,13 +2221,27 @@ impl Live {
|
||||
panic!("the server never said what was waited for; it said {seen:#?}");
|
||||
}
|
||||
|
||||
fn finish(mut self) {
|
||||
/// Shut the session down, and say how many `publishDiagnostics` arrived
|
||||
/// on the way out.
|
||||
///
|
||||
/// The count is what lets a measurement tell one flush from ten: a
|
||||
/// buffer left dirty by a burst is flushed before the next *request* is
|
||||
/// answered, so every publish a burst was going to produce has arrived by
|
||||
/// the time `shutdown` comes back. Most callers ignore the number.
|
||||
fn finish(mut self) -> usize {
|
||||
let published = std::cell::Cell::new(0usize);
|
||||
self.send(r#"{"jsonrpc":"2.0","id":99,"method":"shutdown","params":null}"#);
|
||||
self.wait_for(|m| m["id"] == 99);
|
||||
self.wait_for(|m| {
|
||||
if m["method"] == "textDocument/publishDiagnostics" {
|
||||
published.set(published.get() + 1);
|
||||
}
|
||||
m["id"] == 99
|
||||
});
|
||||
self.send(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#);
|
||||
drop(self.stdin);
|
||||
let status = self.child.wait().expect("the server exits");
|
||||
assert!(status.success(), "clean exit, got {status:?}");
|
||||
published.get()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2664,6 +2715,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 +2745,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")
|
||||
@@ -3016,22 +3069,22 @@ fn incremental_changes_are_advertised_and_applied_over_the_wire() {
|
||||
assert_eq!(sync["openClose"], true, "{sync:#?}");
|
||||
assert_eq!(sync["save"]["includeText"], false, "a save re-sends nothing: {sync:#?}");
|
||||
|
||||
// 2. Each notification published once, and what it published describes
|
||||
// the composed buffer: the error is on the line the third range
|
||||
// inserted, and it clears when the fourth range finishes that line.
|
||||
// 2. The changes were coalesced: both notifications arrived before
|
||||
// anything needed their analysis, so one flush published the composed
|
||||
// buffer once — clean, because the fourth range finished the line the
|
||||
// third inserted. An intermediate publish of the broken half-state is
|
||||
// what the change debounce removed; what is drawn is always a state
|
||||
// the buffer actually passed through, just fewer of them.
|
||||
let published: Vec<_> =
|
||||
messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect();
|
||||
assert_eq!(published.len(), 3, "one per notification, not one per range: {published:#?}");
|
||||
assert_eq!(published.len(), 2, "one for the open, one for the flushed changes: {published:#?}");
|
||||
assert!(
|
||||
published[0]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"the file opened clean: {published:#?}"
|
||||
);
|
||||
let diagnostics = published[1]["params"]["diagnostics"].as_array().expect("an array");
|
||||
assert_eq!(diagnostics.len(), 1, "{diagnostics:#?}");
|
||||
assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the inserted line");
|
||||
assert!(
|
||||
published[2]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"and the next range fixed it: {published:#?}"
|
||||
published[1]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"and the composed buffer is clean: {published:#?}"
|
||||
);
|
||||
|
||||
// 3. And the buffer the server holds is exactly the composed text — read
|
||||
@@ -3205,8 +3258,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 +3274,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 +3294,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 +3310,179 @@ 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 qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan() {
|
||||
// QA attack (index-scope, 2026-08-28, charter item 5). No e2e test
|
||||
// exercised the real `analyzed: <path>` log line at all before this one —
|
||||
// `state.rs`'s unit tests only ever check the `IndexEvent::Analyzed`
|
||||
// variant, never the formatted string a real client would see over
|
||||
// `window/logMessage`. Two claims: the widening `didOpen`'s rescan logs
|
||||
// `analyzed:` for the open buffer and `indexing:` (never `analyzed:`) for
|
||||
// the file that is only ever on disk; and the follow-up `didSave` — the
|
||||
// incremental one-file path — sends no log line at all, so `analyzed:`
|
||||
// cannot leak onto a request that was never a scan.
|
||||
let dir = temp_dir("analyzedword");
|
||||
std::fs::write(
|
||||
dir.join("disk_only.sv"),
|
||||
"package disk_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
)
|
||||
.expect("write");
|
||||
let file = dir.join("m.sv");
|
||||
let source = "module m;\nendmodule\n";
|
||||
std::fs::write(&file, source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(source).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let logged: Vec<&str> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "window/logMessage")
|
||||
.filter_map(|m| m["params"]["message"].as_str())
|
||||
.collect();
|
||||
|
||||
// The `didOpen` rescan: the open buffer's own analysis, the disk file
|
||||
// parsed.
|
||||
assert!(
|
||||
logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("m.sv")),
|
||||
"the open buffer must be logged `analyzed:`: {logged:?}"
|
||||
);
|
||||
assert!(
|
||||
logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("disk_only.sv")),
|
||||
"the disk-only file must still be logged `indexing:`: {logged:?}"
|
||||
);
|
||||
assert!(
|
||||
!logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("disk_only.sv")),
|
||||
"a file with no open buffer is never `analyzed:`: {logged:?}"
|
||||
);
|
||||
assert!(
|
||||
!logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("m.sv")),
|
||||
"the open buffer is not reparsed, so it is never `indexing:`: {logged:?}"
|
||||
);
|
||||
|
||||
// The `didSave` afterwards names one file the index already holds, so it
|
||||
// takes the incremental `reindex_one` path — which the work log states
|
||||
// sends no per-file log line at all. Confirmed here rather than assumed:
|
||||
// there is exactly one `didOpen`-rescan's worth of log lines and nothing
|
||||
// from the save.
|
||||
assert_eq!(
|
||||
logged
|
||||
.iter()
|
||||
.filter(|l| l.starts_with("analyzed: ") || l.starts_with("indexing: "))
|
||||
.count(),
|
||||
2,
|
||||
"one line for each of the two files, from the rescan alone: {logged:?}"
|
||||
);
|
||||
|
||||
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 +3900,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 +4054,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 +4087,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 +4142,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 +4214,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 +4336,492 @@ 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);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Interactive latency — a measurement, not an assertion
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// `docs/perf/README.md` records what one flush costs by calling the pieces
|
||||
// directly. What it could not record from inside the crate is the number a
|
||||
// user actually feels: the wall time from the `didChange` an editor sends on
|
||||
// a keystroke to the `publishDiagnostics` that redraws the squiggles. That
|
||||
// round trip crosses two pipes, a JSON encoder and decoder, the change
|
||||
// debounce's quiet-period timer and a whole `Document::new`, and only a
|
||||
// session against the real binary can time it.
|
||||
//
|
||||
// Like every measurement in `crates/lucisv_server/src/perf.rs` this asserts
|
||||
// nothing about duration — a test that fails when the machine is busy is a
|
||||
// test that gets deleted — and is `#[ignore]`d so an ordinary `cargo test`
|
||||
// never pays for it.
|
||||
|
||||
/// A generated module of about `lines` lines, ending in a comment line for
|
||||
/// keystrokes to land on.
|
||||
///
|
||||
/// A copy of `perf::generated_module`, because `lucisv_server` is a binary
|
||||
/// crate and an integration test cannot reach into its modules. The two
|
||||
/// differ in one line only — the trailing `// typing` comment this version
|
||||
/// adds for a keystroke to land on, which is trivia and not a token — and
|
||||
/// they must stay that close, or the two tables in `docs/perf/README.md`
|
||||
/// stop being readable against one another.
|
||||
fn generated_module(name: &str, lines: usize) -> String {
|
||||
let mut src = format!(
|
||||
"module {name} (\n input logic clk,\n input logic rst_n,\n \
|
||||
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n"
|
||||
);
|
||||
for n in 0..lines.saturating_sub(8) / 4 {
|
||||
src.push_str(&format!(
|
||||
" wire [31:0] w_{n};\n \
|
||||
assign w_{n} = data_in ^ {{32{{rst_n}}}};\n \
|
||||
reg [31:0] r_{n};\n \
|
||||
always @(posedge clk) r_{n} <= w_{n};\n"
|
||||
));
|
||||
}
|
||||
src.push_str(" assign data_out = data_in;\n // typing\nendmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// One keystroke: an `x` typed at `character` on `line`, as an editor with
|
||||
/// incremental sync sends it.
|
||||
fn keystroke(uri: &str, version: u32, line: u32, character: u32) -> String {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"range":{{"start":{{"line":{line},"character":{character}}},"end":{{"line":{line},"character":{character}}}}},"text":"x"}}]}}}}"#
|
||||
)
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn a_keystroke_round_trip_over_the_wire() {
|
||||
for lines in [1_000usize, 10_000] {
|
||||
let dir = temp_dir(&format!("latency{lines}"));
|
||||
let file = dir.join("gen.sv");
|
||||
let source = generated_module("gen", lines);
|
||||
std::fs::write(&file, &source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
// The `// typing` line, 0-based, and the column just past its text.
|
||||
let comment = source.find(" // typing").expect("the typing line");
|
||||
let line = source[..comment].matches('\n').count() as u32;
|
||||
let column = " // typing".len() as u32;
|
||||
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
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":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(&source).expect("json")
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
|
||||
// One keystroke, alone. Nothing else is coming, so what ends the wait
|
||||
// is the debounce's quiet-period timer: this is that timer, plus one
|
||||
// flush, plus the wire.
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&keystroke(&uri, 2, line, column));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let single = started.elapsed();
|
||||
|
||||
// The same keystroke, followed straight away by a request — which is
|
||||
// what a real editor does: VS Code asks for semantic tokens, inlay
|
||||
// hints and highlights the moment the buffer changes. A request
|
||||
// flushes the dirty buffer before it is answered, so the quiet-period
|
||||
// timer never runs and this is the flush and the wire alone.
|
||||
// Ten of them, and the mean: no timer is involved, so these are short
|
||||
// enough that a single one would be mostly scheduling noise.
|
||||
let runs = 10u32;
|
||||
let started = std::time::Instant::now();
|
||||
for k in 0..runs {
|
||||
live.send(&keystroke(&uri, 3 + k, line, column));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":4}}}}}}"#,
|
||||
50 + k
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
live.wait_for(|m| m["id"] == 50 + k);
|
||||
}
|
||||
let requested = started.elapsed() / runs;
|
||||
|
||||
// Ten keystrokes with no pause between them — a burst of typing. The
|
||||
// debounce's whole claim is that this costs one flush and not ten,
|
||||
// and the count below is that claim measured rather than reasoned
|
||||
// about: the wait consumes one publish and `finish` counts every
|
||||
// other one still queued when the shutdown reply comes back.
|
||||
//
|
||||
// This is deliberately the *last* thing measured. Every `wait_for`
|
||||
// above accepts any publish, so a second one the burst had produced
|
||||
// would be absorbed by whichever wait ran next and never counted —
|
||||
// with nothing between the burst and `finish`, there is no such wait.
|
||||
let started = std::time::Instant::now();
|
||||
for k in 0..10u32 {
|
||||
live.send(&keystroke(&uri, 13 + k, line, column + 1 + k));
|
||||
}
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let burst = started.elapsed();
|
||||
|
||||
let published = 1 + live.finish();
|
||||
|
||||
eprintln!(
|
||||
"keystroke round trip, {lines} lines: one change alone {single:?}, \
|
||||
a burst of ten {burst:?} for {published} publish(es), \
|
||||
one change a request follows {requested:?}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,11 @@ impl From<VerificationError> for FormatError {
|
||||
/// The output is only returned if it re-lexes to the same token stream as the
|
||||
/// input (comments included) and formatting it again is a fixed point;
|
||||
/// otherwise the caller gets an error and must leave the original text alone.
|
||||
///
|
||||
/// Parses `source` (twice, for verification), so call this only on a thread
|
||||
/// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one
|
||||
/// lets sufficiently nested input abort the process instead of returning
|
||||
/// `Err` (see `docs/features/recursion-limit/README.md`).
|
||||
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
let output = format_once(source, config).map_err(FormatError::Source)?;
|
||||
verify_equivalence(source, &output)?;
|
||||
@@ -93,6 +98,9 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
|
||||
/// formatter output, and both checks are global. Convergence is checked by
|
||||
/// replaying the same per-item decisions against the output — see
|
||||
/// `docs/features/range-formatting/README.md`.
|
||||
///
|
||||
/// Same stack requirement as [`format_source`]: needs a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
|
||||
pub fn format_range(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
|
||||
@@ -7,13 +7,15 @@
|
||||
//! the formatter at all.
|
||||
|
||||
use vlog_formatter::{format_source, Config, FormatError};
|
||||
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH};
|
||||
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH, PARSE_STACK_SIZE};
|
||||
|
||||
/// Formatting the deepest legal tree peaks around 4 MiB of stack in an
|
||||
/// unoptimized build, more than a default test thread's 2 MiB.
|
||||
/// Formatting the deepest legal tree peaks around 5.9 MiB of stack in an
|
||||
/// unoptimized build, more than a default test thread's 2 MiB. The size is
|
||||
/// the one every production parse site is given, so these tests fail if the
|
||||
/// guarantee is ever cut below what the depth limit needs.
|
||||
fn format_deep(source: String) -> Result<String, FormatError> {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || format_source(&source, &Config::default()))
|
||||
.expect("spawn formatter thread")
|
||||
.join()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -14,7 +14,7 @@ pub mod token;
|
||||
|
||||
pub use lexer::{tokenize, LexError};
|
||||
pub use line_index::LineIndex;
|
||||
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError};
|
||||
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError, PARSE_STACK_SIZE};
|
||||
pub use span::TextRange;
|
||||
pub use token::KEYWORDS;
|
||||
|
||||
|
||||
@@ -160,13 +160,40 @@ const DRIVE_STRENGTHS: &[&str] = &[
|
||||
/// How deeply constructs may nest before the parser gives up.
|
||||
///
|
||||
/// Chosen from measured stack use, not from taste: nested statements are the
|
||||
/// most expensive family at ~62 KiB of stack per level in an unoptimized
|
||||
/// build, so formatting an input that trips the limit peaks at ~3.9 MiB —
|
||||
/// comfortably under the 8 MiB default main-thread stack, and ~0.5 MiB in
|
||||
/// an optimized build. Real RTL nests roughly an order of magnitude less
|
||||
/// than this; see `docs/features/recursion-limit/README.md`.
|
||||
/// most expensive family at ~94 KiB of stack per level in an unoptimized
|
||||
/// build, so the whole pipeline on an input that trips the limit peaks at
|
||||
/// ~5.9 MiB there and ~0.8 MiB in an optimized build. That budget is only
|
||||
/// safe on a thread big enough to hold it, which is what
|
||||
/// [`PARSE_STACK_SIZE`] names — this limit bounds how *many* levels run, not
|
||||
/// what one costs. Real RTL nests roughly an order of magnitude less than
|
||||
/// this; see `docs/features/recursion-limit/README.md`.
|
||||
pub const MAX_NESTING_DEPTH: u32 = 64;
|
||||
|
||||
/// How much stack a thread that parses must be given.
|
||||
///
|
||||
/// [`MAX_NESTING_DEPTH`] turns over-deep input into a parse error instead of
|
||||
/// a stack overflow, but only on a thread that can hold the levels it *does*
|
||||
/// allow: the guard fires at level 64, and reaching level 64 costs stack. On
|
||||
/// a smaller thread the overflow happens first, and a stack overflow is an
|
||||
/// abort, not a `Result` — the whole process dies. So the stack has to fit
|
||||
/// the limit; the limit is not lowered to fit some thread's stack.
|
||||
///
|
||||
/// Measured worst case for the full pipeline (tokenize → parse → analyze →
|
||||
/// format → verify) over every nesting family, on input sized to trip the
|
||||
/// limit: **~5.9 MiB unoptimized, ~0.8 MiB optimized** (nested `case`, the
|
||||
/// fattest family). 16 MiB is that with 2.7× to spare, which is the margin
|
||||
/// this wants: unoptimized frame sizes drift upward with the compiler — the
|
||||
/// same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB in 2026-08-28
|
||||
/// on rustc 1.97 — and there is no recoverable failure mode to fall back to.
|
||||
///
|
||||
/// Every thread that may reach a parse is spawned with at least this:
|
||||
/// `std::thread::Builder::new().stack_size(PARSE_STACK_SIZE)`, or
|
||||
/// `rayon::ThreadPoolBuilder::new().stack_size(PARSE_STACK_SIZE)`. Thread
|
||||
/// stacks are committed by the OS a page at a time, so an unused one costs
|
||||
/// address space rather than memory. `docs/features/recursion-limit/README.md`
|
||||
/// lists every site.
|
||||
pub const PARSE_STACK_SIZE: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// How many links a left-nested chain may add to the tree on one path.
|
||||
///
|
||||
/// Some constructs are parsed by a loop rather than by recursion — postfix
|
||||
@@ -178,9 +205,9 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
|
||||
/// the two limits together no matter how chains and nesting are combined.
|
||||
///
|
||||
/// It is larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap —
|
||||
/// ~6 KiB of stack per link in an unoptimized build against ~62 KiB for a
|
||||
/// nested statement, so a maximal chain peaks near 1.5 MiB, well under the
|
||||
/// ~3.9 MiB that maximal statement nesting already costs — and because long
|
||||
/// ~9 KiB of stack per link in an unoptimized build against ~94 KiB for a
|
||||
/// nested statement, so a maximal chain peaks near 2.4 MiB, well under the
|
||||
/// ~5.9 MiB that maximal statement nesting already costs — and because long
|
||||
/// flat chains are the one shape real RTL does produce (a 256-term generated
|
||||
/// sum, a 64-bit parity XOR). Raising it, unlike raising
|
||||
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
|
||||
@@ -241,6 +268,10 @@ pub struct Parser<'a> {
|
||||
/// `source` must be the exact text `tokens` were lexed from: the constructs
|
||||
/// lucisv keeps verbatim (`constraint`, `covergroup` — see
|
||||
/// `docs/features/classes/README.md`) copy their bytes out of it by span.
|
||||
///
|
||||
/// Recurses with input nesting: call this only on a thread with at least
|
||||
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
|
||||
/// instead of returning `Err`.
|
||||
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
|
||||
Parser::new(tokens, source, false).parse_source_file()
|
||||
}
|
||||
@@ -253,6 +284,10 @@ pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
|
||||
/// still spans the whole file. `source` must be the exact text `tokens` were
|
||||
/// lexed from. On a well-formed file the tree is identical to [`parse`]'s and
|
||||
/// the diagnostics are empty.
|
||||
///
|
||||
/// Same stack requirement as [`parse`]: needs a thread with at least
|
||||
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
|
||||
/// parses of the same over-deep input overflow at the same depth.
|
||||
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
|
||||
let mut p = Parser::new(tokens, source, true);
|
||||
match p.parse_source_file() {
|
||||
@@ -4898,13 +4933,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse on a thread with a generous stack. Nesting all the way to
|
||||
/// [`MAX_NESTING_DEPTH`] peaks around 4 MiB in an unoptimized build,
|
||||
/// which is more than the 2 MiB a default test thread gets — the shipped
|
||||
/// binary parses on the main thread, which has 8 MiB.
|
||||
/// Parse on the stack every production parse site is given. Nesting all
|
||||
/// the way to [`MAX_NESTING_DEPTH`] peaks around 5.9 MiB in an
|
||||
/// unoptimized build, which is more than the 2 MiB a default test thread
|
||||
/// gets — hence [`PARSE_STACK_SIZE`], and hence the fact that the tests
|
||||
/// spell it rather than a number of their own: what they exercise is the
|
||||
/// stack the shipped binaries actually run on.
|
||||
fn parse_deep(src: String) -> PResult<SourceFile> {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || parse(tokenize(&src).expect("lex error"), &src))
|
||||
.expect("spawn parser thread")
|
||||
.join()
|
||||
@@ -5014,6 +5051,47 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
/// `n` copies of a block opener and its closer around one statement, in
|
||||
/// an `initial` — the shape generated RTL nests.
|
||||
fn nested_stmt_blocks(open: &str, close: &str, n: usize) -> String {
|
||||
format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
open.repeat(n),
|
||||
close.repeat(n)
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_nesting_errors_for_every_block_form() {
|
||||
let d = 200;
|
||||
// `fork`/`join` blocks are statements like `begin`/`end`.
|
||||
assert_too_deep(nested_stmt_blocks("fork\n", "join\n", d));
|
||||
// `case` carries the fattest frame in the grammar; the arm's own
|
||||
// statement is a second gated level per source level.
|
||||
assert_too_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", d));
|
||||
// Bodies that need no closer still recurse through the body
|
||||
// statement.
|
||||
assert_too_deep(nested_stmt_blocks("foreach (a[j])\n", "", d));
|
||||
assert_too_deep(nested_stmt_blocks("while (c)\n", "", d));
|
||||
assert_too_deep(nested_stmt_blocks("for (int i = 0; i < 4; i++)\n", "", d));
|
||||
// Nested module declarations (IEEE 1800 §23.4) nest items, not
|
||||
// statements, so they are gated by `parse_item`.
|
||||
assert_too_deep(format!("{}wire w;\n{}", "module m;\n".repeat(d), "endmodule\n".repeat(d)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fattest_block_forms_still_parse_at_the_limit() {
|
||||
// The stack these tests run on is `PARSE_STACK_SIZE`, so this is the
|
||||
// load-bearing direction: the deepest *legal* input in the two most
|
||||
// expensive families has to fit the stack every production parse site
|
||||
// is given. `module` + `initial` + `begin` + the innermost statement
|
||||
// and its expression cost six levels between them.
|
||||
let n = MAX_NESTING_DEPTH as usize - 6;
|
||||
parse_deep(nested_stmt_blocks("fork\n", "join\n", n)).expect("legal `fork` nesting");
|
||||
parse_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", n))
|
||||
.expect("legal `case` nesting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_just_below_the_limit_parses() {
|
||||
parse_deep(chain(".b", MAX_CHAIN_LENGTH as usize))
|
||||
|
||||
@@ -142,6 +142,7 @@ impl<'a> Binder<'a> {
|
||||
kind,
|
||||
name_span,
|
||||
decl_span,
|
||||
detail_span: None,
|
||||
scope,
|
||||
child_scope: None,
|
||||
});
|
||||
@@ -501,6 +502,27 @@ impl<'a> Binder<'a> {
|
||||
ScopeKind::Function | ScopeKind::Task => SymbolKind::TfArg,
|
||||
_ => SymbolKind::Port,
|
||||
};
|
||||
// A non-ANSI port's body declaration (`input signed [31:0] data_in;`)
|
||||
// completes a port the header only named (`data_in,`). `declare`
|
||||
// below attaches it as a reference to that header symbol — and here,
|
||||
// the whole declaration's span is recorded on the symbol as where its
|
||||
// direction, type and width are written. First writer wins, so a
|
||||
// header that names a port twice is the linter's to complain about
|
||||
// and this stays deterministic.
|
||||
//
|
||||
// An old-style task or function argument (`task t(a);` finished by
|
||||
// `input [7:0] a;`) is the same header-names-it, body-completes-it
|
||||
// shape and merges through the same `declare`, so it is recorded on
|
||||
// the same terms — matching on `kind` rather than on `Port` alone.
|
||||
let names = &self.scopes[scope.0 as usize].names;
|
||||
for d in &p.declarators {
|
||||
if let Some(&existing) = names.get(d.name.as_str()) {
|
||||
let symbol = &mut self.symbols[existing.0 as usize];
|
||||
if symbol.kind == kind && symbol.detail_span.is_none() {
|
||||
symbol.detail_span = Some(span);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
//! [`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 = 3;
|
||||
|
||||
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);
|
||||
// The detail span is written unconditionally — `0 0` for the `None`
|
||||
// every ordinary declaration has — so the stream stays flat. Adding it
|
||||
// changed what a record holds, so `FACTS_FORMAT` is bumped and a store
|
||||
// written before it is discarded whole rather than read field-shifted
|
||||
// by two (`docs/features/port-detail-spans/README.md`).
|
||||
match decl.detail_span {
|
||||
Some(span) => self.range(span),
|
||||
None => {
|
||||
self.num(0);
|
||||
self.num(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()?)?;
|
||||
let name_span = self.range()?;
|
||||
// The mirror of the encoder's unconditional pair: `(0, 0)` is the
|
||||
// `None`, and a real span can never be, because a declaration's span
|
||||
// is never empty.
|
||||
let start = self.num()?;
|
||||
let end = self.num()?;
|
||||
let detail_span = (start != 0 || end != 0).then_some(TextRange::new(start, end));
|
||||
Some(Decl { name, name_span, kind, detail_span })
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+9
@@ -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
|
||||
@@ -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,16 @@ 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)>,
|
||||
/// Every symbol id, sorted by the name it declares, ties in declaration
|
||||
/// order — so looking a name up is a binary search rather than a walk of
|
||||
/// every symbol. A side table rather than a `HashMap<String, _>` because
|
||||
/// this way `Semantics` does not carry a second copy of every name it
|
||||
/// already holds, and it is cloned per document.
|
||||
by_name: Vec<SymbolId>,
|
||||
}
|
||||
|
||||
/// Build the symbol table for one parsed file. `src` must be the text the
|
||||
@@ -74,7 +89,26 @@ 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));
|
||||
// A *stable* sort by name, so symbols sharing a name keep the order they
|
||||
// were declared in — the order a caller filtering `symbols()` by name
|
||||
// would have seen, which is what makes swapping the two an identity.
|
||||
let mut by_name: Vec<SymbolId> = (0..symbols.len() as u32).map(SymbolId).collect();
|
||||
by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name));
|
||||
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name }
|
||||
}
|
||||
|
||||
/// Point every import at the package it names, when this file declares it.
|
||||
@@ -122,24 +156,34 @@ impl Semantics {
|
||||
self.symbols.get(id.0 as usize)
|
||||
}
|
||||
|
||||
/// Every declaration that spells `name`, in declaration order — the same
|
||||
/// symbols, in the same order, that filtering [`Semantics::symbols`] by
|
||||
/// name yields, without walking the ones that cannot match.
|
||||
pub fn symbols_named(&self, name: &str) -> impl Iterator<Item = SymbolId> + '_ {
|
||||
// Two binary searches over the name-sorted side table: the first name
|
||||
// that is not less than the one asked for, then the first one past it.
|
||||
let spelling = |id: &SymbolId| self.symbol(*id).map_or("", |symbol| symbol.name.as_str());
|
||||
let start = self.by_name.partition_point(|id| spelling(id) < name);
|
||||
let rest = self.by_name.get(start..).unwrap_or(&[]);
|
||||
let end = rest.partition_point(|id| spelling(id) == name);
|
||||
rest.get(..end).unwrap_or(&[]).iter().copied()
|
||||
}
|
||||
|
||||
/// The declaration whose *name* covers `offset` — a cursor sitting on a
|
||||
/// declared name, not anywhere in its declaration.
|
||||
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
|
||||
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 +255,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)
|
||||
}
|
||||
@@ -57,6 +57,13 @@ pub struct Symbol {
|
||||
/// Byte range of the construct that owns the name (the whole `module`,
|
||||
/// the whole declarator, the whole port declaration).
|
||||
pub decl_span: TextRange,
|
||||
/// Where the *complete* declaration is written, when that is not
|
||||
/// `decl_span`: a non-ANSI port's header names it and a body `input
|
||||
/// signed [31:0] data_in;` finishes it, so hover and go-to-definition
|
||||
/// point here — the line that carries the direction, the type and the
|
||||
/// width — while `name_span`/`decl_span` stay in the header. `None` for
|
||||
/// every declaration that is complete where it is named.
|
||||
pub detail_span: Option<TextRange>,
|
||||
/// The scope the name is bound in.
|
||||
pub scope: ScopeId,
|
||||
/// The scope this declaration opens, for the kinds that open one
|
||||
|
||||
@@ -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)]
|
||||
@@ -36,6 +37,42 @@ pub struct Def {
|
||||
pub name_span: TextRange,
|
||||
/// What kind of declaration it is, for an icon and for hover text.
|
||||
pub kind: SymbolKind,
|
||||
/// Where the declaration is *completed* when not at `name_span` — a
|
||||
/// non-ANSI port's body `input wire clk;`. A cross-file hover shows these
|
||||
/// lines; `None` for every declaration complete where it is named.
|
||||
pub detail_span: Option<TextRange>,
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
@@ -49,18 +86,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 +169,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 +196,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 +227,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 +274,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 +344,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 +354,647 @@ 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) {
|
||||
self.update_facts(facts_of(path, src));
|
||||
}
|
||||
|
||||
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
|
||||
/// known — read from a cache, or from an analysis the caller already holds
|
||||
/// ([`FileFacts::from_analysis`]) — so the update costs no parse at all.
|
||||
///
|
||||
/// Exactly [`WorkspaceIndex::update_file`] with the parse already done, the
|
||||
/// same way [`IndexBuilder::add_facts`] is [`IndexBuilder::add_file`] with
|
||||
/// the parse already done: same contract, same result. Whether the record
|
||||
/// really describes the file is the caller's business.
|
||||
pub fn update_facts(&mut self, facts: FileFacts) {
|
||||
let path = facts.path.clone();
|
||||
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
|
||||
// The common case — a saved file the index already holds. Only the
|
||||
// names this file declared before or declares now can have moved,
|
||||
// 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,
|
||||
pub(crate) detail_span: Option<TextRange>,
|
||||
}
|
||||
|
||||
impl Decl {
|
||||
fn of(symbol: &Symbol) -> Decl {
|
||||
Decl {
|
||||
name: symbol.name.clone(),
|
||||
name_span: symbol.name_span,
|
||||
kind: symbol.kind,
|
||||
detail_span: symbol.detail_span,
|
||||
}
|
||||
}
|
||||
|
||||
fn def(&self, file: FileId) -> Def {
|
||||
Def { file, name_span: self.name_span, kind: self.kind, detail_span: self.detail_span }
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// Parses `src` internally, so call this only on a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one lets
|
||||
/// sufficiently nested input abort the process instead of producing a
|
||||
/// diagnostic (see `docs/features/recursion-limit/README.md`).
|
||||
pub fn of(path: PathBuf, src: &str) -> FileFacts {
|
||||
facts_of(path, src)
|
||||
}
|
||||
|
||||
/// The same record read off an analysis the caller **already has** — the
|
||||
/// tree, the `` `define`` table and the [`Semantics`] of one file — instead
|
||||
/// of from that file's text.
|
||||
///
|
||||
/// This is the second half of [`FileFacts::of`], made callable on its own:
|
||||
/// `of` is `tokenize` + `parse_tolerant` + [`analyze`] followed by exactly
|
||||
/// this function, so a caller that has done that work once (a language
|
||||
/// server holding an open buffer's finished analysis) gets the record the
|
||||
/// parse would have produced without paying for the parse a second time.
|
||||
/// The two paths are the same code and cannot drift; what the caller
|
||||
/// promises is only that `tree`, `defines` and `sem` are the analysis of
|
||||
/// the text `path` currently holds.
|
||||
pub fn from_analysis(
|
||||
path: PathBuf,
|
||||
tree: &SourceFile,
|
||||
defines: &DefineTable,
|
||||
sem: &Semantics,
|
||||
) -> FileFacts {
|
||||
facts_from_analysis(path, tree, defines.clone(), sem)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
facts_from_analysis(path, &tree, defines, &sem)
|
||||
}
|
||||
|
||||
/// Read off what one file contributes, from its finished analysis.
|
||||
fn facts_from_analysis(
|
||||
path: PathBuf,
|
||||
tree: &SourceFile,
|
||||
defines: DefineTable,
|
||||
sem: &Semantics,
|
||||
) -> FileFacts {
|
||||
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 +1017,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.
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Deeply nested input against the stack the parse actually runs on.
|
||||
//!
|
||||
//! `vlog_parser` turns nesting past `MAX_NESTING_DEPTH` into an ordinary
|
||||
//! diagnostic, but only above `PARSE_STACK_SIZE`: reaching level 64 costs
|
||||
//! stack, and a thread too small to hold it overflows before the guard ever
|
||||
//! fires — an abort, not a `Result`. These tests run the whole indexing
|
||||
//! pipeline (tokenize → tolerant parse → `analyze` → facts) on exactly that
|
||||
//! stack, so they fail if either half of the contract is cut.
|
||||
//!
|
||||
//! Reported 2026-08-28: 500 nested `begin`/`end` through `FileFacts::of`
|
||||
//! aborted the process on a default 2 MiB test thread.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
|
||||
|
||||
/// Run `f` on the stack every production parse site is given — the CLI's
|
||||
/// worker thread and rayon pool, the language server's message loop. Not a
|
||||
/// generous number picked for the test: the constant itself, so shrinking
|
||||
/// the guarantee below what the depth limit needs fails here.
|
||||
fn on_parse_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(f)
|
||||
.expect("spawn a parse-sized thread")
|
||||
.join()
|
||||
.expect("the parse thread died")
|
||||
}
|
||||
|
||||
/// The index one file's facts build, read off on the same stack.
|
||||
fn index_of(src: String) -> WorkspaceIndex {
|
||||
on_parse_stack(move || {
|
||||
let mut builder = IndexBuilder::new();
|
||||
builder.add_facts(FileFacts::of(PathBuf::from("/w/deep.sv"), &src));
|
||||
builder.finish()
|
||||
})
|
||||
}
|
||||
|
||||
/// `n` nested `begin`/`end` inside an `initial`, in a module.
|
||||
fn nested_begins(n: usize) -> String {
|
||||
format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
)
|
||||
}
|
||||
|
||||
/// Every block-structured shape that nests, at a depth far past the limit.
|
||||
/// Each is `(name, source)`; the innermost body is a statement or an item, so
|
||||
/// the shape is what real generated code would produce, not a bare skeleton.
|
||||
fn deep_block_shapes(n: usize) -> Vec<(&'static str, String)> {
|
||||
let stmt = |open: &str, close: &str| {
|
||||
format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
open.repeat(n),
|
||||
close.repeat(n)
|
||||
)
|
||||
};
|
||||
vec![
|
||||
("begin/end", nested_begins(n)),
|
||||
("if/begin", stmt("if (c) begin\n", "end\n")),
|
||||
("fork/join", stmt("fork\n", "join\n")),
|
||||
("case/endcase", stmt("case (s)\n1: ", "endcase\n")),
|
||||
("foreach", stmt("foreach (a[j])\n", "")),
|
||||
("while", stmt("while (c)\n", "")),
|
||||
("for", stmt("for (int i = 0; i < 4; i++)\n", "")),
|
||||
(
|
||||
"else-if chain",
|
||||
format!(
|
||||
"module m;\ninitial\n{}x <= 0;\nendmodule\n",
|
||||
"if (c) x <= 1; else\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"generate if",
|
||||
format!(
|
||||
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
|
||||
"if (1) begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"generate for",
|
||||
format!(
|
||||
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
|
||||
"for (i = 0; i < 2; i = i + 1) begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"nested modules",
|
||||
format!("{}wire w;\n{}", "module m;\n".repeat(n), "endmodule\n".repeat(n)),
|
||||
),
|
||||
(
|
||||
// Not legal SystemVerilog at all — a `task` cannot open inside a
|
||||
// task body — so this errors early rather than on depth. It is
|
||||
// here because "errors early" is a claim about the stack too.
|
||||
"nested tasks",
|
||||
format!(
|
||||
"module m;\n{}x = 1;\n{}endmodule\n",
|
||||
"task t;\n".repeat(n),
|
||||
"endtask\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"nested functions",
|
||||
format!(
|
||||
"module m;\n{}f = 1;\n{}endmodule\n",
|
||||
"function int f;\n".repeat(n),
|
||||
"endfunction\n".repeat(n)
|
||||
),
|
||||
),
|
||||
("nested parens", {
|
||||
format!("module m;\nassign x = {}1{};\nendmodule\n", "(".repeat(n), ")".repeat(n))
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_hundred_nested_blocks_are_indexed_not_aborted() {
|
||||
// The reported repro, verbatim in shape. The depth limit rejects the
|
||||
// `initial` block, tolerant recovery turns it into an error leaf, and the
|
||||
// module around it is still a fact — a graceful result, not a dead
|
||||
// process.
|
||||
let index = index_of(nested_begins(500));
|
||||
assert_eq!(index.files().len(), 1);
|
||||
assert_eq!(index.units("m").len(), 1, "the module survives the unparsable body");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_block_shape_can_abort_the_parse_stack() {
|
||||
// 400 levels is far past `MAX_NESTING_DEPTH` for every family, so each of
|
||||
// these either errors on depth or errors earlier; what is asserted is
|
||||
// that the pipeline *returns* on the guaranteed stack. A regression here
|
||||
// is a SIGABRT, so the assertion below is secondary — reaching it is the
|
||||
// test.
|
||||
for (name, src) in deep_block_shapes(400) {
|
||||
let index = index_of(src);
|
||||
assert_eq!(index.files().len(), 1, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_just_under_the_limit_still_yields_its_facts() {
|
||||
// Legal depth, so nothing is rejected and the whole 64-level tree is
|
||||
// parsed, analyzed and walked on this stack — the expensive direction,
|
||||
// and the one a smaller stack fails first.
|
||||
let index = index_of(nested_begins(vlog_parser::parser::MAX_NESTING_DEPTH as usize - 6));
|
||||
assert_eq!(index.units("m").len(), 1, "a legally deep file is indexed like any other");
|
||||
}
|
||||
@@ -510,6 +510,92 @@ endmodule
|
||||
assert_eq!(body.resolved(), Some(a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ansi_port_records_where_its_body_declaration_completes_it() {
|
||||
let src = "\
|
||||
module m (a, b);
|
||||
input [7:0] a;
|
||||
output b;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let a = symbol_named(&s, "a");
|
||||
let detail = a.detail_span.expect("the body declaration's span");
|
||||
assert!(
|
||||
src[detail.start as usize..detail.end as usize].starts_with("input [7:0] a"),
|
||||
"the detail site covers the body declaration: {:?}",
|
||||
&src[detail.start as usize..detail.end as usize]
|
||||
);
|
||||
// ...while the name stays in the header.
|
||||
assert_eq!(&src[a.name_span.start as usize..a.name_span.end as usize], "a");
|
||||
assert!(a.name_span.start < detail.start);
|
||||
|
||||
// An ANSI port is complete where it is named: no detail site.
|
||||
let ansi = sem("module m (input wire clk);\nendmodule\n");
|
||||
assert_eq!(symbol_named(&ansi, "clk").detail_span, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_style_task_argument_records_its_body_declaration_too() {
|
||||
// `task t(a);` names the argument and `input [7:0] a;` finishes it —
|
||||
// the same shape a non-ANSI module port has, merged by the same
|
||||
// `declare`, so it carries the same detail site (QA, PDS-3).
|
||||
let src = "\
|
||||
module m;
|
||||
task t(a);
|
||||
input [7:0] a;
|
||||
$display(a);
|
||||
endtask
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let a = symbol_named(&s, "a");
|
||||
assert_eq!(a.kind, SymbolKind::TfArg);
|
||||
let detail = a.detail_span.expect("the body declaration's span");
|
||||
assert_eq!(&src[detail.start as usize..detail.end as usize], "input [7:0] a;");
|
||||
assert!(a.name_span.start < detail.start, "the name stays in the header");
|
||||
|
||||
// An argument complete where it is named has no detail site, as before.
|
||||
let ansi = sem("module m;\n task t(input [7:0] a);\n endtask\nendmodule\n");
|
||||
assert_eq!(symbol_named(&ansi, "a").detail_span, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn looking_a_name_up_answers_exactly_what_scanning_every_symbol_would() {
|
||||
// The name-keyed lookup exists so a caller never walks the whole symbol
|
||||
// table to find the declarations spelling one name. It is only a
|
||||
// substitution if it answers the same symbols in the same order — and the
|
||||
// order is what decides the tie when one buffer holds two declarations of
|
||||
// one name, as a mid-edit buffer does.
|
||||
// One scope never binds a name twice (`bind::declare`), so two
|
||||
// declarations of one name means two scopes — a buffer holding an old
|
||||
// module and its half-written replacement, which is the tie
|
||||
// `hover::live_symbol` has to break.
|
||||
let src = "\
|
||||
module m (input wire dup);
|
||||
wire other;
|
||||
endmodule
|
||||
module n (input wire [7:0] dup);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for name in ["dup", "other", "m", "n", "absent"] {
|
||||
let scanned: Vec<SymbolId> = s
|
||||
.symbols()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, sym)| sym.name == name)
|
||||
.map(|(i, _)| SymbolId(i as u32))
|
||||
.collect();
|
||||
let looked_up: Vec<SymbolId> = s.symbols_named(name).collect();
|
||||
assert_eq!(looked_up, scanned, "the two answers must agree for {name}");
|
||||
}
|
||||
// The one that matters: two `dup`s, and the first is the earlier one.
|
||||
let dups: Vec<SymbolId> = s.symbols_named("dup").collect();
|
||||
assert_eq!(dups.len(), 2, "{dups:?}");
|
||||
assert!(dups[0].0 < dups[1].0, "declaration order, so the first match is the first written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_name_resolves_only_its_head() {
|
||||
let src = "\
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Behavior of the workspace index: cross-file definitions, duplicate names,
|
||||
//! package members, and the corpus acceptance run.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use std::path::{Path, PathBuf};
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, Definition, ExternalTarget, 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 +283,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 +760,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 +1028,795 @@ 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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Facts from an analysis the caller already has (index-scope, 2026-08-28)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The analysis a server holds for an open buffer, built exactly the way
|
||||
/// `lucisv_server::state::Document::new` builds it — one lex, the tree from a
|
||||
/// clone of that token stream, the define table off the same tokens, and the
|
||||
/// same all-or-nothing lex-failure branch.
|
||||
fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics) {
|
||||
let (tokens, tree) = match tokenize(src) {
|
||||
Ok(tokens) => {
|
||||
let (tree, _) = parse_tolerant(tokens.clone(), src);
|
||||
(tokens, tree)
|
||||
}
|
||||
Err(_) => (Vec::new(), parse_source_tolerant(src).0),
|
||||
};
|
||||
let defines = collect_defines(&tokens);
|
||||
let sem = analyze(&tree, src);
|
||||
(tree, defines, sem)
|
||||
}
|
||||
|
||||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||||
///
|
||||
/// The record format is the comparison — the encoded line is every field the
|
||||
/// index and the persistent store ever read — so a byte-equal line is the
|
||||
/// whole equivalence. Two paths that could drift here would be a corruption
|
||||
/// seed: the index would describe a buffer by facts its own parse disagrees
|
||||
/// with.
|
||||
#[test]
|
||||
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
let crafted = [
|
||||
// Nothing at all, and nothing that lexes.
|
||||
"",
|
||||
" \n\t\n",
|
||||
"this is not verilog\n",
|
||||
"module m;\n \"unterminated\n",
|
||||
"// just a comment\n",
|
||||
// The declaration kinds `facts_of` reads off the file scope.
|
||||
"package p;\n localparam W = 8;\n typedef logic [W-1:0] word_t;\n\
|
||||
\x20 function int f(int a); return a; endfunction\nendpackage\n",
|
||||
"module top #(parameter N = 4) (input logic clk, output logic q);\n\
|
||||
\x20 sub u_a (.clk(clk));\n sub u_b (.clk(clk));\nendmodule\n",
|
||||
// Classes, inheritance, and a class nested in a package.
|
||||
"class base; endclass\nclass derived extends base;\n int x;\nendclass\n",
|
||||
"package pkg;\n class inner extends outer_base;\n typedef int t;\n endclass\nendpackage\n",
|
||||
// `define`s, including a parameterised one and an `undef`.
|
||||
"`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n`undef WIDTH\n\
|
||||
module m; logic [`WIDTH-1:0] w; endmodule\n",
|
||||
// External candidates: imports, scope resolution, port connections.
|
||||
"import other_pkg::*;\nimport third_pkg::thing;\nmodule m;\n\
|
||||
\x20 other_pkg::word_t w;\n assign w = thing;\n child u (.port_a(w));\nendmodule\n",
|
||||
// An instantiation at file scope — deliberately *not* an edge — and a
|
||||
// generate body, which is one site however many instances it makes.
|
||||
"sub u_orphan (.clk(clk));\nmodule m;\n generate for (genvar i = 0; i < 4; i++) begin\n\
|
||||
\x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n",
|
||||
// A tree with error nodes: the tolerant parse still contributes.
|
||||
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n",
|
||||
];
|
||||
for src in crafted {
|
||||
let path = PathBuf::from("/w/x.sv");
|
||||
let (tree, defines, sem) = as_a_server_analyzes(src);
|
||||
let from_text = FileFacts::of(path.clone(), src);
|
||||
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem);
|
||||
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
|
||||
assert_eq!(
|
||||
from_analysis.encode(),
|
||||
from_text.encode(),
|
||||
"and so do their encoded forms for {src:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same claim over every file of the real corpus, which is where the
|
||||
/// constructs nobody thought to craft live.
|
||||
#[test]
|
||||
fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !root.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
corpus_files(&root, &mut files);
|
||||
files.sort();
|
||||
assert!(!files.is_empty(), "corpus/ exists but holds no Verilog");
|
||||
let mut checked = 0usize;
|
||||
for path in &files {
|
||||
let Ok(src) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let (tree, defines, sem) = as_a_server_analyzes(&src);
|
||||
let from_text = FileFacts::of(path.clone(), &src);
|
||||
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem);
|
||||
assert_eq!(
|
||||
from_analysis.encode(),
|
||||
from_text.encode(),
|
||||
"the records differ for {}",
|
||||
path.display()
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
eprintln!("facts equivalence: {checked} corpus files, every record byte-identical");
|
||||
}
|
||||
|
||||
fn corpus_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
corpus_files(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An index built from records read off analyses is the index the parses
|
||||
/// build, byte for byte — the house witness, at index scale rather than at one
|
||||
/// file's.
|
||||
#[test]
|
||||
fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text() {
|
||||
let files = [
|
||||
("/w/pkg.sv", "package p;\n localparam W = 8;\n class c; int x; endclass\nendpackage\n"),
|
||||
("/w/sub.sv", "module sub (input logic clk, input logic [7:0] d);\nendmodule\n"),
|
||||
(
|
||||
"/w/top.sv",
|
||||
"import p::*;\n`define TAG 1\nmodule top;\n logic [W-1:0] w;\n\
|
||||
\x20 sub u_a (.clk(w[0]), .d(w));\n sub u_b (.clk(w[0]), .d(w));\nendmodule\n",
|
||||
),
|
||||
("/w/kid.sv", "class kid extends c;\nendclass\n"),
|
||||
("/w/junk.sv", "module broken (;\n"),
|
||||
];
|
||||
let from_text = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
|
||||
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
// Deliberately not path order: the reuse must not smuggle an ordering in.
|
||||
for (path, src) in files.iter().rev() {
|
||||
let (tree, defines, sem) = as_a_server_analyzes(src);
|
||||
builder.add_facts(FileFacts::from_analysis(PathBuf::from(*path), &tree, &defines, &sem));
|
||||
}
|
||||
let from_analyses = builder.finish();
|
||||
assert_eq!(from_analyses.fingerprint(), from_text.fingerprint());
|
||||
|
||||
// And the same through the incremental door: `update_facts` must leave the
|
||||
// index `update_file` would have left.
|
||||
let mut updated = from_text.clone();
|
||||
let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n";
|
||||
let (tree, defines, sem) = as_a_server_analyzes(changed);
|
||||
updated.update_facts(FileFacts::from_analysis(
|
||||
PathBuf::from("/w/pkg.sv"),
|
||||
&tree,
|
||||
&defines,
|
||||
&sem,
|
||||
));
|
||||
let mut parsed = from_text.clone();
|
||||
parsed.update_file(PathBuf::from("/w/pkg.sv"), changed);
|
||||
assert_eq!(updated.fingerprint(), parsed.fingerprint(), "update_facts == update_file");
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
# change-debounce
|
||||
|
||||
## Goal
|
||||
|
||||
Stop paying a full reanalysis for every keystroke. Before this round each
|
||||
`textDocument/didChange` notification ran `set_document` immediately — lex,
|
||||
parse, `analyze`, `resolve_external`, lint, publish — so a burst of ten
|
||||
keystrokes cost ten of everything and nine of those answers were thrown away
|
||||
before anyone could read them. A `didChange` now only records the buffer's new
|
||||
text as *dirty*; the analysis runs at the first moment anything actually needs
|
||||
it: the next request, the next non-`didChange` notification, or a 150 ms
|
||||
quiet-period timer in the message loop. The buffer's **text** is still exactly
|
||||
current after every notification — only the analysis of it is deferred — so
|
||||
nothing that reads `didChange` results out of order can see a stale buffer.
|
||||
On a 10 000-line file one deferred keystroke saves 31 ms of work
|
||||
(`docs/perf/README.md`); a ten-keystroke burst saves nine of them.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A client sends a burst, not a single change.** Typing produces
|
||||
notifications faster than 150 ms apart; the debounce only pays off while
|
||||
that is true, and costs at most 150 ms of latency when it is not.
|
||||
- **150 ms is short enough not to be felt and long enough to coalesce a
|
||||
burst.** It is the same order as the debounce every mainstream language
|
||||
server uses. It is a constant (`CHANGE_DEBOUNCE` in `server.rs`), not a
|
||||
setting: a knob here would be one more thing to get wrong, and no user has
|
||||
asked for one (`TODO.md` §7, "no option explosion").
|
||||
- **Diagnostics are the one answer nobody requests.** A pushing client never
|
||||
asks for them, so waiting for "the next request" alone would leave a file
|
||||
undiagnosed indefinitely for a user who types and then stops. That is the
|
||||
whole reason the timer exists, rather than flushing only on demand.
|
||||
- **A flush is cheap to trigger from anywhere.** `flush_dirty` returns
|
||||
immediately when nothing is dirty, so the calls at the top of `request` and
|
||||
`notification` cost a `Vec::is_empty` on every message.
|
||||
- **Order within a burst does not matter, order across buffers does.** Dirty
|
||||
buffers are flushed oldest-first (`mark_dirty` replaces an entry in place
|
||||
rather than moving it to the back), so the sequence of `publish` calls a
|
||||
client sees for two edited files is the order they were first edited in.
|
||||
- **Losing an unanalyzed change with its buffer is correct.** `didClose`
|
||||
drops the buffer's pending text: there is nothing left to flush it into,
|
||||
and the client is not looking at the file any more. The drop happens at the
|
||||
*top* of `notification`, ahead of the universal flush — doing it in the
|
||||
`didClose` arm is too late, because the flush has already run by then (QA,
|
||||
CD-1). Closing one buffer says nothing about the others, so every other
|
||||
dirty buffer flushes on that same notification exactly as before.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Amends `docs/features/incremental-sync/README.md`'s pinned invariant.**
|
||||
That round promised "one `didChange` = one `set_document` = one generation
|
||||
bump, however many ranges". The promise is now: **one *flush* is one
|
||||
`set_document`, one generation bump and one `publish` per dirty buffer** —
|
||||
however many ranges *and however many notifications* were coalesced into it.
|
||||
Everything the old promise protected still holds: the generation counter
|
||||
(which is `docs/features/pull-diagnostics/README.md`'s whole `resultId`)
|
||||
never moves twice for work that happened once, and never fails to move for
|
||||
a buffer whose text changed. `incremental-sync`'s own test,
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`, still passes
|
||||
unchanged, because the test helper flushes after each notification — which
|
||||
is exactly the quiet-period timer firing.
|
||||
- **Observable consequence, pinned in `crates/lucisv_server/tests/e2e.rs`**
|
||||
(`incremental_changes_are_advertised_and_applied_over_the_wire`):
|
||||
**intermediate diagnostics states are no longer published**. Two changes
|
||||
arriving back to back — the first breaking a line, the second finishing it
|
||||
— used to produce three publishes (open, broken, fixed) and now produce two
|
||||
(open, composed). Every state that *is* published is a state the buffer
|
||||
really passed through; there are simply fewer of them. That test asserted
|
||||
the old count and now asserts the new one, with the reason written beside
|
||||
it.
|
||||
- **Consumes `sync::apply_changes` unchanged.** Ranged changes are composed
|
||||
against the newest text the server holds, which while a buffer is dirty is
|
||||
the *pending* text, not the last analyzed one. `Server::notification` looks
|
||||
in `dirty` before `workspace.document`. Nothing in `sync.rs` moved.
|
||||
- **Consumes `lsp_server`'s queue as a `std::sync::mpsc` receiver.** The
|
||||
timer is `Receiver::recv_timeout` on the queue `cancel-request` already
|
||||
introduced (`docs/features/cancel-request/README.md`); no thread and no
|
||||
timer object was added. A `Disconnected` receiver ends the loop exactly as
|
||||
the old `while let Ok(..)` did.
|
||||
- **Promises every request still sees the client's own changes.** The flush
|
||||
at the top of `Server::request` runs before dispatch, so a request answered
|
||||
after a `didChange` is answered from that change's analysis — the order
|
||||
contract the loop always had. The large-file fast path is behind that
|
||||
flush, not in front of it.
|
||||
- **No protocol change, no settings change, no index change.** The
|
||||
capabilities advertised at `initialize` are byte-identical.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `dirty: Vec<(Uri, String)>` on `Server` — newest text per buffer, in
|
||||
first-dirtied order.
|
||||
- [x] `mark_dirty` replaces in place, so a burst does not reorder buffers.
|
||||
- [x] `flush_dirty` — one `set_document` + one `publish` per dirty buffer.
|
||||
- [x] `didChange` composes ranges against the pending text when there is one.
|
||||
- [x] Flush on every request, before dispatch.
|
||||
- [x] Flush on every notification that is not a `didChange`.
|
||||
- [x] `CHANGE_DEBOUNCE` (150 ms) quiet-period flush in `run`, via
|
||||
`recv_timeout`, only while something is dirty.
|
||||
- [x] `didClose` drops the buffer's pending change — before the flush, so the
|
||||
drop is real (QA, CD-1), pinned by
|
||||
`closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`.
|
||||
- [x] Test: a burst is one reparse
|
||||
(`a_burst_of_changes_coalesces_into_one_reparse`).
|
||||
- [x] Server tests drive one notification at a time, so the test helper
|
||||
`change()` flushes — documented there as the timer firing.
|
||||
- [x] e2e: the publish count and the reason for it.
|
||||
- [ ] Not done: a flush for a *long* burst that never pauses (a paste-and-hold
|
||||
or a client replaying a file's history sends changes closer together
|
||||
than 150 ms forever). Today such a burst is analyzed when it ends or
|
||||
when the next request arrives. A "flush after N pending changes"
|
||||
backstop is the obvious answer if anyone ever reports it; it is not
|
||||
written because no client behaves that way and an untested backstop is
|
||||
worse than none.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev.** Implemented as part of the LSP performance round
|
||||
(plan: "Improve LSP performance + hover accuracy", part A1).
|
||||
|
||||
- The deferral is a `Vec`, not a `HashMap`: it holds one entry per *dirty*
|
||||
buffer, which is one in practice and two while a user alt-tabs. A linear
|
||||
scan of that is cheaper than hashing a `Uri`, and the `Vec` gives the flush
|
||||
order for free.
|
||||
- Deferred **analysis only, never text**. The alternative — deferring
|
||||
`apply_changes` too and keeping a queue of unapplied changes — was
|
||||
rejected: every reader of `Document::text` would then need to know about
|
||||
the queue, and the ones that forgot would be silently wrong. Composing the
|
||||
text eagerly keeps the pending state to exactly one `String` that only
|
||||
`didChange` and `flush_dirty` know about.
|
||||
- The flush points were chosen to be exhaustive rather than clever: *every*
|
||||
request and *every* notification except the one being deferred. Anything
|
||||
that needs analysis is downstream of one of those two, so there is no
|
||||
handler that has to remember to flush for itself.
|
||||
- `run` only arms the timeout while something is dirty, so an idle server
|
||||
still blocks in `recv()` and wakes for nothing.
|
||||
- The server unit tests drive notifications one at a time through a helper
|
||||
rather than through the loop, so no burst ever forms and nothing would
|
||||
flush them; the helper flushes explicitly, which is the timer's behavior.
|
||||
Three tests that hand-rolled a `didChange` notification were moved onto
|
||||
that helper.
|
||||
|
||||
**2026-08-28 — dev (QA fix).**
|
||||
|
||||
- **CD-1 — fixed.** The `didClose` arm's `dirty.retain` was dead code: the
|
||||
universal flush at the top of `notification` had already drained `dirty`
|
||||
through `std::mem::take` by the time the arm ran, so a buffer closed
|
||||
mid-edit paid a full `Document::new` and published its real diagnostics one
|
||||
line before the close cleared them. The retain moved to the top of
|
||||
`notification`, *ahead* of the flush, guarded on the method name; the arm's
|
||||
comment now says where the drop happened instead of pretending to do it.
|
||||
- The uri has to be read without consuming the notification, since
|
||||
`extract` takes it by value and the arm below still needs it. That is a
|
||||
four-line `closing_uri` beside `extract`, deserializing a clone of the
|
||||
params — a `didClose`'s params are a single uri, so the clone is not
|
||||
worth avoiding with a peek into the raw `Value`. `None` (params that do
|
||||
not parse) drops nothing, which is exactly what the arm below already
|
||||
does with the same params.
|
||||
- The "flush on every notification but `didChange`" rule is unchanged: the
|
||||
flush still runs for `didClose`, and every *other* dirty buffer still
|
||||
goes through it. What changed is only that the closing buffer is no
|
||||
longer in `dirty` when it does.
|
||||
- Pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`
|
||||
(`server.rs`): two buffers dirtied with text that would diagnose, one
|
||||
closed with no request in between; the generation bumps exactly once (the
|
||||
buffer still open), the closed buffer gets exactly one publish and it is
|
||||
the clearing one, and the other buffer's pending edit is published as
|
||||
usual. Verified the test fails on the pre-fix code — `left: 5, right: 4`
|
||||
on the generation assertion — before keeping it.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** Gates run and green: `cargo fmt --check`,
|
||||
`cargo clippy --all-targets --workspace -- -D warnings`, `cargo test
|
||||
--workspace` (0 failed everywhere; `lucisv_server`: 1179 passed, 19 ignored
|
||||
perf tests), `cargo test -p vlog_formatter` (114 passed). All findings below
|
||||
were reproduced with temporary `#[test]`s added to `server.rs`, run, and then
|
||||
removed once confirmed — none are left in the tree.
|
||||
|
||||
- **Finding CD-1 (medium — contradicts a checked-off invariant, wastes work,
|
||||
does not corrupt anything).** `didClose` does **not** actually drop a
|
||||
buffer's pending dirty change before analyzing it. `Server::notification`
|
||||
(`server.rs:1247`) flushes unconditionally for any non-`didChange` method
|
||||
(`server.rs:1253`, `if method != DidChangeTextDocument::METHOD { self
|
||||
.flush_dirty(); }`) — and `didClose` is such a method. That flush runs
|
||||
*before* the `match` statement even reaches the `DidCloseTextDocument::
|
||||
METHOD` arm (`server.rs:1407`), so by the time `self.dirty.retain(|(pending,
|
||||
_)| *pending != uri)` executes (`server.rs:1413`), `flush_dirty` has already
|
||||
drained `self.dirty` via `std::mem::take` — the retain is a no-op in the
|
||||
normal flow. Net effect: closing a buffer that was mid-edit costs one full,
|
||||
wasted reparse + `publish` of the real (about-to-be-discarded) diagnostics,
|
||||
immediately followed by the close handler's own `send_diagnostics(uri,
|
||||
Vec::new())` clearing them — **two** publishes instead of the zero extra
|
||||
ones the design claims. This directly contradicts both the checked-off
|
||||
status-line "`[x]` `didClose` drops the buffer's pending change" and the
|
||||
code comment beside the (dead) retain: "there is nothing left to flush it
|
||||
into" — there is, and it does get flushed.
|
||||
- Repro (temporary test, `server.rs`, removed after confirming): open a
|
||||
clean buffer (`module m;\nendmodule\n`), drain the open publish, note
|
||||
`generation`, send one `didChange` to `module m;\n wire ;\nendmodule\n`
|
||||
(introduces a parse error, buffer stays dirty — `generation` provably
|
||||
unchanged, `dirty` non-empty), then send `didClose` with **no** request
|
||||
in between (`session.notify`, which calls `Server::notification`
|
||||
directly, exactly the production path — no manual flush helper
|
||||
involved). Observed: `generation` bumps by exactly one during the
|
||||
`didClose` call (`2` → `3`), and `session.published()` returns **2**
|
||||
messages: one carrying the real parse-error diagnostic
|
||||
(`"expected identifier (found \";\")"`), then one with `diagnostics: []`.
|
||||
- Not a data-corruption bug — the client ends up with the correct final
|
||||
state (empty diagnostics for a closed file) — but it is a real,
|
||||
reproducible functional gap in exactly the case the debounce is supposed
|
||||
to help most: a user who edits and then immediately closes a buffer pays
|
||||
the full analysis cost the feature exists to avoid, silently. Left
|
||||
unfixed (not small/unambiguous — the right fix wants a decision about
|
||||
whether the top-of-`notification` flush should special-case `didClose`,
|
||||
or whether `didClose` should remove its own `dirty` entry *before* that
|
||||
flush runs, which touches the "flush on every notification but
|
||||
`didChange`" rule this round explicitly checked off).
|
||||
|
||||
- **Attack angles from the brief, checked and clean:**
|
||||
- *An un-flushed edge, generally.* Every request and every non-`didChange`
|
||||
notification flushes at its own top (`server.rs:1253` for notifications,
|
||||
the equivalent at the top of `request`), so the only genuinely
|
||||
un-flushed state is "nothing has asked for analysis yet" — which is
|
||||
exactly what the quiet-period timer exists to bound at 150 ms, and the
|
||||
documented, un-checked TODO item (a burst that never pauses) is real but
|
||||
already honestly disclosed, not silently missing.
|
||||
- *`didChange` on a file the client never opened.* `mark_dirty` does not
|
||||
require a prior `didOpen`, and neither did the pre-debounce
|
||||
`set_document` call it replaces — `flush_dirty`'s `set_document` creates
|
||||
the buffer exactly as before. No new behavior here.
|
||||
- *`didChange` racing `didSave`.* `didSave` is not `didChange`, so it
|
||||
flushes first (`server.rs:1253`) — a save's reindex always sees the
|
||||
latest edited text analyzed, never a stale buffer racing a fresh disk
|
||||
scan.
|
||||
- *Version-number ordering.* The server does not track LSP version numbers
|
||||
at all (`publishDiagnostics`'s own `version` field is hard-coded `None`
|
||||
at `server.rs:1848`, unchanged by this round) — nothing new to get out of
|
||||
order.
|
||||
- *Pending vs. analyzed text observed inconsistent by a request.* Cannot
|
||||
happen: `request` flushes before dispatch (`server.rs`'s `fn request`),
|
||||
so a request is always answered from the analysis of whatever is
|
||||
currently held, dirty or not.
|
||||
- *The `e2e.rs` publish-count change (3 → 2).* Confirmed the buffer
|
||||
genuinely passed through both published states and no diagnostic was
|
||||
lost: traced `incremental_changes_are_advertised_and_applied_over_the_wire`
|
||||
— the two `didChange` notifications and the `textDocument/formatting`
|
||||
request all arrive in one write to the mock transport, so the request's
|
||||
own top-of-`request` flush (or the burst's internal ordering) coalesces
|
||||
both notifications into the one flush that produces publish #2; publish
|
||||
#1 is the clean `didOpen`. The removed middle publish (the transiently
|
||||
*broken* half-edited state) was never a state a real, unhurried client
|
||||
would see anyway — it is the debounce's whole point.
|
||||
- *`a_burst_of_changes_coalesces_into_one_reparse`.* Re-derived by hand:
|
||||
`generation` provably does not move across the two-notification burst,
|
||||
then moves by exactly one at the first request after it, and `dirty` is
|
||||
empty afterward — matches the claimed semantics exactly.
|
||||
|
||||
- **Perf claims (A1's "before/after" in `docs/perf/README.md`).** Arithmetic
|
||||
over already-measured numbers, not a separate measurement — reviewed there,
|
||||
no finding.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted. Gates re-run independently of both agents:
|
||||
`cargo fmt --check` clean, `cargo clippy --all-targets --workspace -D
|
||||
warnings` silent, `cargo test --workspace` green.
|
||||
|
||||
The shape is right. Deferring analysis while applying text immediately is the
|
||||
standard split, and flushing before every request and before every
|
||||
non-`didChange` notification means no handler ever reads a stale buffer —
|
||||
today's correctness guarantee is preserved exactly, and only keystroke-storm
|
||||
reparses are coalesced. The quiet-period timer in `run()` matters as much as
|
||||
the coalescing: diagnostics are the one answer a client never asks for, so a
|
||||
burst that ends in silence still gets drawn.
|
||||
|
||||
QA's CD-1 was a real finding and correctly diagnosed: the universal flush ran
|
||||
*before* the `didClose` arm, so the arm's `retain` was dead and a buffer
|
||||
closed mid-burst paid a full `Document::new` and published diagnostics for a
|
||||
file the user had stopped looking at, only to clear them a line later. The
|
||||
fix drops the pending text ahead of the flush rather than special-casing the
|
||||
flush, which keeps "every other dirty buffer still flushes" true by
|
||||
construction. The dev verified the pinning test fails on pre-fix code before
|
||||
keeping it; that is the right standard.
|
||||
|
||||
The one honest cost is recorded in `docs/perf/README.md` and is not hidden: a
|
||||
keystroke with *nothing* following it now publishes at 164 ms rather than one
|
||||
flush, because it waits out the 150 ms quiet period. Any request flushes
|
||||
early, so a real editor sees 4.35 ms / 37.6 ms instead — but the regression
|
||||
is real for a client that asks for nothing, and the number is written down
|
||||
rather than argued away.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,418 @@
|
||||
# hover-declarations
|
||||
|
||||
## Goal
|
||||
|
||||
Hovering a name declared in **this** file has always shown the declaration
|
||||
itself — `local_text` prints the kind, the name and the source lines
|
||||
`decl_span` covers. Hovering a name declared in *another* file showed only
|
||||
`**port** — declared in `sub.sv:3``: enough to navigate to, not enough to read.
|
||||
The owner's ask (2026-08-27) is that the cross-file card carry the declaration
|
||||
too — for a port its direction, type and width, `input logic [7:0] addr` — so
|
||||
that reading a connection list does not require jumping out of the file. This
|
||||
round adds a fenced `systemverilog` snippet of the declaration's source line(s)
|
||||
under each candidate's existing heading, fetched at hover time and omitted
|
||||
entirely whenever it could be the wrong line.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The index stays text-free.** `Def` is `{file, name_span, kind}` and the
|
||||
persisted facts and `FACTS_FORMAT` are untouched
|
||||
(`docs/features/workspace-index/README.md`,
|
||||
`docs/features/index-persistence/README.md`). A hover is a rare, one-name,
|
||||
human-speed request; reading one file to answer it is the same trade
|
||||
`locate::line_number` has always made for the `file:line` half of the card.
|
||||
- **`reference.name` is the declared name.** Every `Definition::External`
|
||||
answer comes from a reference (`ExternalResolutions::definition_of` looks the
|
||||
target up by `ReferenceId`), and `resolve_external` finds the `Def` by
|
||||
passing exactly that `name` to `WorkspaceIndex::units` / `member`. So the
|
||||
name is the bare declared spelling — `WIDTH` for a `p::WIDTH` use, `clk` for
|
||||
a `.clk(...)` connection — never a qualified path. That is what makes it
|
||||
usable as the guard's expected text.
|
||||
- **Disk text is what the index was built from.** `Workspace::text_of` prefers
|
||||
an open buffer, which is right for a location and wrong for a snippet, so the
|
||||
open case is handled separately and never reaches `text_of`.
|
||||
- **A `decl_span` may be enormous.** A module's `decl_span` is its whole body
|
||||
(`bind_module` passes the item span), and one netlist line has no bound at
|
||||
all — hence the two caps below.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed**
|
||||
|
||||
- `crate::nav::indexed_def_for_symbol` — raised from private to `pub(crate)`,
|
||||
behaviour byte-for-byte unchanged. `nav.rs` walks it live-symbol → indexed
|
||||
`Def`; this feature walks the same relation the other way (scan the open
|
||||
buffer's symbols for the one that maps to this `Def`), which is precisely
|
||||
what `nav.rs`'s own `include_declaration` block already does for the
|
||||
declaration location. One matcher, so a hover snippet and a
|
||||
go-to-definition can never disagree about which declaration is which.
|
||||
- `Workspace::document_for_path`, `Workspace::text_of`, `WorkspaceIndex::path`.
|
||||
- `crate::convert::Positions::whole_lines`, `vlog_parser::LineIndex`.
|
||||
- `vlog_semantic::{Def, Symbol}` — read only; nothing added to either.
|
||||
|
||||
**Promised**
|
||||
|
||||
- `nav.rs` keeps its behaviour: the visibility change is the only edit to it,
|
||||
and its whole test module stays green unmodified.
|
||||
- The `` ```systemverilog `` fence tag is used for the new block, as the
|
||||
fence-tag contract in `docs/features/lucisv-server/README.md` requires — it
|
||||
is the only thing that colours a hover card.
|
||||
- Nothing is added to `Def`, to the facts file, or to `FACTS_FORMAT`; a cache
|
||||
written before this round is still current after it.
|
||||
**Superseded 2026-08-28 by `docs/features/port-detail-spans/README.md`**,
|
||||
which adds `Def::detail_span`, writes it in every declaration record and
|
||||
bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is
|
||||
discarded. This round's own promise held while it was this round's to
|
||||
make; the index is text-free either way (a span is not text).
|
||||
- The heading line `**label** — declared in `file:line`` is unchanged, so a
|
||||
client (or a test) reading only that half sees exactly what it saw before.
|
||||
|
||||
## How the snippet is fetched
|
||||
|
||||
`declaration_snippet(ws, def, name)` in `hover.rs`, once per candidate:
|
||||
|
||||
1. **The target file is open** (`ws.document_for_path`). The index's span is
|
||||
against that file's *last saved* text, so an unsaved edit above the
|
||||
declaration has already moved it and reading the buffer at `def.name_span`
|
||||
would print whatever those offsets now cover. Match the `Def` to a live
|
||||
symbol **logically** instead — same name, and `indexed_def_for_symbol` maps
|
||||
it back to this same `Def` — and widen that symbol's live `decl_span` to
|
||||
whole lines.
|
||||
2. **Not open**: `ws.text_of(path)` (disk, since no buffer backs it), a fresh
|
||||
`LineIndex`, and `def.name_span` widened to whole lines.
|
||||
3. **Guard, both paths.** Slice the chosen text at the chosen name span and
|
||||
require it to equal the hovered name. `str::get` returns `None` for a span
|
||||
that runs past the text or lands mid-character, so a stale or shifted span
|
||||
fails the check rather than panicking. Any failure — unreadable file, no
|
||||
live symbol, text that does not spell the name — drops the snippet and
|
||||
leaves today's card exactly as it was. **A hover must never lie; less
|
||||
information beats wrong information.**
|
||||
|
||||
Note the asymmetry, and that it is deliberate: the open path widens
|
||||
`decl_span` (mirroring `local_text`, which is the only span a live symbol
|
||||
offers that covers a whole multi-line declaration), the disk path widens
|
||||
`def.name_span` (the only span the index holds). For the declarations the ask
|
||||
is about — ports, parameters, typedefs, a module header — both are one line
|
||||
and the two paths print the same thing.
|
||||
|
||||
## Cutting it down
|
||||
|
||||
`cut_to_size` trims trailing blank space (as `local_text` does; leading
|
||||
indentation stays, so the line reads as written) and then applies two caps,
|
||||
each with its own note under the fence:
|
||||
|
||||
| Cap | Value | Why |
|
||||
|---|---|---|
|
||||
| lines | `SNIPPET_LINES` = 5 | a module's `decl_span` is its whole body |
|
||||
| characters | `SNIPPET_CHARS` = 400 | one netlist line can be megabytes |
|
||||
|
||||
A cut appends ` …` inside the fence and `*shown to N lines*` /
|
||||
`*shown to N characters*` after it — the same shape as the macro card's
|
||||
`*truncated at N characters*`, so the two footnotes read as one convention.
|
||||
The character cap counts `char`s and cuts on a boundary.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `declaration_snippet` with the open-buffer and disk paths.
|
||||
- [x] Guard on both paths; snippet omitted on any mismatch.
|
||||
- [x] Line and character caps with a note.
|
||||
- [x] One snippet per candidate for an ambiguous name.
|
||||
- [x] `indexed_def_for_symbol` shared with `nav.rs`, behaviour unchanged.
|
||||
- [x] Tests (9 new, in `hover.rs`'s own test module).
|
||||
- [x] Hover row + hover section in `docs/features/lucisv-server/README.md`.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- Not done, deliberately: no facts/cache change, nothing in `vlog_semantic`,
|
||||
no TODO.md edit (no existing checklist item covers this; §8's hover items
|
||||
are all already checked, and inventing one is out of scope).
|
||||
- [x] **2026-08-28**: one disk read per file per hover (`disk_view` memo);
|
||||
QA finding 4 closed.
|
||||
- [x] **2026-08-28**: `live_symbol` (and `nav::indexed_references`) look a
|
||||
name up instead of scanning every symbol, with the first-match
|
||||
tie-break pinned by test.
|
||||
- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior
|
||||
`\r` into the fence; QA finding 2 closed.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev
|
||||
|
||||
- Read the brief, `hover.rs`, `nav.rs`, `state.rs` and `convert.rs`. Confirmed
|
||||
the two facts the design rests on: `set_document` does **not** rebuild the
|
||||
index (so an open buffer really can hold a span the index does not know
|
||||
about — the case step 1 exists for), and `follow_one` looks a `Def` up by
|
||||
`reference.name`, which is what licenses using that name as the guard's
|
||||
expected text rather than trying to recover a name from `Def`.
|
||||
- Added `declaration_snippet`, `live_symbol`, `span_text`, `fenced` and
|
||||
`cut_to_size` to `hover.rs`, plus the two caps as consts. `symbol_hover`'s
|
||||
`External` arm now appends the snippet to each candidate's part; the heading
|
||||
it appends to is untouched.
|
||||
- Raised `nav::indexed_def_for_symbol` to `pub(crate)` with a doc line naming
|
||||
the second caller. No other change to `nav.rs`.
|
||||
- Decision: the open path uses `decl_span` and the disk path `name_span`,
|
||||
per the brief. Considered using `name_span` on both for symmetry — it would
|
||||
make a big module's card one header line rather than five — but that would
|
||||
drop the live-buffer case's only handle on a multi-line declaration, and the
|
||||
line cap already bounds the damage. Recorded in *How the snippet is fetched*
|
||||
so the asymmetry is a decision and not an accident.
|
||||
- Decision: no fallback from the open path to disk text. If a file is open and
|
||||
no live symbol matches, the buffer has been edited past the index and the
|
||||
indexed span is exactly the thing that cannot be trusted; falling back would
|
||||
re-introduce the wrong-line risk the guard exists to remove.
|
||||
- Nine tests added (listed below). Ran the gates: fmt
|
||||
clean, clippy `--all-targets` clean, `cargo test --workspace` green at 2372
|
||||
passed / 0 failed / 12 ignored.
|
||||
|
||||
**Tests added** (all in `crates/lucisv_server/src/hover.rs`, `mod tests`):
|
||||
|
||||
| Test | Pins |
|
||||
|---|---|
|
||||
| `a_cross_file_port_connection_shows_the_ports_own_declaration_line` | the ask: direction + type + width, and only that port's line |
|
||||
| `a_cross_file_module_instance_shows_its_header_line` | the module header, disk path |
|
||||
| `a_package_member_shows_its_declaration_line` | a `localparam` and a `typedef` through `import p::*` |
|
||||
| `an_unsaved_edit_that_moved_the_declaration_is_read_at_its_live_span` | live line, not the stale-span line (asserts the *new* width and the absence of the old) |
|
||||
| `a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line` | guard, disk half: file rewritten under a live index → no fence at all, heading intact |
|
||||
| `an_open_buffer_that_no_longer_declares_the_name_drops_the_snippet` | guard, live half: the port renamed away in the buffer |
|
||||
| `a_very_long_declaration_line_is_cut_with_a_note` | the character cap and its note |
|
||||
| `a_declaration_spanning_many_lines_is_cut_at_the_line_limit` | the line cap, via an open module whose `decl_span` is its body |
|
||||
| `two_files_declaring_one_name_each_get_their_own_snippet` | ambiguous name: both headings, both snippets |
|
||||
|
||||
### 2026-08-28 — dev (performance: one disk read, one name lookup)
|
||||
|
||||
Parts A2 and A3 of the "Improve LSP performance + hover accuracy" round.
|
||||
Behavior of every card is unchanged; both items are the same answer, reached
|
||||
with less work. Numbers in `docs/perf/README.md`.
|
||||
|
||||
- **A2 — one read per file per hover.** A hover into a *closed* file used to
|
||||
read that file and build a `LineIndex` over it twice: once in
|
||||
`locate::line_number` for the `file:line` heading, once in
|
||||
`declaration_snippet` for the fenced lines. This is QA's finding 4 below,
|
||||
and it is now closed. `symbol_hover` holds a per-request memo — one
|
||||
`(path, text, LineIndex)` in `disk_view` — that the heading and the snippet
|
||||
both read, and `declaration_snippet` no longer touches the disk at all: it
|
||||
is now the *open-buffer* path only, with the closed-file path inlined in
|
||||
`symbol_hover` beside the heading it shares a read with. The
|
||||
`spells_exactly` guard applies on both paths exactly as before. A card
|
||||
naming one file twice (two declarations in one file) now pays for one read,
|
||||
not two, which is why the memo is keyed by path rather than being a single
|
||||
`Option` per candidate.
|
||||
- Measured: 34 ms → 16.3 ms on QA's own 31.7 MB measurement, and 141 µs of
|
||||
a 148 µs hover at 10 000 lines is that one read. See `docs/perf`.
|
||||
- QA's measurement test was renamed
|
||||
`hovering_into_a_large_closed_file_reads_it_twice` →
|
||||
`..._reads_it_once`, since the doubling it was named for is gone. The QA
|
||||
log below still names the old spelling; that section is QA's to amend.
|
||||
- **A3 — `live_symbol` stops scanning every symbol.** Walking the whole
|
||||
buffer's symbol table and calling `nav::indexed_def_for_symbol` (two index
|
||||
lookups) on every symbol whose name happened to match — and reaching every
|
||||
symbol whose name did not — became a name-keyed lookup:
|
||||
`vlog_semantic::Semantics::symbols_named(name)`, two binary searches over a
|
||||
side table of symbol ids sorted by name, built once during `analyze`. Only
|
||||
same-named declarations are probed. A side table rather than a
|
||||
`HashMap<String, Vec<SymbolId>>` so that `Semantics` — which is cloned per
|
||||
document — does not carry a second copy of every name it already holds;
|
||||
four bytes per symbol against a `String` per symbol.
|
||||
- **The tie-break is preserved.** The map's lists are built by walking the
|
||||
symbols in order, so `symbols_named` yields declaration order — the same
|
||||
order, and the same first match, the old `symbols().iter().find(..)`
|
||||
made. Pinned by `looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
|
||||
in `crates/vlog_semantic/tests/semantics.rs`, which compares the two
|
||||
answers directly and asserts the earlier declaration comes first. QA's
|
||||
`duplicate_live_declarations_of_one_name_pick_the_first_one_silently`
|
||||
(finding 3 below) still passes, unchanged.
|
||||
- `nav.rs`'s `indexed_references` had the same scan-by-name for the
|
||||
declaration's live span; it is the same swap and was made in the same
|
||||
change, for the same reason.
|
||||
- `vlog_refactor::ports.rs:1154` has a third one (`symbols().iter()
|
||||
.position(|s| s.name == port && …)`). It is not a trivial swap — the
|
||||
predicate carries a kind and a span test and the code wants the
|
||||
*position* as a `SymbolId` — and it is in another crate, so it is left
|
||||
alone and recorded here rather than done.
|
||||
- Cost: four bytes per symbol. Measured saving on the lookup alone:
|
||||
8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`).
|
||||
|
||||
### 2026-08-28 — dev (CRLF, closing QA finding 2)
|
||||
|
||||
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
|
||||
`\r` inside the fence — is **fixed**, as part of `port-detail-spans`' PDS-4.
|
||||
Every line a card shows now goes through `attached_lines`, which strips a
|
||||
trailing `\r` as it composes each line; that covers both this feature's
|
||||
snippet path and `local_text`'s in-file path, which QA named as having the
|
||||
same property, because both reach it through `fenced_sections`. Display
|
||||
text only: no buffer is written.
|
||||
- QA's pinned regression test was named for the old behaviour
|
||||
(`a_crlf_multiline_snippet_keeps_interior_carriage_returns`) and asserted
|
||||
it; it is now `a_crlf_multiline_snippet_carries_no_carriage_returns` and
|
||||
asserts the opposite, plus that the lines read as written. The QA log below
|
||||
still names the old spelling; that section is QA's to amend.
|
||||
- No other change to this feature. `spells_exactly`, the caps and the
|
||||
disk/live split are untouched.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA
|
||||
|
||||
Read the brief, the dev's Work log, and `crates/lucisv_server/src/hover.rs` /
|
||||
`nav.rs` in full. Ran the gates first (all green before any probing): `cargo
|
||||
fmt --check` clean, `cargo clippy --all-targets --workspace -- -D warnings`
|
||||
clean, `cargo test --workspace` green — 1173 passed / 0 failed / 12 ignored
|
||||
(pre-existing) before this round's own probes were added.
|
||||
|
||||
Then attacked `declaration_snippet`, `live_symbol`, `span_text` and
|
||||
`cut_to_size` along the seven angles in the charter. Eight probe tests added
|
||||
to a new `mod qa_hover_declarations` in `hover.rs` (one `#[ignore]`d perf
|
||||
measurement); one real defect found and fixed with a ninth test pinning it.
|
||||
|
||||
**Finding 1 — MEDIUM, fixed.** *The guard was a fixed-length substring check,
|
||||
not a whole-identifier check, so an edit that only **extends** a name defeats
|
||||
it.* `declaration_snippet`'s guard (`hover.rs:243` and `:252`, before the fix)
|
||||
compared `span_text(text, span)` — a slice of exactly `name.len()` bytes at
|
||||
the *old, recorded* offset — against `name`. `def.name_span`'s length is
|
||||
whatever the name was when the index was last built; it does not grow if the
|
||||
file is edited without a reindex. So: index built on `input logic [7:0]
|
||||
addr;`, then the file is rewritten on disk to `input logic [7:0] addr2;`
|
||||
*without* triggering a reindex (an ordinary edit-then-hover-before-save-event
|
||||
race, exactly the staleness window this feature's guard exists for). The old
|
||||
span still covers exactly the four bytes `"addr"` — a *prefix* of the new
|
||||
`"addr2"` — so `span_text` returns `Some("addr")`, equals the hovered name,
|
||||
and the guard passed. The card for `.addr(...)` then showed
|
||||
`` input logic [7:0] addr2 `` under a heading that says `addr`'s declaration,
|
||||
one line pretending to be a name it is not — exactly the masked-corruption
|
||||
shape CLAUDE.md's invariant 4 is about, applied to this round's new safety
|
||||
net rather than `verify.rs`.
|
||||
- Repro (was a failing/panicking assertion, now a passing regression test):
|
||||
`a_disk_edit_that_only_appends_to_the_name_defeats_the_guard`,
|
||||
`hover.rs:1060`.
|
||||
- Fix: added `spells_exactly` (`hover.rs:293`) and `continues_a_name`
|
||||
(`hover.rs:306`), and switched both guard call sites
|
||||
(`declaration_snippet`'s live and disk branches) to it. It keeps the
|
||||
existing text-equality check and additionally requires that the
|
||||
character immediately outside the span on either side (if any) is not an
|
||||
identifier-continuation character (`[A-Za-z0-9_$]`) — turning a
|
||||
prefix/suffix match back into a miss. Applied to *both* branches for one
|
||||
guard, one guarantee, even though the live branch's `symbol.name_span`
|
||||
(a token span from a fresh parse) could not actually suffer this —
|
||||
`symbol.name == name` was already checked before the span comparison, so
|
||||
the length always matched there. No behavior change for any span that is
|
||||
a genuine whole identifier, which is every case the dev's 9 tests and the
|
||||
existing corpus tests exercise — full `cargo test --workspace` stayed
|
||||
green (1173 passed / 0 failed / 13 ignored, the 13th being this round's
|
||||
own perf probe) after the fix.
|
||||
- This does **not** close every staleness gap by design — a same-length
|
||||
edit that changes an identifier into a different same-length identifier,
|
||||
or that changes what a name's *kind* means without renaming it, is still
|
||||
the accepted risk window the Assumptions section already names ("a hover
|
||||
is a rare, one-name, human-speed request"). What the fix removes is
|
||||
specifically the case where the *shown text visibly disagrees with the
|
||||
name in the heading* — the one the guard's stated promise ("never show a
|
||||
wrong line") is about.
|
||||
|
||||
**Finding 2 — LOW, filed, not fixed.** *A CRLF file's multi-line snippet
|
||||
keeps the embedded `\r` on every interior line, only the last one is
|
||||
trimmed.* `cut_to_size` (`hover.rs`, unchanged by QA) calls `trim_end()` once
|
||||
on the whole cut string, which strips a *trailing* `\r` (and `\n`) but not an
|
||||
interior one before a kept newline. `local_text` (the in-file branch,
|
||||
pre-existing, not part of this round) has the identical property via the same
|
||||
`whole_lines`/`trim_end` shape, so this is not new behavior introduced by
|
||||
this feature, just newly reachable from a second call site. Cosmetic, not a
|
||||
correctness break: the bytes shown are exactly the file's own bytes, and a
|
||||
fenced code block renders them close to verbatim either way. Pinned as a
|
||||
permanent regression test rather than fixed, since a real fix (stripping
|
||||
`\r` before every kept `\n`, in both `local_text` and here) is a
|
||||
cross-cutting change to shared rendering, out of this round's stated scope
|
||||
(`hover.rs`'s `External` arm and its shared helper with `nav.rs`).
|
||||
- Repro: `a_crlf_multiline_snippet_keeps_interior_carriage_returns`,
|
||||
`hover.rs:1156`.
|
||||
|
||||
**Finding 3 — LOW/accepted, pinned as a regression test, not a defect of this
|
||||
round.** *Two live declarations of the same name+kind in one open buffer (a
|
||||
transient mid-edit state, e.g. a duplicate line not yet deleted) make
|
||||
`live_symbol`'s `.find()` pick whichever comes first in `Semantics::symbols()`
|
||||
order, silently.* `indexed_def_for_symbol` (`nav.rs:164`, visibility-only
|
||||
change this round) maps *any* live symbol with a matching name/kind/owner
|
||||
back to the single persisted `Def` for that name when the index itself has
|
||||
only one — it does not know or care that the *live* buffer momentarily has
|
||||
two. This is inherited, unchanged behavior from `nav.rs`'s existing
|
||||
go-to-definition matcher (the Handshakes section calls this out on purpose:
|
||||
"one matcher, so a hover snippet and a go-to-definition can never disagree").
|
||||
Not a lie in the sense the guard is about — the guard still requires the
|
||||
*chosen* symbol's own span to spell the name exactly, which it always does
|
||||
here by construction — but it is a silent, unsignaled choice between two
|
||||
candidates. Filed rather than fixed: fixing it means changing
|
||||
`indexed_def_for_symbol`'s matching rule, which is nav.rs's and explicitly
|
||||
out of this round's scope ("nav tests must stay green," brief line 27).
|
||||
- Repro: `duplicate_live_declarations_of_one_name_pick_the_first_one_silently`,
|
||||
`hover.rs:1126`.
|
||||
|
||||
**Finding 4 — perf note, not a defect, no action taken.** *A hover resolving
|
||||
into a large closed file reads the file and builds a `LineIndex` over it
|
||||
twice*: once inside `locate::line_number` (for the `file:line` heading — this
|
||||
predates this round) and again inside `declaration_snippet` (for the
|
||||
snippet — new this round), independently, from the same disk path. Measured
|
||||
in release mode: a 31.7 MB synthetic file (600k filler lines behind a small
|
||||
port declaration, `maxFileSize` raised so it indexes at all) took 34 ms for
|
||||
one hover — acceptable for a rare, single-shot request, but a real, avoidable
|
||||
doubling of I/O and linear scan work per disk-path candidate. A fix would
|
||||
mean threading one read/`LineIndex` through both `line_number` and
|
||||
`declaration_snippet`, which touches `locate.rs` (also used by `macro_hover`)
|
||||
and is a small refactor rather than a one-line change — noted per the
|
||||
charter's "note it, don't redesign" rather than attempted.
|
||||
- Measurement, `#[ignore]`d (writes ~30 MB, not a correctness assertion):
|
||||
`hovering_into_a_large_closed_file_reads_it_twice`, `hover.rs:1325`. Run
|
||||
with `cargo test --release -p lucisv_server large_closed -- --ignored
|
||||
--nocapture`.
|
||||
- **Amended 2026-08-28 — QA.** Closed by A2 (`docs/perf/README.md`):
|
||||
`symbol_hover`'s `disk_view` memo now shares one read + one `LineIndex`
|
||||
between the heading and the snippet. Re-ran the same measurement (now
|
||||
named `..._reads_it_once`): **17.0 ms**, against the documented
|
||||
"34 ms → 16.3 ms" — matches within the run-to-run noise `docs/perf/
|
||||
README.md` itself calls out. No longer an open finding.
|
||||
|
||||
**Verified, no finding** (angles from the charter that turned up nothing):
|
||||
UTF-8 multi-byte content before a declaration, on the same file, does not
|
||||
panic `span_text`/`whole_lines` (`multibyte_utf8_before_the_declaration_does_not_panic`,
|
||||
`hover.rs`) — both are `.get()`-based and this stayed a belt-and-braces pin.
|
||||
A declaration at byte offset 0 and a declaration on the file's last line with
|
||||
no trailing newline both render correctly, no underflow
|
||||
(`a_declaration_at_the_very_start_of_the_file_is_shown`,
|
||||
`a_declaration_on_the_last_line_with_no_trailing_newline_is_shown`). The line
|
||||
cap (`SNIPPET_LINES` = 5) and character cap (`SNIPPET_CHARS` = 400) are both
|
||||
exact-boundary-safe — 5 lines / 400 chars is not cut, 6 lines / 401 chars is,
|
||||
and a 400-char boundary landing mid multi-byte character is not split because
|
||||
`cut_to_size` counts with `char_indices`, never raw bytes
|
||||
(`exactly_the_line_cap_is_not_cut_one_more_is`,
|
||||
`exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe`). A
|
||||
case-mismatched open buffer (same file, different-case path on a
|
||||
case-insensitive filesystem) is not recognized as "the target file open" by
|
||||
`document_for_path`'s exact `PathBuf` equality, so it falls back to the disk
|
||||
path rather than mixing the two identities — the safe direction, confirmed
|
||||
with unsaved edits in the mismatched buffer never leaking into the card
|
||||
(`a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk`,
|
||||
macOS/Windows-gated). Multiple ambiguous candidates each render from their
|
||||
own file with no cross-contamination — the dev's own
|
||||
`two_files_declaring_one_name_each_get_their_own_snippet` already covers
|
||||
this and reads fine without a divider between candidates (each fenced block
|
||||
is its own visual unit).
|
||||
|
||||
**Gates, final.** `cargo fmt --check` clean. `cargo clippy --all-targets
|
||||
--workspace -- -D warnings` clean. `cargo test --workspace`: 1173 passed / 0
|
||||
failed / 13 ignored (12 pre-existing + this round's one perf probe).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-27 — lead.** Reviewed the full diff after QA's SHIP verdict;
|
||||
gates re-run independently (fmt clean, clippy silent, 1173 server tests
|
||||
green). The shape is right: no widening of persisted facts, snippets
|
||||
fetched at hover time from whichever text the span is valid against
|
||||
(live logical match through `nav.rs`'s one matcher, disk otherwise),
|
||||
and a guard that prefers no snippet to a wrong one. QA's MEDIUM find —
|
||||
the fixed-length substring guard passing on a name that had merely been
|
||||
*extended* in place — is precisely the masked-corruption shape
|
||||
invariant 4 exists for, applied correctly to a new forgiveness path
|
||||
outside `verify.rs`; the `spells_exactly` boundary check closes it on
|
||||
both the live and disk paths and the attack test pins it. The
|
||||
deliberate asymmetry (live path shows `decl_span`, disk path the name's
|
||||
line) is documented and bounded by the caps; the duplicate-live-symbol
|
||||
tie-break is inherited from the shared matcher and correctly pinned
|
||||
rather than re-designed. The CRLF interior-`\r` cosmetic and the
|
||||
double-read of large closed files are accepted as filed. Accepted;
|
||||
committed by the lead.
|
||||
@@ -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.
|
||||
@@ -75,6 +75,15 @@ slice that can panic.
|
||||
and no bump would let a changed buffer answer "unchanged". One notification =
|
||||
one reparse = one stamp = one `publish`. Pinned by
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`.
|
||||
**Amended 2026-08-28 by `docs/features/change-debounce/README.md`**: a
|
||||
`didChange` now records the composed text as dirty and the analysis runs at
|
||||
the next flush, so the promise reads **one *flush* is one `set_document`,
|
||||
one generation bump and one publish per dirty buffer** — however many
|
||||
ranges *and however many notifications* it coalesced. What the promise
|
||||
protects is unchanged: the counter never moves twice for work done once and
|
||||
never fails to move for a buffer whose text changed. The test above still
|
||||
passes as written; its helper flushes after each notification, which is the
|
||||
quiet-period timer firing.
|
||||
- **Changes what the client is told at `initialize`.**
|
||||
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
|
||||
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,692 @@
|
||||
# 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.
|
||||
**Amended again (index-scope, 2026-08-28):** a third arm,
|
||||
`IndexEvent::Analyzed`, for a file that went into the index from an **open
|
||||
buffer's own finished analysis** rather than from a parse or from the store.
|
||||
Its log line reads `analyzed: <path>`; its bar tick is identical again. It
|
||||
deliberately adds **no** clause to the end message — one file out of a
|
||||
workspace is not why a scan finished fast, and "N from cache" keeps meaning
|
||||
the persistent store and nothing else, which is the sentence
|
||||
`index-persistence`'s e2e transcripts assert. See
|
||||
`docs/features/index-scope/README.md`.
|
||||
- `begin` still carries **no** percentage: the first honest one is the first
|
||||
file's.
|
||||
|
||||
### `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.
|
||||
@@ -0,0 +1,440 @@
|
||||
# interactive-latency
|
||||
|
||||
## Goal
|
||||
|
||||
Make the request and notification paths a user *feels* — the ones that run
|
||||
while they type and move the cursor — cost what they have to cost and no
|
||||
more, and say with measured numbers where the rest of the time goes. Round 1
|
||||
(`docs/perf/README.md`) established the baseline and named the open question
|
||||
it could not answer from inside the crate: what a `didChange` →
|
||||
`publishDiagnostics` round trip actually takes over the wire. This round
|
||||
answers that, breaks one flush down stage by stage, and takes the
|
||||
identity-safe wins the breakdown justifies — which turned out to be six token
|
||||
lookups that were sweeping the whole buffer for something a binary search
|
||||
answers in twenty nanoseconds. Nothing on the parse path was touched: the
|
||||
measurements say the remaining cost is lexing and parsing, and that is a
|
||||
change this round deliberately does not make.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The token stream rises and never overlaps.** Every binary search added
|
||||
here rests on one property of `Document.tokens`: the lexer emits tokens in
|
||||
source order, so `end[i] <= start[i+1] <= end[i+1]` and both
|
||||
`span.start < offset` and `span.end < offset` are monotone predicates over
|
||||
the vector. That is the whole precondition `partition_point` needs, and it
|
||||
is pinned by `state::tests::the_token_stream_rises_and_never_overlaps` —
|
||||
the test that would fail first if the lexer ever changed shape. Nothing
|
||||
here assumes tokens are non-empty: the `Eof` sentinel is zero-width, and
|
||||
every argument below survives it.
|
||||
- **No benchmark dependency**, unchanged from round 1: `std::time::Instant`,
|
||||
`#[ignore]`d tests, no `criterion`. `CLAUDE.md` requires a written
|
||||
justification for a new dependency and there is none to write.
|
||||
- **A measurement asserts nothing about duration.** A test that fails when
|
||||
the machine is busy is a test that gets deleted.
|
||||
- **The e2e round trip is a real session.** It spawns the shipped binary and
|
||||
speaks framed JSON-RPC at it, so the number includes the pipes, the JSON,
|
||||
the debounce timer and the flush. It cannot be taken from inside the crate,
|
||||
which is exactly why round 1 could not take it.
|
||||
- **The generated module is uniform, and real RTL is not.** Both generators
|
||||
build the same repeated four-line block. The numbers are a scale, not a
|
||||
prediction for any given file.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser` → this crate (consumed, unchanged).** The binary searches
|
||||
consume the ordering property of `tokenize`'s output described above.
|
||||
Nothing was asked of `vlog_parser` and nothing in it changed. If it ever
|
||||
emits tokens out of order, the pinning test in `state.rs` fails before any
|
||||
handler answers wrongly.
|
||||
- **`state.rs` → `selection.rs`, `on_type.rs`, `completion.rs` (new,
|
||||
internal).** Two free functions, `first_token_reaching` and
|
||||
`first_token_from`, are published from `state.rs` beside `Document`. They
|
||||
are the single place the monotonicity argument is written down; every call
|
||||
site is one comparison on top of one of them. `inline.rs` uses a third
|
||||
predicate (`span.end <= offset`) written at its own call site, because it
|
||||
has one user and its own local proof.
|
||||
- **`e2e.rs`'s `Live::finish` now returns the publish count** it saw on the
|
||||
way out. Existing callers ignore the value, which compiles unchanged. The
|
||||
count is what turns "the debounce coalesces a burst" from arithmetic into a
|
||||
measurement.
|
||||
- **Two copies of one generator.** `perf::generated_module` and the copy in
|
||||
`tests/e2e.rs` must stay the same shape, or the in-crate table and the
|
||||
over-the-wire table in `docs/perf/README.md` stop being readable against
|
||||
one another. `lucisv_server` is a binary crate, so an integration test
|
||||
cannot import the original; the copy is commented as such at both ends.
|
||||
- **Nothing was asked of `vlog_linter`.** The lint pass costs 1.40 ms of a
|
||||
32 ms flush at 10 000 lines and walks the tree once per rule; that is
|
||||
recorded in `docs/perf/README.md` as a future round's work, not requested
|
||||
here.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Phase 1 — a stage-by-stage breakdown of one flush at 1k and 10k lines:
|
||||
`tokenize`, `tokens.clone()`, `parse_tolerant`, `collect_defines`,
|
||||
`analyze`, `resolve_external`, `LineIndex::new`, and the
|
||||
`diagnostics::all` pass a publish runs (which is *not* inside
|
||||
`Document::new`, and which round 1's table did not account for).
|
||||
`perf::breaking_down_one_flushed_keystroke`.
|
||||
- [x] Phase 1 — the end-to-end round trip round 1 listed as its own open
|
||||
TODO: `didChange` → `publishDiagnostics` against the real binary, for a
|
||||
single change, for a burst of ten, and for the change-then-request
|
||||
shape a real editor produces.
|
||||
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`.
|
||||
- [x] Phase 2 — six token lookups swapped from a sweep to a binary search,
|
||||
each with a test that walks **every byte** of a buffer written to have
|
||||
plenty of touching tokens and asserts the search returns exactly what
|
||||
the sweep returned.
|
||||
- [x] Phase 2 — the three sweeps that are inherent left alone, with the
|
||||
reason written down (below).
|
||||
- [x] Phase 3 — decided against every change the breakdown did not justify,
|
||||
with the number for each (below).
|
||||
- [x] Phase 4 — `docs/perf/README.md` refreshed: both of round 1's open
|
||||
TODOs resolved or restated, every figure re-measured on this machine.
|
||||
|
||||
Not done, deliberately, and each with the number that would justify it — the
|
||||
list lives in `docs/perf/README.md`'s *What it would take to go faster* so it
|
||||
sits beside the measurements rather than in a feature's checklist.
|
||||
|
||||
## The Phase 2 call sites, one by one
|
||||
|
||||
The predicate each site wants is *not* always "the token containing this
|
||||
offset", so `Document::token_at` is not a drop-in for any of them. Each swap
|
||||
below is argued from the ordering property, and each argument is pinned by a
|
||||
test that compares the new expression against the old one at every byte of
|
||||
`state::mixed_buffer(20)` — a buffer written with `a=b;`-style adjacent
|
||||
punctuation, comments and strings precisely because the bytes that could tell
|
||||
a search from a sweep are the ones two tokens share.
|
||||
|
||||
**Changed and proven.**
|
||||
|
||||
| site | wanted | now | test |
|
||||
|---|---|---|---|
|
||||
| `selection.rs` `enclosing` | the first token with `start <= offset <= end` | `first_token_reaching`, then one `covers` check | `selection::tests::the_innermost_step_is_the_token_the_sweep_returned_at_every_offset` |
|
||||
| `on_type.rs` `statement_edit` | the token with `end == offset` | `first_token_reaching`, then one `==` | `on_type::tests::the_token_ending_at_the_cursor_is_the_one_the_sweep_returned` |
|
||||
| `on_type.rs` `first_on_line` | the first non-`Eof` token with `start >= content` | `first_token_from`, then `find` over the tail | `on_type::tests::the_first_token_on_a_line_is_the_one_the_sweep_returned` |
|
||||
| `completion.rs` `is_procedural` | the *index* of the token with `start == offset` | `first_token_from`, then one `==` | `completion::tests::the_scope_gates_answer_what_their_sweeps_answered` |
|
||||
| `completion.rs` `balanced` | every token whose start is in `[from, at)` | a slice between two `first_token_from`s | the same test |
|
||||
| `inline.rs` `triggered` | the **last** non-`Eof` token with `end <= offset` | `partition_point`, then `rposition` over the prefix | `inline::tests::the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found` |
|
||||
|
||||
Two of these deserve their reasoning spelled out, because they are the two
|
||||
where a careless swap would have changed an answer:
|
||||
|
||||
- **`selection.rs` takes `span.end` inclusively.** At a byte two adjacent
|
||||
tokens share, `find(covers)` returned the *earlier* of the two, while
|
||||
`Document::token_at` — which uses `TextRange::contains`, end exclusive —
|
||||
would return the later one. `first_token_reaching` returns the earlier one,
|
||||
which is why it is the right primitive here and `token_at` is not.
|
||||
- **`completion.rs`'s `balanced` was sweeping the whole buffer.** Its filter
|
||||
had no upper bound to break on, so a cursor anywhere in a 10 000-line file
|
||||
walked all 94 961 tokens to reach a window a few dozen tokens wide. It is
|
||||
the largest of the six by some way: 130 µs → 36 ns.
|
||||
|
||||
**Left alone, with the reason.**
|
||||
|
||||
- **`signature.rs` `enclosing_list` (:138) and `active_entry` (:231).**
|
||||
Inherent. Both maintain a parenthesis-depth stack, and a depth at the
|
||||
cursor is a function of *every* bracket before it — there is no prefix a
|
||||
binary search may skip without recomputing what it skipped. Both already
|
||||
break at the cursor rather than running to the end of the buffer, so
|
||||
neither is a whole-buffer sweep; bounding the loop with a binary search
|
||||
instead of the `break` would save one comparison per token and change
|
||||
nothing else, which is not worth the edit.
|
||||
- **`pairs.rs` `analyze` (:230).** Inherent, and not a position query at
|
||||
all: it matches *every* scope keyword in the stream and returns the whole
|
||||
pair set. There is no offset to search for.
|
||||
- **`completion.rs` `in_comment_or_string` (:553).** Left, and its existing
|
||||
doc comment already says why: comments are lexer trivia hanging off
|
||||
whichever token happens to follow or precede them, so the token whose
|
||||
`leading` holds a comment at a given byte is not the token a search for
|
||||
that byte would find. A correct search would have to reason about
|
||||
attachment; a wrong one would offer a completion list inside a comment.
|
||||
This is the one remaining per-keystroke whole-buffer walk, and it is
|
||||
recorded as such in `docs/perf/README.md` rather than guessed at.
|
||||
- **`completion.rs` `word_tier` (:355), `candidates.rs` (:218),
|
||||
`folding.rs` (:58).** Inherent: each needs every token in the file, not a
|
||||
token at an offset.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev (round 2).**
|
||||
|
||||
*Phase 1, measured first.* Added
|
||||
`perf::breaking_down_one_flushed_keystroke` and
|
||||
`perf::finding_one_token_against_sweeping_the_stream` to the existing
|
||||
`perf.rs` module, and `a_keystroke_round_trip_over_the_wire` to `e2e.rs`.
|
||||
The e2e measurement reuses the `Live` session helper that already existed in
|
||||
that file for the watched-files test rather than adding a second one; the
|
||||
only change to shared code is that `Live::finish` now returns the number of
|
||||
`publishDiagnostics` it saw while shutting down. That count is the point: a
|
||||
buffer left dirty by a burst is flushed before the next *request* is
|
||||
answered, so by the time `shutdown` comes back every publish the burst was
|
||||
going to produce has arrived. A burst of ten keystrokes produces **one**.
|
||||
|
||||
The breakdown decided everything that followed. At 10 000 lines a flush is
|
||||
31 ms, and 24.5 ms of it is `tokenize` plus `parse_tolerant`. `analyze` is
|
||||
11 %, the diagnostics pass another 4 % on top of the flush, and
|
||||
`resolve_external` — which the round's brief named as a possible target — is
|
||||
**49 µs, one part in six hundred**. There is nothing to skip there.
|
||||
|
||||
*Phase 2.* Six sweeps became binary searches, on the strength of the
|
||||
`finding_one_token` measurement: 77 µs → 20 ns for a cursor lookup at 10 000
|
||||
lines, and 130 µs → 36 ns for `balanced`'s window. The two primitives live in
|
||||
`state.rs` beside `Document::token_at`, which is where the one-paragraph
|
||||
monotonicity argument they all rest on is written; `inline.rs`'s third
|
||||
predicate is written at its own call site because it has one user.
|
||||
|
||||
Every swap is pinned by a test that compares it against the code it replaced
|
||||
at every byte of a shared awkward buffer (`state::mixed_buffer`, whose one
|
||||
job is to have plenty of tokens that touch). Two of the six are *not* what
|
||||
`Document::token_at` would have answered, and the table above says which and
|
||||
why; a seventh candidate, `completion.rs`'s comment gate, was left alone
|
||||
because no search of the token stream answers the question it asks.
|
||||
|
||||
*Phase 3 — nothing, on purpose.* The breakdown does not justify a change:
|
||||
|
||||
- Lex and parse are 79 % of a flush. Making them incremental is the only
|
||||
lever left, and it is a large change under `CLAUDE.md`'s hard invariants 1
|
||||
and 2. Written up in `docs/perf/README.md` with the number that would pay
|
||||
for it; not attempted.
|
||||
- `tokens.clone()` is 2.40 ms, 7.7 % of a flush, and is **load-bearing**:
|
||||
`parse_tolerant` takes its token vector by value and steals the comments
|
||||
out of it (`std::mem::take(&mut self.tokens[pos].leading)`,
|
||||
`self.tokens[pos].trailing.take()`), so `Document.tokens` cannot be the
|
||||
same vector — folding, the on-type comment test and completion's comment
|
||||
gate all read that trivia. The clone is also already a win: before the
|
||||
one-lex change it was a second `tokenize`, which this round measures at
|
||||
12.5 ms. Removing it needs a cheaply-clonable `Token`, which is a
|
||||
`vlog_parser` type change reaching the formatter. Written up, not
|
||||
attempted.
|
||||
- The lint pass walks the tree once per rule (`vlog_linter::lint`'s
|
||||
`for rule in enabled`), but it is 1.40 ms against a 32 ms flush. Fusing the
|
||||
walks is a `vlog_linter` refactor for 4 %. Written up, not attempted.
|
||||
- `resolve_external` is 49 µs. Skipping it when the index generation has not
|
||||
moved would save one part in six hundred of a flush and add a cache
|
||||
invalidation rule to a path that currently has none. Not attempted, and
|
||||
the number is the reason.
|
||||
|
||||
*The finding worth acting on is not a code change.* Over the wire, a lone
|
||||
keystroke's round trip is 156 ms at 1 000 lines — of which 150 ms is the
|
||||
change debounce's own quiet period, and 4.8 ms is the work. The same
|
||||
keystroke followed by a request, which is what a real editor sends, is
|
||||
**4.8 ms at 1 000 lines and 37 ms at 10 000**. So for the editors that ask
|
||||
for anything after a change (VS Code asks for semantic tokens, inlay hints
|
||||
and highlights), the debounce timer never runs and the flush is the whole
|
||||
cost; for a client that asks for nothing, the felt latency is the timer.
|
||||
`CHANGE_DEBOUNCE` is a product decision the previous round made deliberately
|
||||
at 150 ms, so it was not touched — but it is now a measured number rather
|
||||
than an assumed one, and `docs/perf/README.md` says so.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** Verdict: **SHIP WITH FIXES noted, none applied** — one
|
||||
methodology finding on the e2e measurement (not shipped code a user can hit),
|
||||
one informational note verified harmless. Everything else attacked and held.
|
||||
|
||||
Gates, verbatim:
|
||||
|
||||
- `cargo fmt --check` — clean, no output.
|
||||
- `cargo clippy --all-targets --workspace -- -D warnings` — clean, no
|
||||
warnings.
|
||||
- `cargo test --workspace` — every crate green: lucisv_server's unit binary
|
||||
1192 passed / 21 ignored, its `e2e` integration binary 55 passed / 1
|
||||
ignored (the perf test, run separately below), every other crate green
|
||||
too. No `FAILED`, no `error[`.
|
||||
- `cargo test -p vlog_formatter` — 31 + 1 + 4 + 6 + 2 + 22 + 114 + 0 passed
|
||||
across its binaries, 0 failed.
|
||||
- `cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1`
|
||||
— 12 passed. Numbers reproduced within the noise the README itself budgets
|
||||
(see below).
|
||||
- `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
|
||||
— 1 passed: `1000 lines: one change alone 161.9ms, a burst of ten 160.4ms
|
||||
for 1 publish(es), one change a request follows 4.7ms` /
|
||||
`10000 lines: one change alone 205.7ms, a burst of ten 199.0ms for 1
|
||||
publish(es), one change a request follows 38.5ms` — matches
|
||||
`docs/perf/README.md`'s 156/205/157/205/1/4.76/37.4 within reason.
|
||||
|
||||
**Attack angle 1 (identity claims).** All six call sites re-derived from the
|
||||
source and checked against their sweep predicates by hand (`selection.rs`
|
||||
`enclosing`, `on_type.rs` `statement_edit` and `first_on_line`,
|
||||
`completion.rs` `is_procedural` and `balanced`, `inline.rs` `triggered`).
|
||||
Every one of the existing per-site tests already walks **every byte** of
|
||||
`mixed_buffer(20)` (not just a handful of offsets), so the exhaustive-diff
|
||||
form the brief asked for is already what shipped, not something to widen.
|
||||
Checked by hand and confirmed safe at the edges the brief named: offset 0,
|
||||
the last byte, the `Eof` sentinel, an empty file, a file that fails to lex
|
||||
(empty `tokens`), and a large-file fast-path document — `on_type.rs`'s own
|
||||
`OnTypeFormatting::METHOD` arm in `server.rs:832` answers the empty edit list
|
||||
before `level_at`/`first_on_line` ever run on a large doc; `completion.rs`'s
|
||||
`completions` guards `doc.tokens.is_empty()` at `completion.rs:154` before
|
||||
`is_procedural`/`balanced` are reachable; `inline.rs`'s `inline_completions`
|
||||
guards the same at `inline.rs:237`; `selection.rs`'s `enclosing` and the two
|
||||
`first_token_*` primitives themselves degrade safely on an empty slice
|
||||
(`partition_point` on `&[]` is `0`, `.get(0)` on an empty `Vec` is `None`).
|
||||
`selection.rs`'s inclusive-`covers`/exclusive-`token_at` distinction is real
|
||||
and correctly *not* used — traced through `first_token_reaching` +
|
||||
`covers` by hand at a shared boundary byte and it does return the earlier of
|
||||
two touching tokens, matching the sweep it replaced.
|
||||
|
||||
**Attack angle 2 (the precondition).** `state::tests::the_token_stream_rises_and_never_overlaps`
|
||||
exercises exactly one hand-written buffer
|
||||
(`mixed_buffer(20)`), which is narrow on its own — no macros, no directives,
|
||||
no unterminated constructs. Delegated to a sub-agent to read
|
||||
`vlog_parser`'s lexer directly rather than trust the docstring's claim.
|
||||
Finding: `vlog_parser`'s own `tests/spans.rs::assert_covers_source` already
|
||||
asserts the same invariant (non-overlap, source order, full byte coverage,
|
||||
comments included) over 40+ deliberately adversarial fixtures — macros,
|
||||
`` `ifdef``/`` `include`` interleaving, attributes, CRLF, BOM, multi-byte
|
||||
UTF-8 in strings and comments — and `tests/error_recovery.rs` fuzzes every
|
||||
byte-prefix and every single-byte deletion of a corpus without panicking.
|
||||
Every lexer error path (`skip_string`, `skip_block_comment`, the attribute
|
||||
scanner) returns `Err` rather than a partial, possibly-violating `Vec<Token>`,
|
||||
and `TextRange::new` clamps `end` to `max(start)` structurally. No plausible
|
||||
gap found: the one narrow test in `state.rs` is sufficient because it rests
|
||||
on an invariant `vlog_parser` proves far more thoroughly one layer down, and
|
||||
the docs correctly point there rather than re-arguing it.
|
||||
|
||||
**Attack angle 3 (the e2e measurement's methodology) — one finding.**
|
||||
|
||||
- **IL-1 (medium) — the burst's "1 publish(es)" figure is not the robust,
|
||||
order-independent count the code and the docs describe.**
|
||||
`crates/lucisv_server/tests/e2e.rs:4696-4727`. `published` is computed as
|
||||
`1 + live.finish()` (line 4727): the `1` is an unstated assumption that the
|
||||
lone `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
|
||||
right after the burst (line 4704) consumed *exactly* the burst's own
|
||||
publish and nothing else, and `live.finish()`'s count only starts
|
||||
accumulating after the "one change a request follows" loop ten lines later
|
||||
(4714-4725) has already run — ten more iterations, each with its own
|
||||
generic `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
|
||||
(line 4722) that accepts *any* publish, not specifically the one its own
|
||||
request just triggered. A stray or duplicate publish arriving from the
|
||||
burst in that window would be silently absorbed by one of those ten waits
|
||||
and never increment `published` or surface anywhere in the printed line.
|
||||
The doc comment above the burst (line 4696-4699: "the count below is that
|
||||
claim measured rather than reasoned about: any publish still to come
|
||||
arrives before `shutdown` does") is true of `live.finish()`'s own drain —
|
||||
nothing gets past *that* point unnoticed — but it is not true of the
|
||||
window between the burst and the drain, which is exactly where a second
|
||||
publish would have to be counted to falsify "exactly one". As written, the
|
||||
test would print "1" whether the burst produced one publish or secretly
|
||||
produced two, which is indistinguishable from the claim it's supposed to
|
||||
be checking. In practice the debounce is understood to always coalesce to
|
||||
one flush, so this is a soundness gap in the *measurement*, not evidence
|
||||
of a real double-publish — but it means the "counted rather than reasoned
|
||||
about" claim is itself partly reasoned about. Not fixed: closing it cleanly
|
||||
means either running the burst as its own `Live` session finished
|
||||
immediately after (so nothing else can absorb a stray), or having
|
||||
`wait_for` tally every `publishDiagnostics` it ever passes over for the
|
||||
life of the session — both are design choices for the dev, not a
|
||||
QA drive-by edit.
|
||||
- Everything else in this angle held. `Live::finish`'s drain (`e2e.rs:2231`)
|
||||
really does read to `shutdown`'s response before returning, so nothing
|
||||
published after the last explicit `wait_for` in a test is lost *at that
|
||||
point* — it is specifically the mid-test absorption above that is the gap.
|
||||
The 150 ms figure in the lone-keystroke row is the timer and not a stall:
|
||||
reproduced at 161.9 ms / 205.7 ms against a documented 150 ms
|
||||
`CHANGE_DEBOUNCE` plus a single flush (2.6 ms / 31.2 ms measured
|
||||
separately), which accounts for the total without residue.
|
||||
|
||||
**Attack angle 4 (duplication) — one informational note, verified harmless.**
|
||||
`perf::generated_module` (`crates/lucisv_server/src/perf.rs:42-57`) and its
|
||||
copy in `crates/lucisv_server/tests/e2e.rs:4634-4649` are not byte-identical:
|
||||
the `e2e.rs` copy appends ` // typing\n` before `endmodule` that the
|
||||
original does not have, so the test has a stable, comment-only line to land
|
||||
keystrokes on. The doc comment on the copy ("The two must stay the same
|
||||
shape, or the two tables ... stop being readable against one another")
|
||||
slightly overstates it — they differ by one line. Verified harmless: a
|
||||
comment is lexer trivia and is never its own token, so `tokens.len()` is
|
||||
identical between the two generators at the same `lines`, and the added ~12
|
||||
bytes is noise against 29 KB / 309 KB files. The two perf tables do stay
|
||||
readable against one another; no fix needed.
|
||||
|
||||
**Attack angle 5 (perf honesty).** Every figure in `docs/perf/README.md`'s
|
||||
round-2 tables reproduced within the noise the document itself budgets for,
|
||||
on a fresh `--release` run (see gates above for the two exact commands and
|
||||
their output). Spot check on "the breakdown sums to `Document::new`'s
|
||||
31.1 ms" — a claim the brief asked about but which, checked directly, is
|
||||
**not actually written anywhere in either README**; nowhere does the text
|
||||
assert the eight-stage breakdown sums to the `Document::new` figure. As a
|
||||
sanity check anyway: summing this run's own breakdown stages inside
|
||||
`Document::new` (tokenize 12.512 + parse_tolerant-with-clone 14.149 +
|
||||
collect_defines 0.115 + analyze 3.174 + resolve_external 0.012 +
|
||||
`LineIndex::new` 0.105 ≈ 30.07 ms) against the dedicated `Document::new`
|
||||
figure from the same run (31.22 ms) leaves about 1.15 ms — 3.7% —
|
||||
unaccounted for, which is consistent with the README's own caveat that the
|
||||
breakdown "runs eight measurements back to back on one heap" and should be
|
||||
read as *shares*, not as a sum that has to close exactly. No finding, since
|
||||
no stronger claim than that is actually made.
|
||||
|
||||
**Attack angle 6 (regression sweep).** `cargo test --workspace` exercises
|
||||
every one of the four handlers' existing suites unchanged and green
|
||||
(selection.rs, on_type.rs, completion.rs, inline.rs — see gates above).
|
||||
Adversarial shapes the brief named are already covered by name in the
|
||||
existing suites and were spot-read to confirm they exercise the *changed*
|
||||
code paths and not just the surrounding handler: `on_type.rs`
|
||||
`a_semicolon_the_lexer_never_saw_ends_no_statement`,
|
||||
`a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`,
|
||||
`a_crlf_line_ending_is_never_touched_by_the_edit`; `completion.rs`
|
||||
`a_buffer_that_does_not_lex_is_declined`; `inline.rs`
|
||||
`a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at`,
|
||||
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost`,
|
||||
`crlf_line_endings_still_trigger`; `selection.rs`
|
||||
`a_file_that_does_not_lex_still_answers_the_file_range`,
|
||||
`an_empty_file_still_answers_one_degenerate_chain`.
|
||||
|
||||
**PDS-1..4 and CD-1, spot-checked in code rather than trusted from the
|
||||
README.** `hover.rs:361` (`only_a_closer_on`) and `:373` (`is_closer_word`)
|
||||
exist and `another_port_on`/`is_port_grammar_word` are gone — PDS-1 real.
|
||||
`hover.rs:292-295` strips a trailing `\r` in the one line reader all three
|
||||
`attached_lines` collections pass through — PDS-4 real. `server.rs:1247-1262`
|
||||
(`notification`): the `dirty.retain` for `DidCloseTextDocument::METHOD` sits
|
||||
*above* the `if method != DidChangeTextDocument::METHOD { self.flush_dirty() }`
|
||||
call, guarded on the method name via a borrowed, cloned `closing_uri`
|
||||
(`server.rs:2214`, reads `params` without consuming the notification) — CD-1
|
||||
genuinely closed, not dead code any more. PDS-2/PDS-3 not independently
|
||||
re-derived (no code-shape claim to check beyond what PDS-1/PDS-4 already
|
||||
verify the same file's discipline on); taken on the strength of the named
|
||||
tests, which are present and green.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted, with one methodology fix applied by me
|
||||
(below). Gates re-run independently: fmt clean, clippy silent, workspace
|
||||
tests green, formatter snapshot + idempotency suite green, the twelve `perf::`
|
||||
measurements and the wire measurement both reproduce.
|
||||
|
||||
This round did the thing that makes a performance round worth anything: it
|
||||
measured first and then declined to optimise three of the four things it had
|
||||
been pointed at, with a number for each refusal. `resolve_external` at 49 µs
|
||||
of a 31 ms flush disproved the brief's own hypothesis, and saying so is a
|
||||
better outcome than a speculative cache on a path that has no invalidation
|
||||
rule today. Lex and parse at 79 % is the real answer, and leaving incremental
|
||||
parsing to a planned round rather than starting it opportunistically is
|
||||
right — that work lands directly on hard invariants 1 and 2 and is not
|
||||
something to attempt as the tail of a perf sweep.
|
||||
|
||||
The Phase 2 swaps are the part I looked at hardest, because six "obviously
|
||||
identical" rewrites is exactly where a silent behaviour change hides. The
|
||||
dev found the one that was *not* identical: `selection.rs`'s `covers` treats
|
||||
`span.end` inclusively, so at a byte two tokens share, the sweep returned the
|
||||
earlier token and `Document::token_at` would have returned the later one.
|
||||
Building `first_token_reaching` instead of reaching for the existing helper
|
||||
is the correct instinct, and differential-testing each new expression against
|
||||
the predicate it replaced at every byte of a purpose-built buffer is the
|
||||
right proof. Three call sites were left alone with reasons — signature help's
|
||||
paren depth is inherently a prefix scan, `pairs.rs` is not a position query,
|
||||
and completion's comment gate cannot be answered by any search of the token
|
||||
stream because comments are trivia. Recording the last of those as the
|
||||
remaining per-keystroke whole-buffer walk is more useful than a forced fix.
|
||||
|
||||
**Fix applied at review.** QA's IL-1 was right and I closed it directly
|
||||
rather than spending another round: the burst-of-ten publish count was
|
||||
`1 + finish()`, but the ten-iteration request loop sat between the burst and
|
||||
the drain, and each of its `wait_for`s accepts *any* publish — so a second
|
||||
publish the burst had produced would have been absorbed there and the figure
|
||||
would still have read "1". The burst now runs last, immediately before the
|
||||
drain, with the keystroke versions renumbered to stay monotonic. Re-measured
|
||||
after the change: still exactly one publish at both sizes, and the row is now
|
||||
counted rather than assumed. IL-2's overstated doc comment is corrected in
|
||||
place — the two `generated_module` copies differ by one trivia line, which is
|
||||
not a token and does not move a number.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,19 +21,19 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` |
|
||||
| `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` |
|
||||
| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didSave` once per notification, and for a `didChange` once per **flush** (a typing burst publishes once, not once per keystroke — `docs/features/change-debounce/README.md`) — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, and the composed text is held **dirty** — one `set_document` + one `publish` per *flush*, which is the next request, the next other notification, or a 150 ms quiet period. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` and `docs/features/change-debounce/README.md` |
|
||||
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
|
||||
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it |
|
||||
| `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/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
|
||||
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
|
||||
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
|
||||
| `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 |
|
||||
@@ -233,21 +233,97 @@ 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 |
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`, and every **flush** of the buffers a `didChange` left dirty — once per flush, however many ranges *and* however many notifications it coalesced (`docs/features/change-debounce/README.md`) | one file, full recompute — 2.6 ms at 1 000 lines, 31 ms at 10 000 (`docs/perf/README.md`) |
|
||||
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) |
|
||||
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
|
||||
| the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) |
|
||||
|
||||
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
|
||||
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
|
||||
deferred there. Incremental *sync* did not change that: the wire now carries
|
||||
ranges, but a `didChange` still throws the whole `Document` away and builds a
|
||||
new one — one reparse per notification, which is also the one generation bump
|
||||
the pull-diagnostics `resultId` depends on.
|
||||
**Per-file recompute** is the strategy TODO.md §6 states ("per-file recompute
|
||||
is fine at Verilog file sizes"); salsa is explicitly deferred there.
|
||||
Incremental *sync* did not change that: the wire carries ranges, but a flush
|
||||
still throws the whole `Document` away and builds a new one. What changed on
|
||||
2026-08-28 is *how often*: a `didChange` no longer triggers that recompute
|
||||
itself, so a typing burst costs one reparse and one generation bump — still
|
||||
exactly one of each per flush, which is what the pull-diagnostics `resultId`
|
||||
depends on (`docs/features/change-debounce/README.md`).
|
||||
|
||||
**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 +333,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 +412,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 +463,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 }`.
|
||||
@@ -500,14 +590,29 @@ overlap trap and the round-trip property:
|
||||
(`docs/features/include-nav/README.md`).
|
||||
2. **A reference** resolved in-file: the symbol's kind, its name, and the
|
||||
source lines its `decl_span` covers.
|
||||
3. **A reference** answered only by the workspace overlay: the kind and name,
|
||||
plus each target's file and line.
|
||||
3. **A reference** answered only by the workspace overlay: the kind, each
|
||||
target's file and line, and — since 2026-08-27 — **that declaration's own
|
||||
source line(s)** beneath each heading.
|
||||
4. **A declaration** the cursor is sitting on: its own kind, name and
|
||||
snippet.
|
||||
|
||||
The snippet is `decl_span` widened to whole lines, so a declaration reads as
|
||||
it was written rather than starting mid-line.
|
||||
|
||||
**The cross-file snippet (case 3).** The index holds no file contents, so the
|
||||
line is fetched per hover: from the **live buffer** when the target file is
|
||||
open — matched to the indexed `Def` logically through
|
||||
`nav::indexed_def_for_symbol`, because an unsaved edit above a declaration has
|
||||
already moved the span the index recorded — and from disk otherwise, where the
|
||||
recorded span is the one the index was built from. Either way the chosen text
|
||||
is sliced at the chosen name span and required to spell the hovered name; on
|
||||
any mismatch, unreadable file or unmatched buffer the snippet is dropped and
|
||||
the card is exactly what it was before this feature. It is capped at 5 lines
|
||||
and 400 characters (a module's `decl_span` is its whole body; a netlist line
|
||||
has no bound), with a footnote naming whichever cap cut it. Rules, the
|
||||
deliberate span asymmetry between the two paths, and the guard's attack tests:
|
||||
`docs/features/hover-declarations/README.md`.
|
||||
|
||||
**A macro card has a second half since M14 (0.5.0).** Under the definition it
|
||||
shows what the hovered *use* expands to in one step — the body with this call's
|
||||
arguments substituted for the parameters — fenced identically, with a footnote
|
||||
@@ -529,8 +634,10 @@ registered for exactly that language id, and that grammar is the *only* thing
|
||||
that colours a hover card: semantic tokens cannot reach markdown, and VS Code
|
||||
resolves a fence's info string against the language registry rather than
|
||||
against the hovered document. Changing the tag, or fencing a new surface with a
|
||||
different one, silently returns every card to flat grey. The three call sites
|
||||
pin the exact fenced string in their own tests; the registration is pinned by
|
||||
different one, silently returns every card to flat grey. Every call site —
|
||||
`define_text`, `expansion_text`, `local_text`, the cross-file `fenced` and the
|
||||
completion templates' documentation panel — pins the exact fenced string in its
|
||||
own tests; the registration is pinned by
|
||||
`crates/lucisv_server/tests/grammar.rs`, which also holds the extension's keyword
|
||||
list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
`docs/features/editor-packaging/README.md`.
|
||||
@@ -589,11 +696,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 +742,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 +777,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
|
||||
|
||||
@@ -30,12 +30,13 @@ same invocation, regardless of thread count.
|
||||
rather than streaming. For the sizes lucisv targets (a large RTL tree is tens
|
||||
of MiB of source) this is acceptable; it is the reason `--stdout` over a
|
||||
huge tree is no longer incremental.
|
||||
- **8 MiB of worker stack is enough.** Taken from
|
||||
`docs/features/recursion-limit/README.md`, which measured the worst-case
|
||||
full-pipeline peak at ~3.9 MiB in a debug build and ~0.5 MiB in release.
|
||||
The pool is built with exactly that number; rayon's own default is 2 MiB,
|
||||
which would silently reintroduce the stack-overflow crash that feature
|
||||
fixed.
|
||||
- **Worker stacks are `vlog_parser::PARSE_STACK_SIZE`, not a number of this
|
||||
feature's own.** Superseded 2026-08-28: this used to assume "8 MiB is
|
||||
enough", from recursion-limit's then-measured ~3.9 MiB debug peak. That
|
||||
peak is now measured at ~5.9 MiB (rustc 1.97, nested `case`), so the size
|
||||
is no longer this feature's to pick — `build_pool` spells the parser's
|
||||
constant, and recursion-limit owns the number. rayon's own default is
|
||||
2 MiB, which would silently reintroduce the stack-overflow crash.
|
||||
- **The `.gitignore` support is a documented subset, not git.** It is the
|
||||
`--exclude` matcher plus anchoring, directory-only and negation. See
|
||||
"gitignore subset" below for exactly what is and is not honoured. It is
|
||||
@@ -98,11 +99,13 @@ A path named directly on the command line is never ignored, exactly as with
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `docs/features/recursion-limit/README.md`'s request:** that
|
||||
README asks whoever lands parallelism to build the rayon pool with
|
||||
`stack_size(8 * 1024 * 1024)` or larger, because a 2 MiB worker cannot
|
||||
reach `MAX_NESTING_DEPTH` in a debug build (~3.9 MiB measured). Done in
|
||||
`main.rs::build_pool`, with a test (`deep_file_formats_under_the_pool`)
|
||||
that fails if the stack size is ever removed.
|
||||
README asks whoever lands parallelism to build the rayon pool with a stack
|
||||
big enough to reach `MAX_NESTING_DEPTH`, because a 2 MiB worker cannot.
|
||||
Done in `main.rs::build_pool`. Since 2026-08-28 the size is the parser's
|
||||
own `vlog_parser::PARSE_STACK_SIZE` rather than a literal here, so a
|
||||
re-measurement of the worst case moves every parse site at once; the pin
|
||||
test (`a_deeply_nested_file_formats_on_a_worker_thread`) still fails if
|
||||
the pool's stack size is dropped.
|
||||
- **Discharges `docs/features/cli-polish/README.md`'s handshake:** that
|
||||
feature's `catch_panic` swapped the process-global panic hook with
|
||||
`take_hook`/`set_hook` around every call, and flagged it as sound only
|
||||
@@ -126,7 +129,9 @@ A path named directly on the command line is never ignored, exactly as with
|
||||
|
||||
- [x] `rayon` as the workspace's first third-party dependency, pinned
|
||||
exactly, justified below.
|
||||
- [x] Global pool built once at startup with an 8 MiB worker stack.
|
||||
- [x] Global pool built once at startup with an 8 MiB worker stack
|
||||
(re-pointed at `vlog_parser::PARSE_STACK_SIZE` on 2026-08-28, when the
|
||||
worst case was re-measured past what 8 MiB comfortably covers).
|
||||
- [x] One panic hook installed at startup; `catch_panic` uses a thread-local
|
||||
flag instead of swapping hooks.
|
||||
- [x] Per-file loop parallelised; outcomes reported in input order.
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
# port-detail-spans
|
||||
|
||||
## Goal
|
||||
|
||||
A non-ANSI port is declared in two places: the header names it (`data_in,`)
|
||||
and a body declaration finishes it (`input signed [31:0] data_in;`). Every
|
||||
fact a reader wants — direction, signedness, width — is in the second place,
|
||||
and until this round hover and go-to-definition both pointed only at the
|
||||
first, so hovering a port of an older-style module showed a bare name and a
|
||||
comma. `vlog_semantic` now records, on the header symbol, the span of the body
|
||||
declaration that completes it (`Symbol::detail_span`); the server shows both
|
||||
in one hover card and offers both as definition locations, detail first. The
|
||||
same field travels through the workspace index and its on-disk facts, so a
|
||||
*cross-file* hover into a closed file gets the same two sections. Attached to
|
||||
that, because a card that shows a declaration should show what the author
|
||||
wrote about it: each section carries the comment that documents it.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **One name, one symbol, per scope.** `bind::declare` already turns a second
|
||||
declaration of a name into a *reference* to the first, which is exactly how
|
||||
a non-ANSI body declaration attaches to its header port. `detail_span` rides
|
||||
on that existing mechanism; nothing new decides what "the same port" means.
|
||||
- **First writer wins.** If a header somehow names a port twice, the first
|
||||
body declaration to arrive records its span and later ones are ignored. The
|
||||
result is deterministic, which is what matters here; a duplicated port is
|
||||
the linter's complaint to make, not hover's.
|
||||
- **`detail_span` is `None` for everything else.** An ANSI port, a wire, a
|
||||
module — anything complete where it is named — has no detail site, and both
|
||||
consumers render exactly the card they always did.
|
||||
- **A real span is never empty**, so `(0, 0)` is free to mean `None` in the
|
||||
facts codec. `bind_port_decl` only ever records a declaration's own span.
|
||||
- **Comment attachment is textual, and errs towards attaching nothing.** The
|
||||
disk path of a cross-file hover has no parse to ask, so the attachment rules
|
||||
work on lines. Only `//` lines and single-line `/* … */` count as
|
||||
comment-only; the interior of a multi-line block comment is
|
||||
indistinguishable from code without lexing, and a hover card that guessed
|
||||
would be the wrong-line lie the snippet guards exist to prevent.
|
||||
- **A comment below a declaration belongs to the *next* declaration unless
|
||||
nothing else could claim it.** `only_a_closer_on` answers that with a
|
||||
whitelist, not a blacklist: the block attaches only when every word on the
|
||||
line after it is a block terminator (`end`, `endmodule`, `endinterface`,
|
||||
`endtask`, `endfunction`) — which includes a line with no words at all
|
||||
(`);`, a blank line, punctuation) — or when there is no line after it at
|
||||
all. Everything else, a bare `input` on the first line of a *wrapped*
|
||||
declaration included, reads as another declaration. The bias is the whole
|
||||
point: a false "another declaration is here" only ever declines to attach a
|
||||
comment, the direction that cannot lie, while a false "nothing here" shows
|
||||
one declaration's comment on another's card. (QA, PDS-1: the previous
|
||||
keyword-blacklist form got that backwards and did lie.)
|
||||
- **The three comment sources are independent**, as the owner's rule states
|
||||
them: a declaration takes the comment on its own line *and* the block above
|
||||
it *and* the block below it, each guarded on its own. Order is source
|
||||
order. (QA, PDS-2: the first implementation ran them as a priority chain
|
||||
and dropped a below-comment nothing else claimed.)
|
||||
- **Comment attachment renders, it never rewrites.** A CRLF file's line ends
|
||||
before its `\n` but after its `\r`, so `attached_lines` strips that `\r` as
|
||||
it composes each line — display text only; no buffer is touched (QA,
|
||||
PDS-4).
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_semantic::Symbol` gains a field** — `detail_span:
|
||||
Option<TextRange>`. Additive, like `refactor-rename`'s `Target::Declaration`
|
||||
before it (§2.6 of `topo.md`): every existing reader of `Symbol` compiles
|
||||
and behaves identically, and the two struct literals that build a `Symbol`
|
||||
(`bind.rs`) set it. `bind_port_decl` is where it is written.
|
||||
- **`vlog_semantic::Def` gains the same field**, carried by the index's
|
||||
internal `Decl`. `Def` is what `lucisv_server` navigates by, so this is the
|
||||
wire that makes a *cross-file* hover show the body declaration. `Def`
|
||||
derives `PartialEq`; two `Def`s that differ only in `detail_span` cannot
|
||||
arise, because both come from the same `Decl`.
|
||||
- **`facts.rs`'s on-disk format changes** — every declaration record now
|
||||
carries two more numbers, written unconditionally (`0 0` for the `None`
|
||||
that every ordinary declaration has) so the stream stays flat and the
|
||||
reader stays a straight sequence of `num()`s. **`FACTS_FORMAT` is bumped
|
||||
(2 → 3)**, so a store written by an earlier build is discarded whole:
|
||||
`index_cache.rs`'s header line carries the number, and a header that is not
|
||||
this build's means the file is not read at all. Without the bump an old
|
||||
record would be *reinterpreted* — every field after a declaration's name
|
||||
span shifted by two — rather than dropped, and only the reader's `done()`
|
||||
check would stand between a shifted parse and a wrong answer. Dropping the
|
||||
store costs one rescan, once, which is what the persistent index is for
|
||||
(`docs/features/index-persistence/README.md`); it is the
|
||||
`vlog_semantic/src/workspace.rs` choke-point rule in `topo.md` §3.3.
|
||||
- **`nav.rs` and `hover.rs` agree, by construction.** Hover shows two
|
||||
sections — header, then detail — and `nav::definition` returns two
|
||||
locations in the same order, detail first, so "jump" lands where the card's
|
||||
second block is and the card's first block is the second location. Both
|
||||
read `symbol.detail_span`; there is no second rule for what a port's
|
||||
declaration is. An empty detail span is filtered out in `nav.rs` rather
|
||||
than trusted.
|
||||
- **Consumes `hover-declarations`' guards unchanged.** `spells_exactly` still
|
||||
gates every snippet read out of a file the index may be stale against;
|
||||
`fenced_sections` is applied *after* that guard on the disk path, and after
|
||||
`live_symbol` on the live path.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `Symbol::detail_span`, written by `bind_port_decl`, first writer wins —
|
||||
for a module's non-ANSI port and for an old-style task/function
|
||||
argument, which merge through the same `bind::declare`.
|
||||
- [x] `Def::detail_span` + the index's `Decl` carrying it.
|
||||
- [x] `facts.rs` codec: unconditional pair, `(0,0)` = `None`, `FACTS_FORMAT`
|
||||
bumped so a stale store is not read as a fresh one.
|
||||
- [x] `hover::fenced_sections` — one section, or header + detail.
|
||||
- [x] `nav::definition` returns the detail location first.
|
||||
- [x] Comment attachment (`attached_lines`): same-line, above and below, each
|
||||
guarded on its own, all three at once where all three are written.
|
||||
- [x] Tests: `vlog_semantic` records the span for a split port and not for an
|
||||
ANSI one; hover shows two sections from either end of the port;
|
||||
comments attach above, below, and are not stolen from the next port;
|
||||
a cross-file split port shows both sections from the index.
|
||||
- [x] **2026-08-28**: the below-comment guard is a closer whitelist, so a
|
||||
*wrapped* next declaration keeps its own leading comment (QA, PDS-1).
|
||||
- [x] **2026-08-28**: above / beside / below are independent (QA, PDS-2).
|
||||
- [x] **2026-08-28**: an old-style task or function argument gets a
|
||||
`detail_span` too (QA, PDS-3).
|
||||
- [x] **2026-08-28**: a CRLF file's snippet carries no `\r` into the fence
|
||||
(QA, PDS-4).
|
||||
- [ ] Not done: `detail_span` for anything other than a port or a
|
||||
task/function argument. An `extern`
|
||||
method prototype and its out-of-body definition are the same
|
||||
two-places-one-symbol shape and would fit the field exactly, but no
|
||||
hover complaint has been filed about them and speculative generality is
|
||||
what `CLAUDE.md` says not to build.
|
||||
- [ ] Not done: a *doc-comment* model. The attachment above is positional and
|
||||
deliberately dumb — no `///` convention, no markdown rendering of the
|
||||
comment body, no stripping of `//`. That is a feature of its own if it
|
||||
is ever wanted.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev.** Implemented as part of the LSP performance round
|
||||
(plan: "Improve LSP performance + hover accuracy", part B), continued by a
|
||||
second dev after the first stopped mid-round; the code below is the first
|
||||
dev's except where noted.
|
||||
|
||||
- `bind_port_decl` looks the declarator's name up in the scope it is binding
|
||||
into *before* `bind_declarators` runs, because `declare` will turn the name
|
||||
into a reference and there would be no symbol id to write on afterwards.
|
||||
The lookup is the scope's own `names` map — the same map `declare` consults
|
||||
— so "the same port" is decided in exactly one place.
|
||||
- The codec writes the pair unconditionally rather than with a presence flag.
|
||||
A flag would have kept old records readable at the cost of a branch in the
|
||||
hot reader and a second thing to get wrong; dropping a stale record costs
|
||||
one reparse of that file, once.
|
||||
- Comment attachment was not in the plan. It is here because the first card
|
||||
the two-section change produced looked wrong without it: a port's comment
|
||||
sits on the line above or beside it, and showing the declaration without it
|
||||
loses the only prose the author wrote. The rules are the narrowest ones
|
||||
that never steal another declaration's comment, and each has a test.
|
||||
- **Second dev, 2026-08-28**: **bumped `FACTS_FORMAT` 2 → 3**, which the
|
||||
first dev's change owed and did not take. Its comment argued that a
|
||||
pre-field record is "one field short, fails `done()`, and is dropped" —
|
||||
true for the last declaration in a record, but a record with a declaration
|
||||
followed by anything else is not short, it is *shifted*, and relying on a
|
||||
trailing-length check to catch a field-order change is exactly what the
|
||||
format number exists to make unnecessary. The workspace `VERSION` is also
|
||||
in the store's header, but it has not moved this round, so without the bump
|
||||
a store written by the released 0.12.1 would have been read by the new
|
||||
codec. Otherwise no behavioral change: this README is the documentation the
|
||||
round owed, and `cargo fmt` was run over `hover.rs`.
|
||||
|
||||
**2026-08-28 — dev (QA fixes, third dev).** Every finding in the QA log below
|
||||
is addressed; each is marked fixed or left, with the reason.
|
||||
|
||||
- **PDS-1 — fixed.** `another_port_on`/`is_port_grammar_word` are gone,
|
||||
replaced by `only_a_closer_on`/`is_closer_word` (`hover.rs`). The old
|
||||
predicate asked "does this line carry an identifier the port grammar cannot
|
||||
account for?", which is a blacklist: a line that is *only* keywords — the
|
||||
first line of a wrapped `input\n [7:0] result;` — answered "no other
|
||||
port here" and handed `result`'s comment to `data_in`. The new one asks the
|
||||
question the other way round: every word on the line must be a block
|
||||
terminator, so a line with any word the whitelist does not name (a bare
|
||||
`input` included) reads as another declaration and the comment stays put.
|
||||
A line with no words at all — `);`, blank, punctuation — passes, which is
|
||||
what a last port's trailing comment is really followed by, and so does the
|
||||
end of the file, where there is no line left to claim anything. The doc
|
||||
comment now states that bias and why only that direction is safe.
|
||||
- `name` fell out of the predicate, and with it out of `attached_lines` and
|
||||
`fenced_sections` — the guard no longer needs to know which port it is
|
||||
guarding, only whether anything follows the comment. Three call sites
|
||||
simplified; no behaviour rides on the removal.
|
||||
- Pinned: `a_wrapped_next_declaration_keeps_its_own_leading_comment` (the
|
||||
QA repro verbatim, plus the assertion that the comment does reach
|
||||
`result`'s own card) and `a_wrapped_declaration_keeps_the_comment_below_it`
|
||||
(the same wrapped shape as the *last* declaration still takes it). The
|
||||
existing `a_comments_below_a_declaration_attach_only_when_no_port_follows_them`
|
||||
— comment block above `endmodule` — still passes unchanged.
|
||||
- **PDS-2 — fixed.** `attached_lines` no longer runs a priority chain: the
|
||||
above walk, the declaration's own lines (which carry the same-line comment
|
||||
inherently) and the below walk are three independent collections joined in
|
||||
source order. `has_comment_after` was the chain's only reader and is
|
||||
deleted. Each guard is exactly as strict as before — the above walk still
|
||||
stops at the first line that is not comment-only, and the below guard got
|
||||
*stricter* with PDS-1 — so nothing new can be stolen; what changes is only
|
||||
that a below-comment nothing else claims is no longer silently dropped
|
||||
because something was also written above.
|
||||
- Pinned: `a_declaration_shows_the_comments_above_beside_and_below_it_at_once`
|
||||
(all three on one body declaration) and
|
||||
`a_header_port_shows_the_comments_above_and_below_it_at_once`, which is
|
||||
QA's repro 1 and repro 2 in one header — with the negative half (the same
|
||||
block *is* left alone when another port follows it) in the same test.
|
||||
- **PDS-3 — fixed, not documented as a gap.** Checked the binder first, as
|
||||
the brief asked: `bind_tf_args` declares `task t(a);`'s `a` as a `TfArg` in
|
||||
the task's own scope, and `input [7:0] a;` at statement position reaches
|
||||
`bind_port_decl` with that same scope, so `declare` turns it into a
|
||||
reference to the header symbol — the identical header→body merge a module
|
||||
port gets, one symbol and not two (verified by probe before changing
|
||||
anything). So the recording is extended rather than parked: the
|
||||
`kind == SymbolKind::Port` gate is gone and the inner test is
|
||||
`symbol.kind == kind`, which is the same condition for a port and now also
|
||||
holds for an argument. Pinned in `vlog_semantic`
|
||||
(`an_old_style_task_argument_records_its_body_declaration_too`, including
|
||||
that an ANSI-style argument still has none) and in hover
|
||||
(`an_old_style_task_argument_hovers_as_two_sections_too`).
|
||||
- **PDS-4 — fixed.** `attached_lines`'s line reader strips a trailing `\r`
|
||||
from every line it composes, so a CRLF file's fenced block is `\n`-joined
|
||||
like any other. It is done there, at the one place all three collections
|
||||
(above, declaration, below) pass through, rather than in `cut_to_size`,
|
||||
which would have had to re-split the joined string. Display text only —
|
||||
nothing writes to the buffer. QA's pinned test
|
||||
`a_crlf_multiline_snippet_keeps_interior_carriage_returns` was the
|
||||
regression test for the old behaviour; it is now
|
||||
`a_crlf_multiline_snippet_carries_no_carriage_returns`, asserting no `\r`
|
||||
survives *and* that the lines read as written. (Editing a QA-authored test
|
||||
rather than deleting it: the finding it pins is the one being closed, and
|
||||
the same file's `local_text` path goes through the same helper, so it
|
||||
covers both branches QA named.)
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** Verified against the owner's own spec ("two sections
|
||||
… same line, or above it (if no other port on the line above), or below it
|
||||
(if no other port on the line below)"), and attacked with the shapes named in
|
||||
the QA brief. Gates green (see change-debounce's QA log for the shared run).
|
||||
All reproductions used temporary `#[test]`s in `hover.rs`, run once, and
|
||||
removed after confirming — none are left in the tree, except the one noted
|
||||
below as a kept, permanent regression test.
|
||||
|
||||
- **Finding PDS-1 (high — a wrong comment shown, the one invariant this
|
||||
feature explicitly promises never to violate).** `another_port_on`
|
||||
(`hover.rs:355`) — the guard that decides whether a below-comment block
|
||||
belongs to *this* declaration or the next one — inspects only the single
|
||||
line immediately following the comment block. When the next port's own
|
||||
declaration **wraps**, with its direction keyword alone on the first line
|
||||
and its name on a later line, every word on that first line is in
|
||||
`is_port_grammar_word`'s list (`hover.rs:368`, which includes bare
|
||||
`input`/`output`/etc.), so `another_port_on` returns `false` — "no other
|
||||
port here" — and the comment attaches to the **wrong** declaration.
|
||||
- Repro:
|
||||
```systemverilog
|
||||
module alu (data_in, result);
|
||||
input [7:0] data_in;
|
||||
// about result
|
||||
input
|
||||
[7:0] result;
|
||||
endmodule
|
||||
```
|
||||
Hovering `data_in` shows a detail section reading
|
||||
`input [7:0] data_in;\n// about result` — `result`'s own leading comment,
|
||||
attached to `data_in`'s card. Confirmed live (temporary test asserting
|
||||
the comment is *not* present failed with exactly this text).
|
||||
- This is precisely the failure mode `docs/features/port-detail-spans/
|
||||
README.md`'s own Assumptions section rules out: "a false 'yes' only ever
|
||||
declines to attach a comment — the direction that cannot lie." Here a
|
||||
false *no* (failing to recognize `result`'s declaration as a port) makes
|
||||
it lie. Left unfixed — not small/unambiguous; the honest fix wants
|
||||
`another_port_on` (or its caller) to look past a line that is *entirely*
|
||||
grammar words with no other identifier, to the line(s) after it, which
|
||||
is a real design change to a predicate three call sites and several
|
||||
tests depend on.
|
||||
|
||||
- **Finding PDS-2 (medium — divergence from the stated spec, not corruption;
|
||||
the one the QA brief asked to check explicitly).** The owner's rule reads
|
||||
as three independently-checked sources (same line, above, below). The
|
||||
implementation instead runs a strict priority chain in `attached_lines`
|
||||
(`hover.rs:297`): below-comment collection is skipped **entirely** whenever
|
||||
there is *any* above-comment, or *any* same-line trailing comment
|
||||
(`hover.rs:313`, `if above.is_empty() && !decl.last()...has_comment_after`)
|
||||
— even when the below comment is otherwise unclaimed by anything else
|
||||
(no other port follows it).
|
||||
- Repro 1 (above blocks below):
|
||||
```systemverilog
|
||||
module alu (
|
||||
// above
|
||||
data_in
|
||||
// below
|
||||
);
|
||||
input [7:0] data_in;
|
||||
endmodule
|
||||
```
|
||||
Header section shows `// above` + `data_in` only; `// below` is silently
|
||||
dropped, though nothing else claims it (the next line is `);`).
|
||||
- Repro 2 (same-line trailing comment blocks below):
|
||||
```systemverilog
|
||||
module alu (
|
||||
data_in // right here
|
||||
// below
|
||||
);
|
||||
input [7:0] data_in;
|
||||
endmodule
|
||||
```
|
||||
Header section shows `data_in // right here` only; `// below` dropped.
|
||||
- Not unsafe (never shows the wrong comment — just fewer than the literal
|
||||
spec asks for), so lower severity than PDS-1, but a real, reproducible
|
||||
divergence. Left unfixed — a design call (should a declaration ever show
|
||||
*two* attached comments at once?) belongs to the dev/lead, not QA.
|
||||
|
||||
- **Finding PDS-3 (low — silent feature-completeness gap, not a bug).**
|
||||
`bind_port_decl`'s `detail_span`-recording branch is gated on `kind ==
|
||||
SymbolKind::Port` (`bind.rs:512`), which excludes `SymbolKind::TfArg` —
|
||||
**old-style (non-ANSI) task/function port declarations**
|
||||
(`task t(a);\n input a;\n ...\nendtask`) never get a `detail_span`, even
|
||||
though they are exactly the same two-places-one-symbol shape a module's
|
||||
non-ANSI port is, and `bind_port_decl` is already reached at statement
|
||||
position for them (`bind.rs:1030`, `StmtKind::PortDecl`). The feature's own
|
||||
"Not done" list names only extern method prototypes as the deliberately
|
||||
parked case; task/function old-style ports are a second, unmentioned one.
|
||||
Falls back to the single-section card exactly as before this round — no
|
||||
regression, just an undocumented gap, worth a line in Status/TODO if the
|
||||
dev wants it.
|
||||
|
||||
- **Finding PDS-4 (low/cosmetic — pre-existing, amplified by this round, not
|
||||
introduced by it).** On a CRLF file, a multi-line fenced snippet embeds a
|
||||
raw `\r` byte in the *middle* of the code fence for every joined line
|
||||
except the last (whose trailing `\r` happens to be stripped because
|
||||
`cut_to_size`'s `trim_end()` only trims the very end of the whole joined
|
||||
string, not each line). This is pre-existing behavior of
|
||||
`Positions::whole_lines` / `cut_to_size` — `local_text` already had the
|
||||
same characteristic for any multi-line `decl_span` before this round — but
|
||||
comment attachment now makes multi-line snippets routine (any port with a
|
||||
nearby comment, not just a rare multi-line declaration), so the gap is hit
|
||||
far more often in practice. Repro: a CRLF split-port module with an
|
||||
above-comment; the header section's rendered text contains a literal `\r`
|
||||
between the comment line and the declaration line. Cosmetic only (a stray
|
||||
control character, not wrong text); not fixed, flagged for whoever touches
|
||||
`cut_to_size` next.
|
||||
|
||||
- **Attack angles checked and clean (no finding):**
|
||||
- *A port declared twice* — first-writer-wins confirmed: the second body
|
||||
declaration's comment (`// second (duplicate...)`) never appears; only
|
||||
the first's (`// first`) does, matching `bind_port_decl`'s documented
|
||||
policy.
|
||||
- *ANSI mixed with non-ANSI in one header* — a full ANSI port (`input wire
|
||||
clk,`) and a split non-ANSI port (`data_in`) in the same header list:
|
||||
`clk` renders exactly one fenced section, `data_in` exactly two, no
|
||||
cross-contamination.
|
||||
- *A comment containing `//` inside a string on the declaration line* —
|
||||
the whole line is shown verbatim regardless (the attachment logic never
|
||||
parses the line's meaning, only whether `has_comment_after` sees `//`/
|
||||
`/*` after the name), so there is no wrong-line risk, only the expected
|
||||
line reproduced as written.
|
||||
- *`` `ifdef``/`` `endif`` between the header and the body declaration* —
|
||||
correctly ignored as neither comment-only nor a stolen declaration; the
|
||||
detail section is exactly the body decl's own line(s). (Note: a
|
||||
`` `endif``/`` `ifdef``/`` `define`` line sitting where "no other port"
|
||||
is required is itself treated as "another port" by `another_port_on`'s
|
||||
conservative word-matching — a false positive that only *declines* to
|
||||
attach, so it is safe, just another instance of the documented
|
||||
conservative-below-the-fold behavior, not a new bug.)
|
||||
- *An attribute (`(* foo *)`) prefixing the next port's declaration* —
|
||||
correctly detected as "another port" (the attribute's own words split
|
||||
out as ordinary non-grammar identifiers), so the comment is not stolen.
|
||||
- *A block comment `/* … */` spanning multiple lines* — the interior lines
|
||||
are (by design, and correctly) not recognized as comment-only, so the
|
||||
walk stops there and nothing is attached from inside the block — safe
|
||||
(declines rather than guesses), matching the documented limitation.
|
||||
|
||||
- **Facts-format bump (2 → 3): verified the drop, not a shifted read.**
|
||||
Wrote and kept a permanent regression test,
|
||||
`a_store_from_the_previous_facts_format_is_dropped_not_misread`
|
||||
(`crates/lucisv_server/src/index_cache.rs`, next to the existing
|
||||
`a_store_from_another_version_is_dropped_whole_and_replaced` and
|
||||
`a_store_from_the_previous_store_format_is_dropped_whole_and_replaced`,
|
||||
which cover a `VERSION` mismatch and a `CACHE_FORMAT` mismatch but, before
|
||||
this, never a `FACTS_FORMAT`-only mismatch). It writes a store whose header
|
||||
says `FACTS_FORMAT` `2` with today's `CACHE_FORMAT` and `VERSION`
|
||||
otherwise unchanged, opens it, and asserts `facts_for` returns `None` (the
|
||||
whole store is unread, not field-shifted) and that the first write since
|
||||
replaces it under today's header, readable afterward. Passes. This closes
|
||||
a real test gap the round left — the design (the format number lives in
|
||||
the header line `IndexCache::open` compares byte-for-byte,
|
||||
`index_cache.rs:103`) was sound but untested for this exact axis.
|
||||
|
||||
- **A3 tie-break: confirmed correct**, both via the shipped
|
||||
`looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
|
||||
(passes) and by re-deriving it: `by_name` is built with a **stable** sort
|
||||
(`Vec::sort_by`, `lib.rs`), so symbols sharing a name keep declaration
|
||||
order, and `symbols_named`'s two `partition_point` binary searches over
|
||||
that name-sorted table can only reorder within a name if the sort were
|
||||
unstable — it is not.
|
||||
|
||||
- **`nav::definition` / hover agreement:** confirmed the detail location is
|
||||
filtered by `!span.is_empty()` (`nav.rs`) exactly as documented, and that a
|
||||
detail-less symbol (ANSI port, ordinary declaration) still returns exactly
|
||||
one location, unchanged from before this round.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted after one fix round. Gates re-run
|
||||
independently: fmt clean, clippy silent, `cargo test --workspace` green
|
||||
(2 396 passing at the time of review), `cargo test -p vlog_formatter` green.
|
||||
|
||||
`detail_span` is the right adaptation of the "detail range" idea to this
|
||||
model: the non-ANSI merge already produced one symbol, so the only thing
|
||||
missing was *where the declaration is completed*, and recording that as an
|
||||
optional second span leaves every complete-where-named declaration
|
||||
untouched. Hover and go-to-definition read the same field, which keeps
|
||||
`topo.md`'s one-matcher rule intact.
|
||||
|
||||
Two things in this feature deserved the scrutiny they got.
|
||||
|
||||
**The facts-format bump.** The first implementation added two numbers per
|
||||
declaration record without moving `FACTS_FORMAT`, on the argument that a
|
||||
short record fails `done()` and is dropped. That argument only holds for the
|
||||
*last* declaration in a record; every earlier one would have been read
|
||||
field-shifted by two, which is a persisted cache handing back wrong spans —
|
||||
the exact shape invariant 4 exists to catch, in the same family as the
|
||||
macro-items corruption. Bumping 2→3 is correct and QA's added regression test
|
||||
(`index_cache.rs`, a store from the previous format is dropped, not misread)
|
||||
closes a gap no existing test covered, since nothing varied `FACTS_FORMAT`
|
||||
alone.
|
||||
|
||||
**The comment attachment.** This began as scope creep — round 1's plan
|
||||
explicitly deferred doc comments on hover — and then turned out to be
|
||||
precisely what the user asked for, so it stays. But it is a *textual*
|
||||
heuristic running over disk text on the cross-file path, and QA's PDS-1 found
|
||||
it lying: `another_port_on` was a keyword blacklist, so a wrapped declaration
|
||||
whose first line is bare `input` looked like an empty line and the next
|
||||
port's comment attached to the previous port's card. Replacing the blacklist
|
||||
with a closer whitelist (`only_a_closer_on`) inverts the bias in the one
|
||||
direction that is safe — an unrecognised line now declines to attach rather
|
||||
than mis-attaching — and the doc comment states that bias as the contract.
|
||||
That is the correct resolution; a predicate over source text that guesses
|
||||
must fail closed.
|
||||
|
||||
PDS-2 was a genuine divergence from the user's stated rule and is fixed by
|
||||
making the three comment sources independent rather than a priority chain.
|
||||
PDS-3 was worth chasing rather than parking: the binder does perform the same
|
||||
header/body merge for `TfArg`, so old-style task and function arguments now
|
||||
get detail spans too, and the gap is closed rather than documented. PDS-4's
|
||||
CRLF strip is display-only and does not touch the buffer.
|
||||
|
||||
The dev renamed and inverted a QA-authored test, and flagged it. Correct call
|
||||
and correctly surfaced: the behaviour that test pinned *was* the finding.
|
||||
|
||||
@@ -50,16 +50,28 @@ not by 64 × 256.
|
||||
`parse_unary`), one nested generate `if` costs 2 (`parse_item` +
|
||||
`parse_gen_if`), one `.b` or one `+` costs 1 link. The limits are a
|
||||
stack-safety budget, not a style rule.
|
||||
- **8 MiB of stack is available.** That is the default main-thread stack on
|
||||
macOS and Linux, and `lucisv` parses on the main thread. Anything that parses
|
||||
on a *spawned* thread must give it a comparable stack — the default 2 MiB
|
||||
is not enough to reach the limit in an unoptimized build (see Handshakes;
|
||||
the tests here spawn 16 MiB threads for exactly this reason).
|
||||
- ~~**8 MiB of stack is available.**~~ **Retired 2026-08-28 — it is now
|
||||
enforced, not assumed.** This used to say "8 MiB is the default main-thread
|
||||
stack on macOS and Linux, and `lucisv` parses on the main thread". Both
|
||||
halves were hazards: the default is not 8 MiB everywhere (`ulimit -s` in a
|
||||
container, 1 MiB on Windows), and "parses on the main thread" stopped being
|
||||
true the moment anything spawned. `MAX_NESTING_DEPTH` bounds how *many*
|
||||
levels run, not what one costs, so the guard only converts an overflow into
|
||||
an error on a stack big enough to reach level 64. That size is now a
|
||||
constant — `vlog_parser::PARSE_STACK_SIZE` — and every thread that can
|
||||
reach a parse is spawned with it, including the two `main`s. See "The stack
|
||||
the limit needs" and the parse-site table in Handshakes.
|
||||
- **Unoptimized builds are the worst case.** Debug stack frames in this
|
||||
parser are large (`parse_keyword_stmt` alone is a ~50 KiB frame at
|
||||
`opt-level=0`, because rustc gives every match arm's temporaries their own
|
||||
slot and does not merge them). The limit is picked for debug builds, so
|
||||
release builds have an order of magnitude more headroom.
|
||||
- **Frame sizes drift upward, so the stack constant carries margin, not a
|
||||
fit.** The same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB on
|
||||
2026-08-28 (rustc 1.97.1) without a line of the parser changing. Nothing in
|
||||
the build pins a compiler version, and the failure mode is an abort rather
|
||||
than a diagnostic, so `PARSE_STACK_SIZE` is set at ~2.7× the measured worst
|
||||
case instead of just above it.
|
||||
- **Rejecting an over-deep file is acceptable behavior.** The file is left
|
||||
untouched with a diagnostic and exit 2, exactly like any other parse error.
|
||||
No real RTL is expected anywhere near the limit; machine-generated
|
||||
@@ -75,9 +87,16 @@ not by 64 × 256.
|
||||
```
|
||||
MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs)
|
||||
MAX_CHAIN_LENGTH = 256
|
||||
PARSE_STACK_SIZE = 16 MiB
|
||||
```
|
||||
|
||||
Going one past either produces an ordinary parse error:
|
||||
The first two bound the input. The third bounds nothing — it is what the
|
||||
first two *cost*, and it is the size every thread that can reach a parse is
|
||||
spawned with. The three only work together: a depth limit on a stack too
|
||||
small to reach it converts nothing, because the overflow (an abort, with no
|
||||
`Result` to return) happens first.
|
||||
|
||||
Going one past either limit produces an ordinary parse error:
|
||||
|
||||
```
|
||||
error: rtl/deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk")
|
||||
@@ -117,9 +136,12 @@ trips the limit (bisected the same way, minimum surviving thread stack):
|
||||
| nested `{...}` / `(...)` | 983–1047 KiB | 103 KiB |
|
||||
| `? :` chains, stacked `~` | 135–423 KiB | — |
|
||||
|
||||
So the worst case is **~3.9 MiB in a debug build, ~0.5 MiB in release**,
|
||||
against an 8 MiB main-thread stack: 2× headroom in the profile with the fat
|
||||
frames, 16× in the profile users actually run.
|
||||
So the worst case *as measured in 2026-08* is **~3.9 MiB in a debug build,
|
||||
~0.5 MiB in release**. Both the number and the stack it was compared against
|
||||
have since been superseded — see "The stack the limit needs" below, which
|
||||
re-measures it at ~5.9 MiB over a wider family sweep and replaces "the 8 MiB
|
||||
main-thread stack" with a stated constant. The table is kept because it is
|
||||
what 64 was chosen from; the choice still holds under the new numbers.
|
||||
|
||||
Why not larger: 128 would need ~7.9 MiB in a debug build — i.e. the CLI
|
||||
integration tests, which run the *debug* binary, would still overflow before
|
||||
@@ -168,6 +190,62 @@ fits). Charging chain links against `MAX_NESTING_DEPTH` instead would have
|
||||
capped those at ~60 terms and rejected real code; that is why chains get
|
||||
their own, larger budget rather than sharing the nesting one.
|
||||
|
||||
### The stack the limit needs — re-measured 2026-08-28
|
||||
|
||||
Same method as above (subprocess per trial, bisect the smallest thread stack
|
||||
that survives), but over the *whole* consumer pipeline this time —
|
||||
`tokenize` → `parse_tolerant` → `analyze` → `FileFacts`, i.e. what the
|
||||
language server runs, alongside `format_source`. Two things changed since the
|
||||
2026-08 numbers: the sweep now covers block families the first round did not
|
||||
(`case`, `fork`, `foreach`, `while`, `for`, nested modules), and the compiler
|
||||
moved (rustc 1.97.1).
|
||||
|
||||
Peak stack on input sized to *trip* the limit — the global worst case, since
|
||||
tripping it walks one level further than any legal input can:
|
||||
|
||||
| family | debug | release |
|
||||
|---|---|---|
|
||||
| nested `case` (any flavour: `casez`, `unique`, `inside`) | **6023 KiB** | **823 KiB** |
|
||||
| nested `case` + `begin` per level | 5847 KiB | 775 KiB |
|
||||
| `else if` chains | 5751 KiB | 807 KiB |
|
||||
| nested `if … begin` | 5735 KiB | 775 KiB |
|
||||
| nested `begin`, `fork`/`join`, labelled `begin : b` | 5591 KiB | 711 KiB |
|
||||
| `foreach` / `do … while` | 5447 KiB | 679 KiB |
|
||||
| `while` / `repeat` / `wait` / `assert … else` | 5367 KiB | 663 KiB |
|
||||
| generate `for` | 3879 KiB | 583 KiB |
|
||||
| generate `if` | 1895 KiB | 343 KiB |
|
||||
| nested `(...)` | 1623 KiB | 183 KiB |
|
||||
| `@(posedge clk)` chains | 1255 KiB | — |
|
||||
| nested `module` … `endmodule` | 103 KiB | 23 KiB |
|
||||
|
||||
So **~5.9 MiB debug, ~0.8 MiB release**, and ~94 KiB per gated level in a
|
||||
debug build rather than the ~62 KiB measured in 2026-08. Nested `module` is
|
||||
cheap because item frames are small; `case` is the ceiling because
|
||||
`parse_keyword_stmt` carries the fattest frame in the grammar and a `case`
|
||||
spends two of them per source level (the `case` itself, then the arm's
|
||||
statement).
|
||||
|
||||
Three things the same sweep settles:
|
||||
|
||||
- **The peak is entirely in the parser.** `analyze` and `FileFacts` measured
|
||||
byte-identical to `parse_tolerant` alone in every family, and `analyze` run
|
||||
*by itself* on a max-legal tree (parsed and dropped on a separate large
|
||||
thread) needs **71 KiB** — ~1.2 KiB per level. It does not need a bound of
|
||||
its own; it is two orders of magnitude under the walk that produced the
|
||||
tree. Same for the tolerant recovery: strict and tolerant parses of the
|
||||
same limit-tripping input bisect to the same byte.
|
||||
- **Chains still do not move the worst case.** A 256-link chain alone peaks
|
||||
at 2487 KiB debug (~9 KiB per link); the same chain inside 58 nested `case`
|
||||
measures 5895 KiB — identical to that nesting without any chain, because
|
||||
the two peak in different phases. The additive-composition argument above
|
||||
is unchanged.
|
||||
- **16 MiB is the constant, and it is margin rather than a fit.** 8 MiB —
|
||||
what the CLI's pool used and what a stock main thread happens to have —
|
||||
is 1.33× the debug worst case, and the last two years of this number moving
|
||||
(3.9 → 5.9 MiB, no parser change) say that is not enough room. 16 MiB is
|
||||
2.7×, costs address space rather than memory (thread stacks are committed a
|
||||
page at a time), and is the size the feature's tests already spawned.
|
||||
|
||||
## Where the counters sit
|
||||
|
||||
`Parser::enter()` / `Parser::leave()` bracket each gated function; `enter`
|
||||
@@ -286,17 +364,41 @@ not inflate depth — the output of a max-depth file re-parses inside
|
||||
expression it has already built — the `Box::new(previous)` shape — must
|
||||
charge `link()`, or it reopens exactly the hole QA found. Loops that push
|
||||
into a `Vec` widen the tree instead and need nothing.
|
||||
- **Request to TODO.md §3's parallel-file-processing item (rayon):** rayon
|
||||
worker threads default to 2 MiB of stack, which is *not* enough to reach
|
||||
the depth limit in a debug build (~3.9 MiB needed). Whoever lands
|
||||
parallelism must set `ThreadPoolBuilder::stack_size(8 * 1024 * 1024)` or
|
||||
larger, otherwise this feature's guarantee silently regresses to a crash.
|
||||
Same applies to any future LSP server thread that parses.
|
||||
- **Promised to every consumer: `vlog_parser::PARSE_STACK_SIZE`.** The depth
|
||||
limit converts an overflow into a diagnostic *only* on a stack of at least
|
||||
this size. It is a `pub const` next to the two limits, so no consumer picks
|
||||
a number of its own and none can drift from the measurement. The rule is
|
||||
one line: **any thread that can reach `tokenize`/`parse`/`analyze` is
|
||||
spawned with `stack_size(PARSE_STACK_SIZE)`** — including the thread a
|
||||
`main` hands its work to, because a process's main stack is set by the OS
|
||||
and `ulimit`, not by us.
|
||||
- **Request to TODO.md §6's error-tolerant parsing mode:** recovery must not
|
||||
reset `depth` while unwinding — it is decremented by `leave()` on the way
|
||||
out of every gated frame, including error paths, and a sync-and-continue
|
||||
recovery has to resume from the frame it recovered in.
|
||||
|
||||
### Every parse site and the stack it runs on
|
||||
|
||||
Audited 2026-08-28 by reading every `thread::spawn` / `thread::Builder` /
|
||||
`ThreadPoolBuilder` / `par_iter` in `crates/` outside `#[cfg(test)]`. This
|
||||
table is the enforcement: a new row without a stated stack is the bug.
|
||||
|
||||
| site | thread | stack |
|
||||
|---|---|---|
|
||||
| `lucisv/src/main.rs` — the whole run (`run_stdin`, `run_files`, `run_check`) | spawned `"lucisv"` | `PARSE_STACK_SIZE` |
|
||||
| `lucisv/src/main.rs::build_pool` — rayon global pool, used by `run_files`' and `lint.rs`' `par_iter` | rayon workers | `PARSE_STACK_SIZE` |
|
||||
| `lucisv_server/src/main.rs` — the LSP message loop, which analyses every buffer | spawned `"lucisv-main"` | `PARSE_STACK_SIZE` |
|
||||
| `lucisv_server/src/server.rs::queue` — forwards `Message`s off the rendezvous channel | spawned `"lucisv-queue"` | default; **never parses** (moves messages, touches no server state) |
|
||||
| `lsp-server`'s `Connection::stdio()` reader/writer | inside the dependency | default; **never parses** (JSON framing only) |
|
||||
| both `main` threads | OS-given | irrelevant by construction — they only parse arguments and the LSP handshake, then hand off |
|
||||
|
||||
Two sites were the actual hole this round closed. The rayon pool was already
|
||||
sized (`8 * 1024 * 1024`, from the older ~3.9 MiB measurement, now 1.33× a
|
||||
re-measured worst case and re-pointed at the constant); the two `main`
|
||||
threads were not sized at all, which is what "8 MiB of stack is available"
|
||||
assumed away. `lucisv -` and `lucisv check -` format on the calling thread
|
||||
and never reach the pool at all, so the CLI's spawn is not redundant with it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Depth counter (`Parser::depth`) + `enter`/`leave` guard pair.
|
||||
@@ -334,6 +436,34 @@ From QA round 1 (2026-08-19):
|
||||
one).
|
||||
- [x] TODO.md §1 recursion-depth item re-checked after the fix.
|
||||
|
||||
Round 3 — the stack the limit needs (2026-08-28, from a QA finding on
|
||||
`vlog_semantic::FileFacts::of`):
|
||||
|
||||
- [x] Diagnosis verified by measurement, not by reading: the overflow is in
|
||||
the parser's own descent, at level ~30 of an in-budget 64, on a 2 MiB
|
||||
thread. `analyze`, `FileFacts` and the tolerant recovery add nothing to
|
||||
the peak.
|
||||
- [x] Worst case re-measured over every nesting family, debug and release,
|
||||
through both the LSP pipeline and `format_source`: ~5.9 MiB / ~0.8 MiB,
|
||||
~94 KiB per gated level in debug. New table above.
|
||||
- [x] `analyze`'s own walk measured on a max-legal tree (71 KiB, ~1.2 KiB per
|
||||
level) — no second bound needed, and no second limit constant added.
|
||||
- [x] `PARSE_STACK_SIZE` (16 MiB) added next to the two limits, `pub`, with
|
||||
the measured rationale and the margin argument.
|
||||
- [x] Every production parse site audited and given that stack: the CLI's run
|
||||
thread, the rayon pool, the language server's message loop. Table in
|
||||
Handshakes; the two threads that do not parse are named there too.
|
||||
- [x] `MAX_NESTING_DEPTH` left at 64 — the stack fits the limit, not the
|
||||
other way round.
|
||||
- [x] Regression tests on controlled stacks: the reported repro through
|
||||
`FileFacts::of`, a 14-shape block sweep, at-limit parses for the two
|
||||
fattest families, and the stdin path through the real binary.
|
||||
- [x] Existing 16 MiB test threads re-pointed at the constant (`parse_deep`,
|
||||
`format_deep`), so a shrunk guarantee fails the suite.
|
||||
- [x] Batch/`catch_unwind` behaviour re-checked end-to-end after the change.
|
||||
- [x] `cargo test --workspace` (2425), `cargo clippy --all-targets`,
|
||||
`cargo fmt --check` all clean.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
@@ -468,6 +598,104 @@ Files touched: `crates/vlog_parser/src/parser.rs`,
|
||||
grew a second pathological file). `cargo clippy --all-targets` silent.
|
||||
`cargo fmt --check` clean. Same files touched as the first round.
|
||||
|
||||
### 2026-08-28 — dev agent, the stack the limit needs
|
||||
|
||||
- **Reproduced first, diagnosed second.** Built a scratchpad probe crate
|
||||
(path-dependencies on the real crates, never inside the repo) that runs one
|
||||
shape, one depth, one phase on a thread of a chosen size, as a
|
||||
*subprocess*, so a stack overflow — which aborts and cannot be caught — is
|
||||
just a non-zero exit to bisect on. The reported input (500 nested `begin`
|
||||
through `FileFacts::of`) dies on a 2 MiB thread exactly as reported.
|
||||
- **The lead's reading is confirmed, and sharper than "64 levels is too
|
||||
much".** Splitting the pipeline into phases, the minimum surviving stack is
|
||||
*byte-identical* for `parse_tolerant` alone, `parse_tolerant` + `analyze`,
|
||||
and the full `FileFacts::of`, in all 25 shapes measured — so the peak is
|
||||
the parser's own descent, and neither `analyze` nor the record-building
|
||||
adds a frame above it. Strict and tolerant parses of the same input also
|
||||
bisect to the same byte, so recovery adds nothing either. At ~94 KiB per
|
||||
gated level the overflow lands around level 30 of an in-budget 64: the
|
||||
limiter never gets to fire. Nothing was missing a counter.
|
||||
- **`analyze` measured on its own** (parse and drop the tree on a separate
|
||||
256 MiB thread, analyse on the thread being bisected) to make sure the
|
||||
identical numbers were not masking: **71 KiB** on a max-legal tree, ~1.2 KiB
|
||||
per level. Two orders of magnitude under the parse. So no second bound and,
|
||||
per the brief, no second limit constant.
|
||||
- **Swept 25 shapes rather than the reported one**, because the reported one
|
||||
is not the worst: nested `case` (6023 KiB debug) beats nested `begin`
|
||||
(5591 KiB), and neither was in the 2026-08 table. Also measured
|
||||
`casez`/`unique`/`inside` flavours, `case`+`begin` per level, `fork`/`join`,
|
||||
labelled blocks, `foreach`, `while`, `for`, `repeat`, `wait`, `do … while`,
|
||||
`assert … else`, `@(posedge)` chains, generate `if`/`for`, nested modules
|
||||
and nested tasks. Full table above. The old ~3.9 MiB figure is now ~5.9 MiB
|
||||
on rustc 1.97.1 without a parser change, which is the argument for margin
|
||||
rather than a fit.
|
||||
- **`PARSE_STACK_SIZE = 16 MiB`, and one constant for everything.** 8 MiB —
|
||||
what the rayon pool already used, and what a stock main thread happens to
|
||||
have — is 1.33× the debug worst case; 16 MiB is 2.7×, costs address space
|
||||
rather than resident memory, and is the number the feature's own tests were
|
||||
already spawning. Putting it in `vlog_parser` beside `MAX_NESTING_DEPTH` is
|
||||
what stops it drifting: the tests now spell the constant instead of
|
||||
`16 * 1024 * 1024`, so cutting the guarantee below what the limit needs
|
||||
fails the suite rather than the user.
|
||||
- **Audited every parse site** (`thread::spawn`, `thread::Builder`,
|
||||
`ThreadPoolBuilder`, `par_iter` across `crates/`, excluding
|
||||
`#[cfg(test)]`); table in Handshakes. The rayon pool was the only one that
|
||||
had a stated stack. The two `main` threads had none — that is what "8 MiB
|
||||
of stack is available" was assuming, and it is not true on Windows, under a
|
||||
tuned `ulimit -s`, or for anyone who later moves work onto a thread. Both
|
||||
`main`s now hand their work to a thread sized by the constant.
|
||||
- **The CLI's spawn is not redundant with the pool.** `docs/features/
|
||||
parallel-files` established (with a probe, and re-verified by QA) that
|
||||
rayon's `par_iter` called from outside the pool *blocks* the caller instead
|
||||
of running jobs on it. But `lucisv -` and `lucisv check -` never build a
|
||||
pool at all: they format the buffer on the calling thread. That path had no
|
||||
stated stack until this change, and it is the one the new CLI test covers.
|
||||
- **Deliberately not done: lowering `MAX_NESTING_DEPTH`.** Per the brief, and
|
||||
because it would change which real files parse. The stack fits the limit.
|
||||
- **Deliberately not done: shrinking the parser's frames.** The 2026-08 round
|
||||
measured that experiment (extracting one `match` arm moved
|
||||
`parse_keyword_stmt` 50,528 → 47,872 B) and rejected it; nothing has
|
||||
changed that calculus, and this round's fix does not need it.
|
||||
- **Tests, all on controlled stacks so they cannot be flaky across
|
||||
environments** — `vlog_semantic/tests/deep_nesting.rs` is new
|
||||
(`five_hundred_nested_blocks_are_indexed_not_aborted` — the reported repro,
|
||||
which now indexes module `m` with the unparsable body recovered;
|
||||
`no_block_shape_can_abort_the_parse_stack` — 14 shapes at 400 levels
|
||||
including nested modules, tasks, functions, fork/join, generate blocks and
|
||||
else-if chains; `nesting_just_under_the_limit_still_yields_its_facts`).
|
||||
`vlog_parser` gained `deep_nesting_errors_for_every_block_form` and
|
||||
`the_fattest_block_forms_still_parse_at_the_limit`; `lucisv` gained
|
||||
`a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash`.
|
||||
- **Sabotage-verified the new tests the way QA does**: set
|
||||
`PARSE_STACK_SIZE` to 2 MiB, rebuilt, and `cargo test -p vlog_semantic
|
||||
--test deep_nesting` died with `SIGABRT` / "fatal runtime error: stack
|
||||
overflow" instead of failing an assertion — i.e. the tests are pinned to
|
||||
the constant, not merely passing beside it. Restored and re-ran green.
|
||||
- **Re-checked the batch/`catch_unwind` claims** end-to-end with the real
|
||||
debug binary on a 4-file directory (`good`, 500 nested `begin`, 400 nested
|
||||
`case`, `good`): `2 files reformatted, 2 files failed to format`, exit 2,
|
||||
both deep files left untouched, no abort. Also drove the real
|
||||
`lucisv-server` over stdio with the 500-level buffer: `initialize`,
|
||||
`didOpen`, `publishDiagnostics`, a `documentSymbol` answer naming module
|
||||
`m`, clean `shutdown`/`exit` 0.
|
||||
- **Touched two files outside this feature, both because they now contradict
|
||||
the code:** `docs/features/parallel-files/README.md`'s "8 MiB of worker
|
||||
stack is enough" assumption and its recursion-limit handshake bullet, and
|
||||
the same number in TODO.md §3's parallel-file item. Only the living
|
||||
contract sentences — that feature's work log and QA log are history and
|
||||
were left alone.
|
||||
|
||||
**Results:** `cargo test --workspace` **2425 passed, 0 failed** (up 8: +2
|
||||
`vlog_parser` unit, +3 `vlog_semantic` `deep_nesting`, +1 `lucisv` CLI, and
|
||||
two pre-existing helpers re-pointed at the constant). `cargo clippy
|
||||
--all-targets` silent. `cargo fmt --check` clean. Files touched:
|
||||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_parser/src/lib.rs`,
|
||||
`crates/lucisv/src/main.rs`, `crates/lucisv_server/src/main.rs`,
|
||||
`crates/lucisv_server/src/server.rs` (one doc comment),
|
||||
`crates/vlog_formatter/tests/deep_nesting.rs`, `crates/lucisv/tests/cli.rs`,
|
||||
`crates/vlog_semantic/tests/deep_nesting.rs` (new),
|
||||
`docs/features/parallel-files/README.md`, `TODO.md`, this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
@@ -884,8 +1112,208 @@ No new BLOCKING finding. No code changes made this round (the one finding
|
||||
is a documentation number, not something I judged a "small unambiguous
|
||||
fix" worth touching without the dev confirming their construction).
|
||||
|
||||
### 2026-08-28 — QA agent, the stack the limit needs
|
||||
|
||||
**Tooling results (verbatim):** `cargo fmt --check`: clean, exit 0.
|
||||
`cargo clippy --all-targets`: silent, no warnings. `cargo test --workspace`:
|
||||
every binary green, 0 failed across the run (`vlog_parser` lib 1204 passed/23
|
||||
ignored, `vlog_semantic` 82 + 62 + 3 new `deep_nesting`, `vlog_formatter` 4
|
||||
`deep_nesting`, `lucisv` 217 + the new stdin test, `lucisv_server` 190 + 20 +
|
||||
114 + others, doc-tests all 0/0 except `vlog_linter`'s 1/1) — matches the
|
||||
dev's "2425 passed, 0 failed" claim (one transient doctest failure on a first
|
||||
run, `vlog_linter`'s, traced to a stale rlib left by my own concurrent
|
||||
`git stash`/rebuild during the ulimit test below, not a real regression —
|
||||
reran `cargo test -p vlog_linter --doc` clean on its own and the next full
|
||||
`cargo test --workspace` was clean too).
|
||||
|
||||
**Independent audit of every thread/pool/par_iter outside `#[cfg(test)]`
|
||||
(charter item 1) — matches the dev's table exactly, no missed site.**
|
||||
`grep -rn "thread::spawn\|thread::Builder\|ThreadPoolBuilder\|par_iter\|\.spawn("
|
||||
crates --include="*.rs"` and traced every hit:
|
||||
|
||||
- `lucisv/src/main.rs`'s own spawn (the "lucisv" thread) and `build_pool`
|
||||
(rayon global pool): both `PARSE_STACK_SIZE`, as claimed.
|
||||
- `lucisv/src/lint.rs:48`'s `jobs.par_iter()` (the `check` subcommand,
|
||||
charter's "vlog_linter/vlog_refactor entry points from the CLI pool"):
|
||||
confirmed it runs on the *same* rayon global pool `build_pool` sizes —
|
||||
`run_check` calls `gather(opts).and_then(|jobs| build_pool(opts).map(...))`
|
||||
before `lint::check_files`, same as `run_files`. `check`'s stdin path
|
||||
(`lint::check_stdin`) never touches the pool at all; it runs on `run_check`
|
||||
called from `run()`, which is the body of the spawned "lucisv" thread — so
|
||||
it inherits `PARSE_STACK_SIZE` the same way `run_stdin` does. Not a missed
|
||||
site; the dev's table entry ("the whole run") already covers it, just not
|
||||
spelled out by name.
|
||||
- `lucisv_server/src/main.rs`'s spawn and `server.rs::queue`'s forwarder:
|
||||
match the table.
|
||||
- `lucisv_server/src/index_cache.rs:921,1194` and `state.rs:3374` (a
|
||||
`qa_attack_…` test spawning at a deliberate 64 MiB, with a comment citing a
|
||||
*different*, pre-existing recursion ceiling filed in `index-scope`'s own
|
||||
2026-08-28 QA log) — all three are inside `#[cfg(test)] mod tests`
|
||||
(checked with `grep -n "#\[cfg(test)\]"` in each file), so they are
|
||||
correctly outside the dev's stated audit scope ("outside `#[cfg(test)]`")
|
||||
and outside production risk. Tried to find a production path to them
|
||||
anyway (workspace-scan-on-`initialize`, watched-file rescans) — found none;
|
||||
`index_cache`'s writers only run inside its own test module.
|
||||
- `lsp-server` 0.10.0's own threads (`stdio.rs`): read the vendored source at
|
||||
`~/.cargo/registry/src/…/lsp-server-0.10.0/src/stdio.rs` — reader and
|
||||
writer threads only frame/deframe `Message` (JSON-RPC header parsing via
|
||||
`usize::parse`, unrelated to `vlog_parser`), no `vlog_parser` symbol
|
||||
anywhere in the crate. Confirms charter item 2's second half directly from
|
||||
the dependency's source, not by inference.
|
||||
- `server.rs::queue` (charter item 2's first half): read `queue()` and
|
||||
`run()` in full. The forwarder thread's closure captures only
|
||||
`source`/`sender`, does `source.recv()` → `sender.send()` → break on
|
||||
`is_shutdown`/`Err`, touches no field of `Server`; `run()` and
|
||||
`process_batch` are the only things that call `self.request`/
|
||||
`self.notification` (which reach analysis), and they execute on the
|
||||
thread `Server::run` was called on, i.e. the spawned `"lucisv-main"`
|
||||
thread. The module doc at `server.rs:1` ("one burst in, one response per
|
||||
request, on one thread") holds; `didChangeWatchedFiles` and every other
|
||||
notification dispatch through `Server::notification` (`server.rs:1249`),
|
||||
called only from `process_batch`, same thread.
|
||||
|
||||
No un-gated production parse-reachable spawn found. Dev's table is accurate
|
||||
and complete.
|
||||
|
||||
**Charter item 3 (library-consumer footgun) — real gap found, fixed
|
||||
directly as a small unambiguous doc fix.** The README's Handshakes section
|
||||
states the contract plainly ("any thread that can reach
|
||||
`tokenize`/`parse`/`analyze` is spawned with `stack_size(PARSE_STACK_SIZE)`"),
|
||||
but that is an internal project document, not rustdoc — a consumer of
|
||||
`vlog_parser`/`vlog_semantic`/`vlog_formatter` as a library reads the public
|
||||
items' own doc comments, and none of them said anything: `vlog_parser::parse`
|
||||
(`parser.rs:271`), `parse_tolerant` (`parser.rs:283`), `vlog_semantic::
|
||||
FileFacts::of` (`workspace.rs:741`), `vlog_formatter::format_source`
|
||||
(`format.rs:80`) and `format_range` (`format.rs:101`) — the five public
|
||||
entry points that actually recurse over caller-supplied input — carried no
|
||||
stack-size mention at all. Confirmed by reading each doc comment before this
|
||||
fix; `tokenize` (`lexer.rs:731`) checked too and correctly excluded — it is
|
||||
loop-based with no recursion on nesting, so it carries no such requirement.
|
||||
Added a one- to three-line note to each of the five, referencing
|
||||
`PARSE_STACK_SIZE` and (except `parse`/`parse_tolerant`, which are right next
|
||||
to the constant) `docs/features/recursion-limit/README.md`. Files touched:
|
||||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_semantic/src/workspace.rs`,
|
||||
`crates/vlog_formatter/src/format.rs`. Re-ran `cargo fmt --check` and
|
||||
`cargo clippy --all-targets` after — both still clean.
|
||||
|
||||
**Charter item 4 (sabotage re-verify), on a scratchpad copy, never the
|
||||
repo under review.**
|
||||
|
||||
- `PARSE_STACK_SIZE` 16 MiB → 2 MiB, rebuilt: `cargo test -p vlog_semantic
|
||||
--test deep_nesting`, `cargo test -p vlog_formatter --test deep_nesting`
|
||||
and `cargo test -p vlog_parser --lib` (which builds `parse_deep` on the
|
||||
same constant) **all SIGABRT** ("stack overflow, aborting", signal 6) —
|
||||
every deep-nesting test suite genuinely depends on the constant rather
|
||||
than merely running beside it. Restored to 16 MiB and reran: all three
|
||||
green again (`vlog_semantic`: 3/3, `vlog_formatter`: 4/4, `vlog_parser`
|
||||
lib: full suite).
|
||||
- `MAX_NESTING_DEPTH` 64 → 128, `PARSE_STACK_SIZE` left at 16 MiB (the
|
||||
"double the limit, keep the stack" margin check): `vlog_semantic`'s
|
||||
`deep_nesting` (3/3), `vlog_formatter`'s `deep_nesting` (4/4) and
|
||||
`vlog_parser`'s `nesting_just_below_the_limit_parses`,
|
||||
`chain_just_below_the_limit_parses`, `the_fattest_block_forms_still_
|
||||
parse_at_the_limit` and `deep_nesting_errors_for_every_block_form` all
|
||||
**passed** — including `the_fattest_block_forms_still_parse_at_the_limit`,
|
||||
which now parses 122-deep `fork`/`case` nesting (`MAX_NESTING_DEPTH - 6`)
|
||||
on the same 16 MiB stack that only had to reach 58 before. The 2.7×
|
||||
margin is real, not illusory: it survives doubling the depth the tests
|
||||
actually walk. Reverted `MAX_NESTING_DEPTH` to 64. Verified afterward that
|
||||
the working tree's `parser.rs` shows only the intended diff (`grep -n
|
||||
"MAX_NESTING_DEPTH: u32\|PARSE_STACK_SIZE: usize"` → `64` and
|
||||
`16 * 1024 * 1024`, matching what `git status` shows for the round under
|
||||
review).
|
||||
|
||||
**Charter item 5 (binary end-to-end) — both scenarios behave as claimed,
|
||||
and the pre-fix binary was rebuilt to confirm the deviation is load-bearing,
|
||||
not cosmetic.**
|
||||
|
||||
- Directory run: a temp dir with `good.sv` and a 500-nested-`begin` file
|
||||
through `./target/debug/lucisv .`: `error: ./deep500.sv: parse error:
|
||||
64:1: nesting too deep (limit 64) (found "begin")` /
|
||||
`1 file left unchanged, 1 file failed to format`, exit 2. `good.sv`
|
||||
untouched (it was already formatted), `deep500.sv`'s first 60 bytes
|
||||
confirmed byte-identical to the input. No abort.
|
||||
- `ulimit -s 1024; lucisv - < deep500.sv` (1 MiB main-thread stack) on the
|
||||
**fixed** binary: `error: <stdin>: parse error: 64:1: nesting too deep
|
||||
(limit 64) (found "begin")`, exit 2, no crash.
|
||||
- To confirm this isn't true regardless of the fix (i.e. that the moved-main
|
||||
deviation actually matters, not just the depth counter): stashed the
|
||||
round's diff (`git stash`, working tree confirmed clean via `git status`),
|
||||
rebuilt `lucisv`, and ran the identical `ulimit -s 1024` command against
|
||||
the **pre-fix** binary: `thread 'main' (…) has overflowed its stack /
|
||||
fatal runtime error: stack overflow, aborting`, exit 134 (SIGABRT) — same
|
||||
input, same shell, only the binary differs. Popped the stash (`git stash
|
||||
pop`, confirmed all twelve modified files and the new test file were back)
|
||||
and rebuilt the fixed binary; reran the same command to reconfirm exit 2.
|
||||
This is the one experiment in this round that actually falsifies "the
|
||||
depth counter alone was always going to be enough" — it was not, on a
|
||||
shell with a small `ulimit -s`, until `main` stopped running on the OS-given
|
||||
stack.
|
||||
|
||||
**Charter item 5, LSP half — independently reproduced via a standalone LSP
|
||||
client (not the dev's own manual verification, not the checked-in `e2e.rs`
|
||||
suite, which has no test for this exact repro).** Wrote a small Python
|
||||
script (framed JSON-RPC over the real `lucisv-server` binary's stdio) that
|
||||
sends `initialize` → `initialized` → `didOpen` (the 500-nested-`begin` file)
|
||||
→ `documentSymbol` → `shutdown` → `exit`. Result: `publishDiagnostics` with
|
||||
`"nesting too deep (limit 64) (found \"begin\")"` at line 63, a second
|
||||
diagnostic for the resulting `endmodule` mismatch, `documentSymbol` still
|
||||
answers with module `m` (`range` spanning the whole 564-line file), clean
|
||||
`shutdown` (`id: 99, result: null`) and process exit code 0. No crash, no
|
||||
hang, matches the dev's manual claim independently.
|
||||
|
||||
**Charter item 6 (idempotency/corruption) — holds.** On the fixed binary:
|
||||
a 58-nested-`begin` file (one under the dev's stated 59/60 with-statement
|
||||
boundary — chosen so the *statement* inside costs its extra levels too, same
|
||||
construction the boundary table uses) formats once, then formats again from
|
||||
its own output: `diff` reports the two outputs identical, i.e.
|
||||
`format(format(x)) == format(x)`. The 500-nested-`begin` file piped through
|
||||
`lucisv -`: stdout is exactly 0 bytes (no partial output), stderr carries
|
||||
the one-line diagnostic, exit 2 — the "verified-correct output or the input
|
||||
unchanged with an error, never partial" invariant holds for the rejection
|
||||
path on the CLI's own thread, consistent with the directory-run and
|
||||
`vlog_semantic` test evidence that the tolerant/LSP path never produces a
|
||||
corrupted tree either (recovery yields an `ItemKind::Error` leaf, not
|
||||
partial/wrong facts).
|
||||
|
||||
**Verdict: SHIP.** No blocking or medium finding. One low finding (the
|
||||
library-consumer stack-size contract living only in an internal README, not
|
||||
in any public item's rustdoc) fixed directly per CLAUDE.md's "small
|
||||
unambiguous fix" allowance — five doc comments, no behavior change, gates
|
||||
re-confirmed clean after. The round's own claims all independently
|
||||
reproduced: the audit table is complete, the forwarder and `lsp-server`
|
||||
threads are confirmed parse-free by reading their code (not just trusting
|
||||
the comment), the stack-size guarantee is real under sabotage in both
|
||||
directions (shrinking it breaks the tests it should break; doubling the
|
||||
depth limit under the existing stack does not), and both the CLI and LSP
|
||||
binaries handle the original repro gracefully end-to-end, including the one
|
||||
scenario (`ulimit -s 1024`) where the pre-fix binary provably still crashes.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead, stack-budget round.** Reviewed after QA's SHIP;
|
||||
gates re-run independently (fmt clean, clippy silent, 2425 workspace
|
||||
tests green). The round did the right thing with the diagnosis: nothing
|
||||
was missing a counter — the 2026-08 feature's own "8 MiB is available"
|
||||
Assumption was the unenforced hole, and its measured basis had silently
|
||||
drifted (~62→~94 KiB per level under rustc 1.97, worst family now
|
||||
nested `case`, never measured in the original round). Turning the
|
||||
assumption into one code-enforced constant (`PARSE_STACK_SIZE`, 16 MiB,
|
||||
2.7× over the re-measured worst case) applied at every parse-reaching
|
||||
spawn site is the boring fix the situation wanted; the dev's deviation
|
||||
of moving both binaries' work off the main thread is load-bearing, not
|
||||
cosmetic — QA proved the pre-fix binary aborts under `ulimit -s 1024`
|
||||
where the fixed one emits a diagnostic, and the win32 target's 1 MiB
|
||||
default main stack made this a real shipped-binary risk, not just a
|
||||
test-thread artifact. QA's independent spawn-site audit matched the
|
||||
dev's table exactly, the sabotage runs prove the tests exercise the
|
||||
guarantee (2 MiB → SIGABRT) and the margin survives doubling the depth
|
||||
limit, and its doc fix — the caller-side stack contract on every public
|
||||
parse entry point's rustdoc — closes the library-consumer footgun the
|
||||
lead's charter flagged. Invariant 1 spot-checks (no partial output on
|
||||
rejection, idempotent round-trip at depth) held. Accepted; committed by
|
||||
the lead.
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed after one rejection
|
||||
and a verified rework.**
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -104,15 +116,71 @@ standard capability both VS Code's built-in client and Neovim's `vim.lsp`
|
||||
consume on their own once it is advertised; no extension change was needed
|
||||
and none was made.
|
||||
|
||||
**Requested of other modules**: none.
|
||||
**Requested of other modules (2026-08-28) — DELIVERED 2026-08-28** by the
|
||||
index-scope round; see `docs/features/index-scope/README.md`, work log
|
||||
"a rescan stops re-parsing what is already analyzed". An open buffer's index
|
||||
facts and completion words now come from the analysis it already holds
|
||||
(`FileFacts::from_analysis`, `words_of_tokens`), on the whole-rebuild path and
|
||||
on `update_one`'s: **~228 ms → ~23 ms** on this feature's own probe. The request
|
||||
as it was written:
|
||||
|
||||
**Requested of other modules (2026-08-28):** a scope-widening `didOpen`
|
||||
re-parses every open buffer. `Workspace::collect_sources`
|
||||
(`crates/lucisv_server/src/state.rs`) clones each open document's text into the
|
||||
list the index is rebuilt from, so a rescan triggered by opening some *other*
|
||||
file pays a full lex-and-parse of every buffer the user has open — measured at
|
||||
**210 ms of a 223 ms rescan** for one 1.4 MB `top.sv`, against 13 ms for the
|
||||
same 401-file scope with that buffer closed. Every open buffer already holds a
|
||||
finished parse and `Semantics`; `FileFacts::of` re-does both from the text.
|
||||
This is `index-scope` / `state.rs` territory, not this feature's, and the
|
||||
2026-08-28 brief said measure it and stop — so it is written here rather than
|
||||
changed. The obvious shape (an `IndexBuilder::add_facts` path fed from the
|
||||
buffer's existing analysis instead of its text) is a real option and a separate
|
||||
decision.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] **References latency with a big buffer open (2026-08-28):** measure both
|
||||
directions of a cross-file references request while a 1.4 MB, 40 000-line
|
||||
`top.sv` is an open document, then fix what the numbers convict. Landed:
|
||||
a **spelled-name prefilter** and a **hoisted `file_id`** in
|
||||
`indexed_references`'s open-document overlay loop, and **walker-batched**
|
||||
span conversion in the two in-file fallbacks. Release probes:
|
||||
**3.20 ms → 110 µs** from the use site, **3.18 ms → 110 µs** from the
|
||||
declaration (29×); the in-file fallback for a signal used 10 001 times,
|
||||
**1.76 ms → 1.18 ms**, and `documentHighlight` on it **1.54 ms → 917 µs**.
|
||||
No answer changes — the equivalence test against
|
||||
`vlog_refactor::find_references` and the whole nav suite are untouched
|
||||
and green.
|
||||
- [x] **Not this feature's to fix, measured and filed (2026-08-28) — fixed
|
||||
elsewhere the same day:** the owner-reported *asymmetry* is not in
|
||||
`references` at all — both directions cost the same, before and after.
|
||||
What is expensive is the `didOpen` that jumping into another folder's
|
||||
file triggers: **220 ms**, of which **210 ms** is re-parsing the open big
|
||||
buffer during the scope-widening rescan. See the work log and
|
||||
Handshakes. Landed by `index-scope` on 2026-08-28 — the open buffer's
|
||||
facts and words now come from its own finished analysis — and this
|
||||
feature's `qa_didopen_latency_when_a_new_folder_widens_the_scope` probe
|
||||
reads **~228 ms → ~23 ms**, with its closed-buffer floor unmoved at
|
||||
~12 ms. The probe now also prints the buffer's own share of a rescan,
|
||||
before and after, on every run.
|
||||
|
||||
- [x] **Indexed navigation performance (2026-08-27):** persist each file's
|
||||
externally reachable reference facts beside its declarations, merge them
|
||||
into declaration-to-occurrence postings in `WorkspaceIndex`, and route
|
||||
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 +210,183 @@ and none was made.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-28 — references latency with a big buffer open
|
||||
|
||||
The owner reported find-references from a *use site* in a big open `top.sv`
|
||||
toward a module as "still very slow", and the same request from the module's
|
||||
*declaration* toward its uses as fast. Both run the same
|
||||
`indexed_references`, so the asymmetry was unexplained. Measured first.
|
||||
|
||||
**The fixture.** Two `#[ignore]`d probes in `nav.rs`'s own test module, beside
|
||||
the `qa_indexed_references_latency_over_a_large_workspace` probe that has been
|
||||
there since 2026-08-27, and taken with `perf::mean` (now `pub(crate)`) so every
|
||||
number in this repo is timed the same way. `generated_top(10_000, 4)` is a
|
||||
40 000-line, 1 374 KB module of ordinary RTL blocks — a wire, an assign, a
|
||||
register and its update — carrying **70 024 references**, four instantiations
|
||||
of a small `sub`, and one local `acc` used by every block so the file also has
|
||||
a *local* name with 10 001 occurrences. Both files are open documents; the
|
||||
index is built over the directory.
|
||||
|
||||
```text
|
||||
cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
Machine: the one `docs/perf/README.md` records — Apple M1 Max, macOS 27.0,
|
||||
`--release`. Means of 20 runs (5 for the rescan rows).
|
||||
|
||||
| what | before | after |
|
||||
|---|---|---|
|
||||
| `references` from the **use site** in `top.sv`, `includeDeclaration` | **3.20 ms** | **110 µs** |
|
||||
| `references` from the **declaration** in `sub.sv`, same | **3.18 ms** | **110 µs** |
|
||||
| `definition` from the use site | 1.21 µs | 1.13 µs |
|
||||
| `references` on a local wire used 3× (the in-file fallback) | 1.49 µs | 1.20 µs |
|
||||
| `references` on a local wire used 10 001× | **1.76 ms** | **1.18 ms** |
|
||||
| `documentHighlight` on that same wire | **1.54 ms** | **917 µs** |
|
||||
|
||||
**Hypothesis 1 is convicted, and it is symmetric.** The open-document overlay
|
||||
loop was the whole 3.2 ms: for every one of the 70 024 references in the open
|
||||
buffer it ran either `indexed_def_for_symbol` — a `file_id` binary search whose
|
||||
comparisons are whole-path `cmp`s, plus a `units`/`member` `BTreeMap` lookup,
|
||||
plus a scope-and-owner chase — or a `doc.external` hash lookup, to discard all
|
||||
but five of them. It cost that whichever end the cursor was on, which is the
|
||||
first thing the measurement says: **the two directions are within 1 % of each
|
||||
other, before and after.** The owner's asymmetry is not in `references`.
|
||||
|
||||
**Hypothesis 2 registers, but only for a common local name.** The in-file
|
||||
fallback and `documentHighlight` convert their spans one at a time with
|
||||
`positions.range`, which re-measures a line per span. On three occurrences that
|
||||
is 1.5 µs and invisible; on 10 001 it is 1.76 ms. Both now batch-convert with
|
||||
`positions.walker()` over the already-sorted span list, exactly as `locations`
|
||||
has done for the cross-file answer since this feature shipped — 1.5× and 1.7×.
|
||||
The rest of those two figures is collecting, sorting and allocating 10 001
|
||||
spans, which is the answer's own size and not something to shave here.
|
||||
|
||||
**Hypothesis 3 is where the felt latency actually is** — measured, and
|
||||
deliberately not redesigned this round (see Handshakes). With the same 1.4 MB
|
||||
buffer open and 401 files in scope:
|
||||
|
||||
| `didOpen` | cost |
|
||||
|---|---|
|
||||
| a file the folder scope **already covers** | **8.4 µs** |
|
||||
| a file in a **new folder** (`didOpen` + the rescan `server.rs` then runs) | **220 ms** |
|
||||
| — the rescan alone | 223 ms |
|
||||
| — the same rescan with the big buffer **closed** | **13 ms** |
|
||||
|
||||
So the scope-widening rescan is 223 ms, and **210 ms of it is the open big
|
||||
buffer**: `Workspace::collect_sources` clones every open document's text into
|
||||
the source list and the index re-parses it, at full lex-and-parse cost, on a
|
||||
rescan that was triggered by an entirely different file. That is the shape that
|
||||
matches the owner's report: F12 or a references result *from* `top.sv` opens the
|
||||
module's file, and when that file lives in a folder the folder scope had not
|
||||
reached, the `didOpen` widens the scope and pays a whole rescan. The reverse
|
||||
direction — standing on the declaration and listing its uses — opens nothing
|
||||
new and pays nothing. Filed as a Handshake request against `index-scope` /
|
||||
`state.rs`; no scope code was touched.
|
||||
|
||||
**The prefilter, and why it changes no answer.** The new first line of the
|
||||
overlay loop is `if reference.name != target.name { continue }`. It is sound
|
||||
because *a `Def` in this index determines the name it is filed under*, and both
|
||||
sides of the old comparison are filed under a name the code already has in
|
||||
hand:
|
||||
|
||||
- Every indexed `Def` is pushed into `units[name]` or `members[unit][name]`
|
||||
under its own declaration's `name`, and both `facts_of` and `collect_members`
|
||||
skip any declaration whose `name_span` is empty. A non-empty byte range in
|
||||
one file is one identifier, spelling one name — so two different keys cannot
|
||||
hold one `Def` value, and `target.def`'s key is `target.name` in both
|
||||
`indexed_target` arms (the `Local` arm looks the def up *by* `symbol.name`
|
||||
and stores that as `name`; the `External` arm stores the cursor reference's
|
||||
own `name`, which is the only key `follow_one` looks a def up under).
|
||||
- A reference that would have matched is filed under `reference.name`. In the
|
||||
Local arm, a `Resolution::Resolved` comes from `lookup_local(name)` (or an
|
||||
end label the binder checked spells the declaration's name), so
|
||||
`symbol.name == reference.name`, and `indexed_def_in_file` looks up
|
||||
`units[symbol.name]` / `members[owner][symbol.name]`. In the External arm,
|
||||
`resolve_external` calls `follow_one(index, reference.name, path)`, which
|
||||
only ever reads `units[reference.name]` or `member(unit, reference.name)`.
|
||||
|
||||
So `def == target.def` implies `reference.name == target.name`, and skipping
|
||||
the name-mismatched references skips only work whose answer was `false`.
|
||||
|
||||
**The `Ambiguous` refusal survives it**, by the same step: the candidates in
|
||||
`ExternalTarget::Ambiguous(defs)` all come out of the bucket keyed by
|
||||
`reference.name`, so `defs.contains(&target.def)` can only be true for a
|
||||
reference spelling `target.name` — which the prefilter always lets through. The
|
||||
`name_span.is_empty()` guard was deliberately *not* hoisted into the prefilter
|
||||
for the same reason: an ambiguous use aborts the whole collection whether or not
|
||||
it has a span, and moving that check earlier would have been a real behaviour
|
||||
change.
|
||||
|
||||
**The hoist.** `indexed_def_for_symbol` is now two functions: the public one
|
||||
(unchanged signature, still `hover.rs`'s) resolves the document's `FileId` and
|
||||
calls `indexed_def_in_file`, which takes it as an argument. The overlay loop
|
||||
takes the `file_id` once per open buffer instead of once per reference.
|
||||
|
||||
**What is left at 110 µs** is the loop itself: 70 024 string comparisons plus
|
||||
the iteration. Making that sublinear means a name-keyed reference side table in
|
||||
`Semantics` — the shape `symbols_named` already has for declarations — which is
|
||||
a `vlog_semantic` change this round's brief put out of scope. Not needed at
|
||||
110 µs; worth naming as the next lever if a file ten times this size shows up.
|
||||
|
||||
**Tests added** (permanent, all three green before and after the change, which
|
||||
is the point — the prefilter must change cost and not answers):
|
||||
|
||||
- `a_same_named_port_in_another_open_buffer_is_a_different_symbol` — two
|
||||
modules declare a port `clk`, all three files open; each port's references
|
||||
are its own. The prefilter's risk case, from both sides.
|
||||
- `two_packages_declaring_one_name_keep_their_references_apart` — the same
|
||||
attack through the member table: `p::WIDTH` and `q::WIDTH` used on adjacent
|
||||
lines of one open file, asked from the declaration and from the use.
|
||||
- `every_in_file_occurrence_is_converted_against_its_own_line` — 41
|
||||
occurrences over 40 lines each carrying a multi-byte and an astral character;
|
||||
every reported range is checked to point at the name, and
|
||||
`documentHighlight`'s ranges are asserted equal to `references`'. A walker
|
||||
handed spans out of order would answer stale columns here.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
|
||||
zero warnings; `cargo test --workspace` **2 406 passed, 0 failed** (3 ignored
|
||||
probes in `nav.rs`, one of them pre-existing). Files edited:
|
||||
`crates/lucisv_server/src/nav.rs` and one `pub(crate)` on `perf::mean`. No new
|
||||
dependencies, no `unsafe`, no `unwrap`/`expect` outside `#[cfg(test)]`, no new
|
||||
`#[allow]`. `TODO.md` untouched — this round closes no backlog item; M7 is
|
||||
already checked. Did not `git commit`/`git push`.
|
||||
|
||||
### 2026-08-27 — indexed navigation performance
|
||||
|
||||
- Began replacing the per-request `Workspace::sources()` +
|
||||
`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,
|
||||
@@ -211,6 +456,158 @@ Files added: `crates/vlog_refactor/src/references.rs`,
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-28 — QA agent, references-latency round
|
||||
|
||||
Adversarial charter: try to make the new spelled-name prefilter (`nav.rs:248`,
|
||||
`indexed_references`) **change an answer**. Slower-but-right was already true;
|
||||
only a changed answer is a defect this round.
|
||||
|
||||
#### Soundness of the prefilter — traced by construction, not just trusted
|
||||
|
||||
Read the dev's write-up's claim against the actual code that makes it true,
|
||||
rather than the prose alone:
|
||||
|
||||
- `Def` (`crates/vlog_semantic/src/workspace.rs:33`) derives `PartialEq` over
|
||||
`(file, name_span, kind, detail_span)` — it carries no name at all. Its
|
||||
identity is "this declaration, right here," so `def == target.def` can only
|
||||
be decided by the site it points at, never by a spelling.
|
||||
- Every `Decl` is filed under exactly one key, its own declared name:
|
||||
`self.units.entry(decl.name.clone())...push(decl.def(file))`
|
||||
(`workspace.rs:529`) and `self.members.entry(unit.clone())...entry(decl.name.clone())...push(decl.def(file))`
|
||||
(`workspace.rs:535-540`). `decl.name` traces back to `Symbol.name`
|
||||
(`Decl::of`, `workspace.rs:654`), and `Symbol.name`/the scope's `names` map
|
||||
key are the same `name.to_string()` written in one `declare` call
|
||||
(`bind.rs:141` and `bind.rs:151`) — so a `Def` cannot be filed under a name
|
||||
it wasn't declared with, and cannot be filed under two names.
|
||||
- `Scope::lookup_local` (`model.rs:215`) is a plain `HashMap<String,
|
||||
SymbolId>` `get` — no case-folding, no normalization. Every
|
||||
`Resolution::Resolved(id)` in `resolve.rs` comes from `lookup_local(&p.name)`
|
||||
(or `Target::Declaration(id)`, an end label the binder already matched to
|
||||
its opener's name). `Reference.name` is `p.name.clone()` at the exact
|
||||
construction site (`lib.rs:78-79`). So a **locally** resolved reference's
|
||||
`.name` is *definitionally* `symbol.name` — the prefilter reads the same
|
||||
field the binder used to decide the match, not a second, potentially
|
||||
divergent, source of truth.
|
||||
- The **external** arm is the same shape one level up: `resolve_external`
|
||||
(`workspace.rs:1097`) always calls `follow_paths(index, &reference.name,
|
||||
paths)`, and `follow_one` (`workspace.rs:1132`) always queries
|
||||
`index.units(name)` or `index.member(unit, name)` with that same `name` —
|
||||
`path` only picks *which* table, never the key. So both `Resolved(def)` and
|
||||
`Ambiguous(defs)` for a reference are always drawn from the bucket keyed by
|
||||
that reference's own `.name`, which makes the dev's ambiguity-survives
|
||||
argument mechanical rather than incidental: `defs.contains(&target.def)`
|
||||
can only be true when `defs` came from the `target.name` bucket, which only
|
||||
happens when `reference.name == target.name` — exactly what the prefilter
|
||||
already let through.
|
||||
|
||||
No escaped-identifier or case-folding attack survives this: the lexer
|
||||
(`crates/vlog_parser/src/lexer.rs:304-318`) keeps an escaped identifier's
|
||||
leading backslash in the token text (`\sub` and `sub` are different strings
|
||||
at the token level already), and nothing between the lexer and
|
||||
`Scope::names` ever folds case or strips it — so whatever the binder already
|
||||
does or doesn't unify, the prefilter reads the identical field the binder
|
||||
matched on. There is no code path where `reference.name` and the spelling the
|
||||
binder used to resolve it can diverge, so there is no daylight for the
|
||||
prefilter to exploit. Traced, not fuzzed — I did not find a construction
|
||||
worth writing as a failing-if-regressed test beyond what's below, because the
|
||||
invariant is enforced by there being exactly one string in play, not by a
|
||||
check that could later be weakened unnoticed.
|
||||
|
||||
**Verdict on the prefilter: sound, no answer-changing case found.**
|
||||
|
||||
#### Attempts to break it anyway
|
||||
|
||||
- **Port connection vs. declared name, member-table variant.** Extended the
|
||||
attack beyond the dev's own two tests (`a_same_named_port_in_another_open_buffer_is_a_different_symbol`,
|
||||
`two_packages_declaring_one_name_keep_their_references_apart`) with a name
|
||||
that is a **unit in one file and a member in another** — `module W` and
|
||||
`package p; localparam W = 4;` — plus a **live unsaved edit** to the file
|
||||
using both (a second instantiation added post-open, never saved). Added as
|
||||
`indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member`
|
||||
(`nav.rs:662`), asserted equal to `vlog_refactor::find_references` on
|
||||
`ws.sources()` (which itself overlays the unsaved edit) in both directions.
|
||||
Passed first try — no answer conflation between the `units` and `members`
|
||||
buckets, and the unsaved instantiation is correctly counted.
|
||||
- **Walker ordering/multi-byte/astral attack** on the two newly-batched
|
||||
conversion sites (`in_file_references` and `document_highlights`, now both
|
||||
walker-based per `nav.rs:347` and `nav.rs:374`). The dev's own
|
||||
`every_in_file_occurrence_is_converted_against_its_own_line` already covers
|
||||
this shape well (41 occurrences over 40 lines, each preceded by a
|
||||
multi-byte and an astral character, every reported range checked against
|
||||
the actual byte); I did not find a shape it misses. The walker itself
|
||||
(`crates/lucisv_server/src/convert.rs`, `PositionWalker`) is pre-existing,
|
||||
general-purpose infrastructure (`locations()` has used it since the
|
||||
2026-08-27 round) with its own dedicated tests for out-of-order offsets,
|
||||
ping-ponging between far-apart lines, and an empty document
|
||||
(`the_walker_agrees_with_the_per_call_converter_on_every_shape`,
|
||||
`a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position`,
|
||||
`a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly`,
|
||||
`a_walker_over_an_empty_document_answers_the_one_position_there_is`, all in
|
||||
`convert.rs`) — so the only new risk this round is whether
|
||||
`in_file_references`/`document_highlights` feed it spans in order, and they
|
||||
do: both consume `occurrences()`, which sorts by `span.start`
|
||||
(`nav.rs:413`) before the walker ever sees them. No out-of-order feed
|
||||
exists on either path.
|
||||
- **Ambiguous-abort still aborts.** Re-ran
|
||||
`a_name_declared_in_two_files_degrades_references_to_the_in_file_answer`
|
||||
(already in the suite, unmodified by the dev this round) and traced the
|
||||
`Ambiguous(defs) if defs.contains(&target.def) => return None` arm
|
||||
(`nav.rs:258-260`) by hand against the bucket argument above: an ambiguous
|
||||
external use can only carry `target.def` in its candidate set when it
|
||||
spells `target.name`, which is exactly when the prefilter lets it reach
|
||||
this arm. Confirmed by construction, not just by the still-green test.
|
||||
- **Equivalence, existing test.** `indexed_references_equal_the_refactor_walk_they_replace`
|
||||
(`nav.rs:648`, pre-dating this round) still passes unmodified.
|
||||
|
||||
#### Measurements reproduced (release, `--release`, this machine)
|
||||
|
||||
```
|
||||
cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
| what | work log | reproduced here |
|
||||
|---|---|---|
|
||||
| references, use site | 110 µs | 109.8 µs |
|
||||
| references, declaration | 110 µs | 108.9 µs |
|
||||
| definition, use site | 1.13 µs | 0.82 µs |
|
||||
| in-file, wire used 3× | 1.20 µs | 1.12 µs |
|
||||
| in-file, wire used 10 001× | 1.18 ms | 1.17 ms |
|
||||
| documentHighlight, same wire | 917 µs | 916 µs |
|
||||
| didOpen, scope already covers | 8.4 µs | 7.3 µs |
|
||||
| didOpen, new folder (+ rescan) | 220 ms | 214.6 ms |
|
||||
| rescan alone | 223 ms | 217.7 ms |
|
||||
| rescan, big buffer closed | 13 ms | 12.5 ms |
|
||||
|
||||
All within the charter's 2-3× tolerance (most within 5%) — no contradiction
|
||||
of the work log's order-of-magnitude claims. The pre-existing
|
||||
`qa_indexed_references_latency_over_a_large_workspace` probe (2026-08-27,
|
||||
untouched by this round) also still ran clean: 0.068 ms/request vs. 31.35 ms
|
||||
for the old walk on this machine, consistent with that round's own numbers.
|
||||
|
||||
#### Gates
|
||||
|
||||
- `cargo fmt --all -- --check` — clean.
|
||||
- `cargo clippy --all-targets --all-features` — clean, zero warnings (forced
|
||||
re-check by `touch`ing the changed files first, not a cache hit).
|
||||
- `cargo test --workspace` — **2 406 passed, 0 failed** before my addition,
|
||||
matching the work log's count exactly; **2 407** after adding the one
|
||||
permanent equivalence test above. 24 ignored across the workspace (3 in
|
||||
`nav.rs`, one of those pre-existing, matching the work log).
|
||||
|
||||
**All gates: pass, claims confirmed.**
|
||||
|
||||
#### Verdict
|
||||
|
||||
**SHIP.** No corruption, no answer change, no crash found under the
|
||||
adversarial charter. The prefilter's soundness holds by construction (one
|
||||
string, read by both the binder and the prefilter, never normalized or
|
||||
duplicated anywhere in between), not merely by the tests passing. One
|
||||
permanent regression test added
|
||||
(`indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member`,
|
||||
`nav.rs:662`) for the nastier unit/member name-collision case with a live
|
||||
unsaved edit, requested by the round's brief; no other findings warranted a
|
||||
fix or a new test. Review section left untouched.
|
||||
|
||||
### 2026-08-24 — QA agent
|
||||
|
||||
#### Gates
|
||||
@@ -463,6 +860,45 @@ correctness or safety issue in the shipped feature.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead, references-latency round.** Reviewed after QA's
|
||||
clean SHIP; gates re-run independently (fmt clean, clippy silent, 2407
|
||||
workspace tests green). Measure-first discipline held: the probes were
|
||||
written and their before-numbers recorded ahead of any fix, and they
|
||||
convicted the overlay loop (H1) while acquitting `references` of the
|
||||
owner-reported asymmetry — which the didOpen numbers (H3) explain
|
||||
instead, correctly filed as a Handshake request rather than fixed
|
||||
cross-scope. The prefilter comment in `indexed_references` points at
|
||||
the soundness argument, QA traced that argument to the code
|
||||
(single-key filing, no name normalization anywhere between lexer and
|
||||
lookup), and the unit-vs-member equivalence test QA added is the
|
||||
sharpest same-spelling case the design admits. The empty-span check
|
||||
deliberately left unhoisted — so a spanless ambiguous use still aborts
|
||||
— is the kind of detail that separates a fast loop from a subtly
|
||||
different one; noted with approval. Accepted; the scope-widening
|
||||
rescan follow-up (210 ms of re-parsing open buffers) is the next
|
||||
round.
|
||||
|
||||
**2026-08-27 — lead, indexed-navigation performance round (external dev:
|
||||
codex).** Reviewed the full diff line-by-line and ran all three gates
|
||||
independently (fmt clean, clippy silent, 1155 server tests + workspace
|
||||
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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
# perf — measured numbers for the paths a keystroke and a hover run through
|
||||
|
||||
## Goal
|
||||
|
||||
Give the server's hot paths — `analyze`, opening a buffer, answering a hover,
|
||||
reindexing one saved file, and (since round 2) one flush stage by stage and
|
||||
one keystroke's round trip over the wire — a number that is *measured* rather
|
||||
than guessed, taken the same way every time, so a later round can say whether
|
||||
it made something faster or only different. This is the record; the
|
||||
measurements themselves are `#[ignore]`d tests in
|
||||
`crates/lucisv_server/src/perf.rs` and in
|
||||
`crates/lucisv_server/tests/e2e.rs`, run on demand and asserting nothing about
|
||||
duration. Nothing here is a performance *budget*: a test that fails when a
|
||||
machine is busy is a test that gets deleted.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **No benchmark dependency.** `criterion` and friends are out: `CLAUDE.md`
|
||||
requires a written justification for any new dependency, and the workspace
|
||||
has six direct ones (`rayon`, `lsp-server`, `lsp-types`, `serde`,
|
||||
`serde_json`, plus their pins). `std::time::Instant` + `eprintln!` is the
|
||||
shape this repo already uses for perf notes (`hover.rs`'s QA measurement,
|
||||
`includes.rs`, `inlay.rs`, `file_ops.rs`) and it is what is used here.
|
||||
- **`--test-threads=1` or the numbers are noise.** The harness otherwise runs
|
||||
these concurrently with each other and with 1 200 other tests. The first run
|
||||
of these measurements was taken without it and reported a cross-file hover
|
||||
as *cheaper* than the single file read it performs; that is how obvious the
|
||||
contamination is.
|
||||
- **Means, not single runs.** Each measurement is the mean of 10–1 000 runs
|
||||
(`perf::mean`), with `std::hint::black_box` around the inputs and results so
|
||||
a release build cannot optimize the work away.
|
||||
- **Generated input, not the corpus.** `perf::generated_module` builds an
|
||||
ANSI-headed module of repeated four-line blocks (a wire, an assign, a
|
||||
register, an update) at 1 000 and 10 000 lines. It is uniform, which real
|
||||
RTL is not — the numbers are a scale, not a prediction for any given file.
|
||||
The corpus-scale numbers this repo already has live where they were taken
|
||||
(`docs/features/incremental-index`, `index-persistence`, `references-nav`).
|
||||
|
||||
## Reproducing
|
||||
|
||||
```text
|
||||
cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
Each test's own doc comment names the narrower filter for running it alone.
|
||||
The over-the-wire measurement lives with the other end-to-end tests, because
|
||||
it spawns the shipped binary, so it has its own command:
|
||||
|
||||
```text
|
||||
cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
The one older measurement quoted below has a third:
|
||||
|
||||
```text
|
||||
cargo test --release -p lucisv_server large_closed -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
## The machine
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| CPU | Apple M1 Max (`uname -m` = `arm64`) |
|
||||
| OS | macOS 27.0 (build 26A5421a) |
|
||||
| build | `--release`, workspace at 0.12.1 + rounds 1 and 2 uncommitted |
|
||||
| date | 2026-08-28 (every figure below re-measured this day, round 2) |
|
||||
|
||||
## Numbers
|
||||
|
||||
All figures are the mean of the runs named above. "1k" and "10k" are the
|
||||
generated module's line counts (29 KB / 501 symbols and 309 KB / 5 001
|
||||
symbols respectively).
|
||||
|
||||
| what | 1k lines | 10k lines |
|
||||
|---|---|---|
|
||||
| `vlog_semantic::analyze` (tree already parsed) | 252 µs | 3.76 ms |
|
||||
| `Document::new` — lex + parse + analyze + `resolve_external` | 2.54 ms | 31.1 ms |
|
||||
| `hover`, target declared in the same open buffer | 2.68 µs | 1.10 µs |
|
||||
| `hover`, target in a **closed** file (disk path) | 38.1 µs | 159 µs |
|
||||
| — of which one read + one `LineIndex` of that file | 27.4 µs | 140 µs |
|
||||
| `WorkspaceIndex::update_file`, 20 files of this size | 2.76 ms | 32.1 ms |
|
||||
| — of which the clone the measurement needs to repeat itself | 60 µs | 567 µs |
|
||||
| one name looked up among the file's symbols: **linear scan** | 767 ns | 8.14 µs |
|
||||
| one name looked up among the file's symbols: **name-sorted lookup** | 93 ns | 131 ns |
|
||||
| one token found at the cursor: **sweep** | 6.58 µs | 77.5 µs |
|
||||
| one token found at the cursor: **binary search** | 15 ns | 20 ns |
|
||||
| the balanced-paren window `completion.rs` needs: **sweep** | 8.63 µs | 130 µs |
|
||||
| the balanced-paren window `completion.rs` needs: **binary search** | 27 ns | 36 ns |
|
||||
|
||||
Every figure above comes from one run of the command in *Reproducing*, on the
|
||||
machine above. A local hover is a handful of pointer chases and comes out
|
||||
under 3 µs at both sizes; the 1k figure being the larger of the two is that
|
||||
measurement's noise floor, not a result.
|
||||
|
||||
Three things stand out:
|
||||
|
||||
- **A hover into a closed file is a file read.** 27 µs of the 1k hover's
|
||||
38 µs, and 140 µs of the 10k hover's 159 µs, is reading that file and
|
||||
building a `LineIndex` over it. Everything else — resolution, guards,
|
||||
rendering — is single-digit microseconds.
|
||||
- **`Document::new` is where a keystroke's cost lives**, and it is dominated
|
||||
by lexing and parsing, not by `analyze` (31 ms against 3.8 ms at 10k
|
||||
lines). The stage-by-stage table below says exactly how much.
|
||||
- **A sweep of the token vector costs about what the parse of one line
|
||||
costs**, and there are several per keystroke. That is round 2's Phase 2.
|
||||
|
||||
### One flush, stage by stage
|
||||
|
||||
`Document::new` runs the first seven of these in order; the eighth is not
|
||||
inside it at all — `diagnostics::all` is what a *publish* runs, on every
|
||||
flush, and round 1's table did not account for it.
|
||||
|
||||
`parse_tolerant` consumes its token vector, so each run of the parse needs a
|
||||
fresh clone. The clone has its own row and the parse row still contains it;
|
||||
subtracting one from the other is the honest reading, and it is what
|
||||
`Document::new` really pays.
|
||||
|
||||
| stage of one flush | 1k lines (9 461 tokens) | 10k lines (94 961 tokens) |
|
||||
|---|---|---|
|
||||
| `tokenize` | 1.14 ms | 12.5 ms |
|
||||
| `tokens.clone()` (the copy `Document` keeps) | 230 µs | 2.40 ms |
|
||||
| `parse_tolerant`, clone included | 1.16 ms | 14.3 ms |
|
||||
| — the parse alone, by subtraction | 0.93 ms | 11.9 ms |
|
||||
| `collect_defines` | 7.09 µs | 121 µs |
|
||||
| `analyze` | 278 µs | 5.55 ms |
|
||||
| `resolve_external` | 943 ns | 49.3 µs |
|
||||
| `LineIndex::new` | 10.5 µs | 115 µs |
|
||||
| `diagnostics::all` (parse errors + closers + lint) | 104 µs | 1.40 ms |
|
||||
|
||||
Read this table as *shares of a flush*, not as the last word on any one
|
||||
stage: it runs eight measurements back to back on one heap, and its `analyze`
|
||||
row came out 5.55 ms in the same run where the dedicated `analyze` test —
|
||||
which measures nothing else — came out 3.76 ms. The dedicated figure is the
|
||||
cleaner one. What the table is for is the proportion, and the proportion is
|
||||
unambiguous:
|
||||
|
||||
- **Lexing and parsing are 79 % of a flush** at 10 000 lines (12.5 + 11.9 of
|
||||
30.9 ms, taking the dedicated `analyze` figure for the rest). Everything
|
||||
else together is a fifth.
|
||||
- **`tokens.clone()` is 7.7 %**, and it is load-bearing rather than waste:
|
||||
`parse_tolerant` takes ownership of its tokens and *steals the comments out
|
||||
of them*, so the copy `Document` keeps is the only one that still has its
|
||||
trivia. It is also already the cheap option — before the one-lex change
|
||||
this was a second `tokenize`, which is 12.5 ms.
|
||||
- **`resolve_external` is 49 µs, one part in six hundred.** Making the
|
||||
workspace overlay skippable was on this round's list of candidates; the
|
||||
measurement says there is nothing there to save.
|
||||
- **The lint pass is 1.40 ms on top of the flush**, about 4 %. It walks the
|
||||
tree once per rule.
|
||||
|
||||
### Over the wire — what a keystroke actually costs a user
|
||||
|
||||
Round 1 listed this as its own open TODO, because it cannot be taken from
|
||||
inside the crate: the number includes two pipes, a JSON encoder and decoder,
|
||||
the change debounce's quiet-period timer and a whole flush. It is measured by
|
||||
spawning the shipped binary and speaking framed JSON-RPC at it
|
||||
(`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`, command above).
|
||||
|
||||
| `didChange` → `publishDiagnostics` | 1k lines | 10k lines |
|
||||
|---|---|---|
|
||||
| one keystroke, nothing following it | 164 ms | 202 ms |
|
||||
| a burst of ten keystrokes, no pause | 165 ms | 207 ms |
|
||||
| — publishes that burst produced | **1** | **1** |
|
||||
| one keystroke **a request follows** (mean of 10) | 4.35 ms | 37.6 ms |
|
||||
|
||||
The three rows say three different things.
|
||||
|
||||
- **The debounce is the felt latency when a client asks for nothing.**
|
||||
150 ms of the 164 ms is `CHANGE_DEBOUNCE`'s quiet period; the work is the
|
||||
rest. At 10 000 lines the same 150 ms sits on top of a 31 ms flush. This
|
||||
is the one row where round 1 made something *slower*: before the debounce
|
||||
a lone keystroke published in about one flush, and it now waits out the
|
||||
timer first. It is the bargain debouncing is, and the last row is why it
|
||||
is worth taking.
|
||||
- **A real editor never waits for that timer.** VS Code asks for semantic
|
||||
tokens, inlay hints and highlights the moment a buffer changes, and a
|
||||
request flushes the dirty buffer before it is answered. That is the last
|
||||
row, and it is the number a user actually feels: **4.35 ms at 1 000 lines,
|
||||
37.6 ms at 10 000**.
|
||||
- The first two rows are single round trips, not means, and each is bounded
|
||||
below by a 150 ms timer; treat their differences as noise. The last row is
|
||||
the mean of ten and is the one worth comparing across rounds.
|
||||
|
||||
## Before / after — round 1 (2026-08-28)
|
||||
|
||||
**A1 — didChange debounce.** Not measured directly *at the time*, and the
|
||||
arithmetic below is what round 1 recorded: every `didChange` used to run one
|
||||
`Document::new` plus lint and publish; a burst of *k* changes now runs one.
|
||||
At 10k lines that is 31 ms saved per keystroke after the first in a burst, at
|
||||
1k lines 2.6 ms. What the debounce cannot save is the first change in a burst
|
||||
and the last flush, so the floor is one `Document::new` per burst per buffer.
|
||||
|
||||
**Round 2 measured it.** A burst of ten keystrokes over the wire produces
|
||||
**one** `publishDiagnostics`, counted rather than reasoned about — the count
|
||||
comes from draining the session at `shutdown`, which every pending flush is
|
||||
guaranteed to have arrived before. The arithmetic above was right.
|
||||
|
||||
The burst is deliberately the **last** thing that measurement does, which is
|
||||
QA finding IL-1 closed: every `wait_for` in the test accepts *any* publish,
|
||||
so while the burst ran before the other rows, a second publish it had
|
||||
produced would have been absorbed by the next row's wait and never counted.
|
||||
With nothing between the burst and the drain, the count is the count.
|
||||
|
||||
**A2 — one disk read per hover.** Measured, two ways.
|
||||
|
||||
- The QA round that filed the finding measured a hover into a 31.7 MB closed
|
||||
file at **34 ms** (`docs/features/hover-declarations/README.md`, finding 4,
|
||||
2026-08-27, same machine, same test, release build). The same test after
|
||||
the `disk_view` memo: **16.3 ms**. That is the expected shape — two reads
|
||||
and two `LineIndex` builds became one — but the two numbers come from
|
||||
different runs on different days, so read it as "about half", not as
|
||||
2.08×.
|
||||
- The `perf::hovering_across_files_into_a_closed_file` measurement takes the
|
||||
after-number and the cost of one read + `LineIndex` side by side, in the
|
||||
same run: 142 µs of a 160 µs hover at 10k lines. Removing a second read of
|
||||
that same file is therefore removing roughly the whole remaining cost of
|
||||
the request, which is the before/after in the form that does not depend on
|
||||
an old number.
|
||||
|
||||
**A3 — name-keyed symbol lookup.** Measured directly, on the lookup alone:
|
||||
8.41 µs → 133 ns at 10k lines (5 001 symbols), 763 ns → 106 ns at 1k. The
|
||||
lookup is only part of what was saved: in `hover::live_symbol` every symbol
|
||||
the scan used to reach was also an `indexed_def_for_symbol` call — two index
|
||||
lookups apiece — which the name-sorted lookup never makes. That larger saving
|
||||
is **not measured here**; the 8.41 µs → 133 ns figure is a floor on it, not
|
||||
the whole of it.
|
||||
|
||||
**B — port detail spans, and comment attachment.** Not measured. The work
|
||||
added is a second `fenced_sections` call over lines already in memory, and
|
||||
two integers per declaration in the index and its facts records. No
|
||||
measurement was taken and none is claimed.
|
||||
|
||||
## Before / after — round 2 (2026-08-28)
|
||||
|
||||
**C1 — six token lookups stopped sweeping the buffer.** Measured directly,
|
||||
both halves in the same run against the same token stream
|
||||
(`perf::finding_one_token_against_sweeping_the_stream`), with the cursor
|
||||
three quarters of the way down the file — a sweep costs the distance from
|
||||
token zero, so measuring at either end would flatter it.
|
||||
|
||||
| | 1k lines | 10k lines |
|
||||
|---|---|---|
|
||||
| the token at the cursor: sweep → binary search | 6.58 µs → 15 ns | 77.5 µs → 20 ns |
|
||||
| `balanced`'s window: sweep → binary search | 8.63 µs → 27 ns | 130 µs → 36 ns |
|
||||
|
||||
Six call sites across `selection.rs`, `on_type.rs`, `completion.rs` and
|
||||
`inline.rs`; which ones, what each of them wanted, and the per-site argument
|
||||
that the search returns exactly what the sweep returned are in
|
||||
`docs/features/interactive-latency/README.md`. Every one is pinned by a test
|
||||
that walks **every byte** of a buffer full of touching tokens and compares
|
||||
the two. None of them changed an answer, and the tests are what says so
|
||||
rather than the claim.
|
||||
|
||||
Three sweeps were left alone with the reason written down: `signature.rs`'s
|
||||
two paren-depth walks (a depth is a function of every bracket before the
|
||||
cursor), `pairs.rs::analyze` (not a position query at all), and
|
||||
`completion.rs`'s comment gate (comments are trivia attached to whichever
|
||||
token happens to be next, so no search of the stream answers "is this byte
|
||||
inside a comment"). That last one is the remaining per-keystroke
|
||||
whole-buffer walk on the completion path.
|
||||
|
||||
**C2 — the round trip, and nothing else changed.** No stage of a flush was
|
||||
touched this round, so the flush table above is a baseline rather than an
|
||||
after. The reasons each candidate was refused, with its number, are in the
|
||||
next section.
|
||||
|
||||
## What it would take to go faster
|
||||
|
||||
Ranked by what the measurements above say is there, with what each would
|
||||
cost. None of these were attempted; each is a future round.
|
||||
|
||||
1. **Incremental lexing and parsing — 24.5 ms of a 31 ms flush at 10 000
|
||||
lines (79 %).** This is the only large lever left. It is also the one
|
||||
change that runs straight into `CLAUDE.md`'s hard invariants 1 and 2: the
|
||||
parser is what the "never corrupt code" and idempotency guarantees rest
|
||||
on, and an incremental parser that is right on 99 % of edits is worse than
|
||||
none. The change debounce already removed most of the *repetition* per
|
||||
keystroke, which is why this was not attempted here. The number that would
|
||||
justify it: **37.6 ms**, the felt latency of one keystroke in a
|
||||
10 000-line buffer, of which roughly 30 ms is lex + parse.
|
||||
2. **A cheaply-clonable `Token` — 2.40 ms, 7.7 % of a flush.**
|
||||
`Document.tokens` must be a separate copy because `parse_tolerant` takes
|
||||
ownership and steals `leading`/`trailing` out of the tokens it parses; the
|
||||
copy is 94 961 `String` allocations. Interning the text, or an `Rc<str>`,
|
||||
would remove most of it — but `Token` is `vlog_parser`'s public type and
|
||||
the formatter reads it everywhere, so this is a cross-crate change for
|
||||
under 8 %.
|
||||
3. **One tree walk for the whole lint pass — 1.40 ms, about 4 % on top of a
|
||||
flush.** `vlog_linter::lint` is `for rule in enabled { rule.check(ctx) }`,
|
||||
one walk per rule, and the same engine serves `lucisv check`. Fusing them
|
||||
is a `vlog_linter` refactor, and the editor and CI must not disagree about
|
||||
what a violation is.
|
||||
4. **`completion.rs`'s comment gate**, the last whole-buffer walk on a
|
||||
per-keystroke request path. Not measured on its own; it is one pass over
|
||||
the token vector plus its trivia, so the sweep figures above (77.5 µs at
|
||||
10 000 lines) are the right order of magnitude for it. Doing it properly
|
||||
means giving the lexer a way to answer "which comment covers this byte",
|
||||
which is a `vlog_parser` question and not a `completion.rs` one.
|
||||
5. **`CHANGE_DEBOUNCE` itself** is not a code problem: 150 ms of a lone
|
||||
keystroke's 164 ms round trip is the timer. It only bites clients that ask
|
||||
for nothing after a change, and it was set deliberately. Now that it is
|
||||
measured, a future round has the number to argue about.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/lucisv_server/src/perf.rs` — eight `#[ignore]`d measurements,
|
||||
std only, each with the command to run it.
|
||||
- [x] `analyze`, `Document::new`, hover (local + closed cross-file),
|
||||
`WorkspaceIndex::update_file`, at 1k and 10k lines.
|
||||
- [x] Before/after where it was cheap: A2 (two ways), A3 and C1.
|
||||
- [x] Machine, command and date recorded above.
|
||||
- [x] **Round 1's first open TODO, resolved (round 2, 2026-08-28):**
|
||||
end-to-end request latency over the wire, measured against the shipped
|
||||
binary — a single `didChange`, a burst of ten (with the publish count
|
||||
that turns A1's arithmetic into a measurement), and the
|
||||
change-then-request shape a real editor produces.
|
||||
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`.
|
||||
- [x] **Added in round 2:** one flush stage by stage, including the
|
||||
`diagnostics::all` pass that runs on every publish and that round 1's
|
||||
table did not account for.
|
||||
`perf::breaking_down_one_flushed_keystroke`.
|
||||
- [ ] **Round 1's second open TODO, restated and still open:** memory.
|
||||
Nothing in the repo measures resident size. Round 2 added no data
|
||||
structure — two free functions and no state — so the figure it would
|
||||
report has not moved, and round 1's name index is still four bytes per
|
||||
symbol. Worth doing before anything interns tokens, which is item 2 of
|
||||
*What it would take to go faster* and is a memory trade as much as a
|
||||
time one.
|
||||
- [ ] Not measured: the per-request handlers themselves (hover aside).
|
||||
Completion, signature help and semantic tokens each have a
|
||||
whole-buffer pass somewhere; only their token lookups were measured
|
||||
this round, not the requests end to end.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev.** Wrote `perf.rs` and took the numbers above (part A4 of
|
||||
the LSP performance round). Chose one module of six tests over a test per
|
||||
crate so that a single command produces the whole table. The generated-module
|
||||
generator lives beside the tests rather than in a shared helper — it has one
|
||||
user.
|
||||
|
||||
Renamed `hover.rs`'s QA measurement
|
||||
`hovering_into_a_large_closed_file_reads_it_twice` →
|
||||
`..._reads_it_once`, since the doubled read it was named for is what A2
|
||||
removed. The QA log in `docs/features/hover-declarations/README.md` still
|
||||
names the old spelling; that section belongs to QA and was left alone.
|
||||
|
||||
**2026-08-28 — dev (QA fixes).** No number above moved, and none was
|
||||
re-measured, because nothing on a measured path changed shape:
|
||||
|
||||
- The hover fixes (PDS-1, PDS-2, PDS-4) are all inside `attached_lines`,
|
||||
which part **B** already records as unmeasured. The added work is a
|
||||
`strip_suffix` per composed line and a below-comment walk that now also
|
||||
runs when a comment sits above — a handful of `line_range` lookups against
|
||||
the 142 µs *file read* that dominates the "hover closed" figure.
|
||||
- CD-1 only *removes* work (a closing buffer's `Document::new` and publish),
|
||||
and the debounce's own A1 numbers are arithmetic over `Document::new`,
|
||||
which is untouched.
|
||||
- PDS-3 widens one `bind_port_decl` branch from ports to task/function
|
||||
arguments: one hash lookup per declarator of a body port declaration
|
||||
inside a task or function. `perf.rs`'s generated modules contain no
|
||||
tasks, so the `analyze` / `Document::new` / `update_file` figures cannot
|
||||
have moved at all.
|
||||
|
||||
**2026-08-28 — dev (round 2).** Added
|
||||
`perf::breaking_down_one_flushed_keystroke`,
|
||||
`perf::finding_one_token_against_sweeping_the_stream` and
|
||||
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`, and **re-measured every
|
||||
figure in this document** on the same machine from the commands written
|
||||
beside them — the tables above are one run of each, not a mix of runs across
|
||||
days. The old figures are gone rather than kept alongside; every pair was
|
||||
within the noise this document already budgets for, and carrying two columns
|
||||
of the same measurement would invite reading a difference into scheduling.
|
||||
Round 1's figures are not lost — the QA log below quotes all of them in its
|
||||
own table, dated, and that section belongs to QA and was left alone.
|
||||
|
||||
The round's changes are in `docs/features/interactive-latency/README.md`.
|
||||
Only C1 touched shipped code, and it touched no stage of a flush, so the
|
||||
flush table is a baseline for the next round rather than an after.
|
||||
|
||||
Two things are recorded here that a future round should not have to
|
||||
rediscover. First, the e2e measurement reuses `e2e.rs`'s existing `Live`
|
||||
session helper; the only shared code that changed is that `Live::finish` now
|
||||
returns the publish count it saw on the way out, which is what makes the
|
||||
debounce's coalescing countable. Second, `perf::generated_module` now has a
|
||||
copy in `tests/e2e.rs` — a binary crate's modules are not reachable from an
|
||||
integration test — and the two must stay the same shape or the in-crate table
|
||||
and the over-the-wire table stop being readable against one another.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** No findings — every number reproduces within reason.
|
||||
|
||||
- **Machine match confirmed.** `sysctl -n machdep.cpu.brand_string` →
|
||||
`Apple M1 Max`; `sw_vers` → macOS 27.0, build `26A5421a` — exactly the
|
||||
machine named in the README's own table, on the same checkout.
|
||||
- **Re-ran the exact reproduce command**, `cargo test --release -p
|
||||
lucisv_server perf:: -- --ignored --nocapture --test-threads=1`, and
|
||||
compared every figure against the table:
|
||||
|
||||
| what | table | re-measured |
|
||||
|---|---|---|
|
||||
| `analyze`, 1k / 10k | 274 µs / 3.79 ms | 287.6 µs / 3.806 ms |
|
||||
| `Document::new`, 1k / 10k | 2.60 ms / 31.1 ms | 2.600 ms / 31.72 ms |
|
||||
| hover local, 1k / 10k | 1.79 µs / 0.97 µs | 3.35 µs / 1.01 µs |
|
||||
| hover closed, 1k / 10k | 35.2 µs / 160 µs | 34.4 µs / 172 µs |
|
||||
| — one read of it, 1k / 10k | 26.9 µs / 142 µs | 26.7 µs / 147.6 µs |
|
||||
| `update_file`, 1k / 10k | 2.73 ms / 31.4 ms | 2.695 ms / 32.45 ms |
|
||||
| — the clone, 1k / 10k | 60 µs / 528 µs | 60.7 µs / 516.7 µs |
|
||||
| linear scan, 1k / 10k | 763 ns / 8.41 µs | 793 ns / 8.21 µs |
|
||||
| name-sorted, 1k / 10k | 106 ns / 133 ns | 93 ns / 134 ns |
|
||||
|
||||
Every pair is within the noise the README itself budgets for — including
|
||||
the hover-local 1k figure, which the README already calls out by name as
|
||||
"that measurement's noise floor, not a result" (mine is higher still,
|
||||
3.35 µs vs. 1.79 µs, and still a handful of pointer chases either way).
|
||||
Nothing here is scaled, remembered, or overclaimed.
|
||||
- **Re-ran the older, separately-commanded measurement** too: `cargo test
|
||||
--release -p lucisv_server large_closed -- --ignored --nocapture
|
||||
--test-threads=1` → **17.0 ms** against the documented "34 ms → 16.3 ms."
|
||||
Matches the README's own honesty caveat exactly ("read it as 'about half',
|
||||
not as 2.08×" — different runs, different days).
|
||||
- **`perf.rs` measures what its name says** — spot-checked
|
||||
`hovering_across_files_into_a_closed_file` and
|
||||
`looking_up_one_name_against_scanning_every_symbol` against `hover.rs`'s
|
||||
and `lib.rs`'s actual entry points (`hover::hover`, `Semantics::
|
||||
symbols_named` vs. a hand-rolled linear scan over `symbols()`) — both call
|
||||
the real, shipped functions, not a stand-in.
|
||||
- **A1's "before/after" is correctly labeled "not measured directly"** — it
|
||||
is arithmetic over the already-verified `Document::new` figures, and the
|
||||
README says so; no separate claim to check.
|
||||
- **B's "not measured, none is claimed"** — confirmed true: no perf test
|
||||
exercises `fenced_sections`/`attached_lines`, and the README does not say
|
||||
one does.
|
||||
|
||||
**2026-08-28 — QA (round 2).** Findings and the full gate output are recorded
|
||||
in `docs/features/interactive-latency/README.md`'s QA log, which is this
|
||||
round's owning feature; summarized here since this document is where the
|
||||
numbers live.
|
||||
|
||||
- Every figure in *Over the wire* and *One flush, stage by stage* reproduced
|
||||
within the noise this document budgets for, from a fresh
|
||||
`cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1`
|
||||
and `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
|
||||
on this session's run of this machine.
|
||||
- **C1's identity claim** (six sweeps → binary searches, none changed an
|
||||
answer) held under a hand-traced check of all six call sites, including
|
||||
the empty-token and large-file-fast-path edges, and under an independent
|
||||
check of the `state.rs` monotonicity precondition against `vlog_parser`'s
|
||||
own much wider corpus/fuzz tests (`tests/spans.rs`, `tests/error_recovery.rs`)
|
||||
— no gap found.
|
||||
- **One methodology finding, IL-1 (medium)**, on the e2e round trip's burst
|
||||
measurement: the "1 publish(es)" figure for a burst of ten is not the
|
||||
order-independent count its own doc comment claims — a stray extra publish
|
||||
in the window between the burst and `Live::finish`'s drain could be
|
||||
silently absorbed by an unrelated `wait_for` later in the same test and
|
||||
never counted. Full detail and repro in
|
||||
`docs/features/interactive-latency/README.md`. Not a claim about a real
|
||||
double-publish (the debounce is understood to coalesce to one), and not
|
||||
fixed — closing it is a test-restructuring decision for the dev.
|
||||
- The two `generated_module` copies (this crate's `perf.rs` and `e2e.rs`'s)
|
||||
differ by one trivia line, not the byte-identical shape their own comment
|
||||
implies; verified harmless (comments are not tokens, and the tables stay
|
||||
readable against each other). Detail in the same QA log.
|
||||
- **Verdict: SHIP WITH FIXES noted, none applied.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted as the round's record.
|
||||
|
||||
The discipline here is what makes the numbers usable later: one command, one
|
||||
machine block, means rather than single runs, `--test-threads=1` justified by
|
||||
a contaminated first attempt that reported a cross-file hover as cheaper than
|
||||
the file read it performs. Refusing criterion was the right call against
|
||||
`CLAUDE.md`'s dependency rule, and the `#[ignore]`d-measurement pattern was
|
||||
already this repo's idiom rather than an invention for this round.
|
||||
|
||||
I re-ran every measurement independently and the figures reproduce. Two
|
||||
claims were softened at review rather than left as written: the wire-latency
|
||||
rows are re-measured after the IL-1 methodology fix (164/202 ms lone,
|
||||
4.35/37.6 ms with a request following), and the lone-keystroke row now says
|
||||
plainly that round 1 made that case *slower* — 150 ms of it is the debounce
|
||||
timer, and a client that asks for nothing after a change waits it out. A perf
|
||||
document that only records wins is not a perf document.
|
||||
|
||||
What I want the next round to inherit: the felt-latency number is **37.6 ms**
|
||||
for one keystroke in a 10 000-line buffer, roughly 30 ms of it lex and parse.
|
||||
That is the figure any incremental-parsing proposal has to be argued against,
|
||||
and it now exists.
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
# 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.13.1 — 2026-08-28
|
||||
|
||||
The F12-latency release.
|
||||
|
||||
- **Find References with a huge file open is ~30× faster** (3.2 ms →
|
||||
0.11 ms on a 70 000-reference buffer), and in-file references and
|
||||
occurrence highlighting on heavily used signals are ~40 % faster.
|
||||
- **Jumping into a new folder is ~10× faster.** The index rescan that a
|
||||
scope-widening jump triggers now reuses what your open buffers already
|
||||
analyzed instead of re-parsing them: ~228 ms → ~23 ms with a 1.4 MB
|
||||
file open.
|
||||
- **Pathologically nested files can no longer crash the tools.** ~500
|
||||
nested `begin`/`end` (or `case`, `fork`, generate…) blocks now produce
|
||||
an ordinary "nesting too deep" diagnostic on every platform, including
|
||||
Windows, instead of risking an abort.
|
||||
|
||||
## 0.13.0 — 2026-08-28
|
||||
|
||||
- **Typing no longer reanalyzes on every keystroke.** The buffer's analysis is
|
||||
deferred to the first moment anything needs it, so a burst of typing costs
|
||||
one reanalysis instead of one per key. Half-typed lines stop flashing
|
||||
squiggles that vanish a keystroke later. In a 10 000-line file a keystroke
|
||||
now round-trips in 37.6 ms.
|
||||
- **Old-style ports hover properly.** A port named in the module header and
|
||||
completed in the body (`input signed [31:0] data_in;`) now shows both
|
||||
places on one card — the header line and the declaration carrying its
|
||||
direction, type and width — with the comments that document each of them.
|
||||
Go-to-definition offers both, body declaration first. Works across files,
|
||||
and for old-style task and function arguments too.
|
||||
- **Faster hover and cursor answers.** Hovering into a closed file reads it
|
||||
once instead of twice, and expand-selection, on-type formatting, completion
|
||||
and inline templates find the token at your cursor by binary search rather
|
||||
than by scanning the file. No answer changed.
|
||||
- The index cache's format changed, so the first session after upgrading
|
||||
rebuilds it.
|
||||
|
||||
## 0.12.1 — 2026-08-27
|
||||
|
||||
- **Hover shows the declaration itself.** Hovering a name declared in another
|
||||
file — a port at an instantiation, a module instance, a package parameter
|
||||
or typedef — now shows its declaration's source line (direction, type,
|
||||
width), syntax-highlighted, under the "declared in" location. Unsaved edits
|
||||
in the declaring file are reflected live; very long declarations are
|
||||
trimmed with a note.
|
||||
|
||||
## 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`.
|
||||
+132
-4
@@ -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.13.1**. 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 |
|
||||
|
||||

|
||||
|
||||
## 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,65 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.13.1 highlights
|
||||
|
||||
Version 0.13.1 is the F12-latency release:
|
||||
|
||||
- Find References with a big file open answers in ~0.1 ms where it took
|
||||
milliseconds, and jumping into a not-yet-indexed folder costs ~23 ms
|
||||
where it took ~228 ms — the rescan reuses what open buffers already
|
||||
analyzed.
|
||||
- Deeply nested files produce a "nesting too deep" diagnostic instead of
|
||||
ever crashing the server or CLI, on every platform.
|
||||
|
||||
## Release 0.13.0 highlights
|
||||
|
||||
Version 0.13.0 is the responsiveness release. Typing no longer reanalyzes the
|
||||
buffer on every keystroke — the analysis is deferred to the first moment
|
||||
anything needs it, so a burst of typing costs one reanalysis instead of one
|
||||
per key, and half-typed lines stop flashing squiggles that vanish a moment
|
||||
later. Cursor-position answers — expand selection, on-type formatting,
|
||||
completion, inline templates — binary-search for the token under your cursor
|
||||
instead of scanning the file.
|
||||
|
||||
Hover also learned old-style ports: a port named in the module header and
|
||||
completed in the body (`input signed [31:0] data_in;`) shows both places on
|
||||
one card, with the comments that document each of them.
|
||||
|
||||
## Release 0.12.1 highlights
|
||||
|
||||
Version 0.12.1 makes hover answer the question directly: a cross-file name
|
||||
shows its declaration's own source line — `input logic [7:0] addr` for a
|
||||
port, the header line for a module — not just the file and line it lives in.
|
||||
|
||||
## 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:
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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.13.1",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,633 @@
|
||||
# topo.md — the dependency topology of lucisv
|
||||
|
||||
**Purpose.** This document is the map an agent reads before touching anything:
|
||||
which modules depend on which, which features consume which, and where the
|
||||
two graphs meet. It exists to make parallel multi-agent development safe —
|
||||
every edge below is an interface somebody can break, and every *absent* edge
|
||||
is a place two agents can work at the same time without talking.
|
||||
|
||||
Sources of truth this document is derived from (and defers to on conflict):
|
||||
each crate's `Cargo.toml`, each feature's `docs/features/<name>/README.md`
|
||||
(the **Handshakes** section in particular), `README.md` and `CLAUDE.md`.
|
||||
Drafted 2026-08-27 from the workspace at v0.10.2 (93 feature READMEs);
|
||||
updated 2026-08-28 for hover-declarations, change-debounce,
|
||||
port-detail-spans and interactive-latency (97 feature READMEs).
|
||||
|
||||
**Edge notation, used in all three sections:**
|
||||
|
||||
| notation | meaning |
|
||||
|---|---|
|
||||
| `A ──▶ B` | **A depends solely on B.** A consumes B's published interface; B was not changed for A and does not know A exists. Breaking B's interface breaks A; breaking A costs B nothing. |
|
||||
| `A ◀──▶ B` | **Handshake.** A negotiated, two-sided contract: B changed something *for* A (or both sides pin one wire shape / file format / naming convention), and the contract is written down in one or both READMEs. Either side moving unilaterally breaks the other. |
|
||||
| `A ─▶ B` | **Not a dependency** — a one-way note whose `kind` column says what it is: `sequencing` (corpus files handed from one bucket to the next), `standing promise` (A imposes a rule on B and its successors), `open request`, or `depends (consumed by)` — the last reads **B depends on A**. |
|
||||
| *(absent)* | The two are independent. Independent pairs are **not listed** — their absence is the claim. |
|
||||
|
||||
A handshake that was **requested but not yet delivered** is an *open
|
||||
handshake*; those are collected in §2.9 because they are exactly the
|
||||
coordination points parallel agents must not both grab.
|
||||
|
||||
---
|
||||
|
||||
## 1. Module dependency graph
|
||||
|
||||
"Module" here means: the eight workspace crates, the two editor trees, and
|
||||
the script layer (`tools/`, `scripts/`, CI). Intra-crate structure that
|
||||
matters for parallel work is in §1.3.
|
||||
|
||||
### 1.1 Crate-level graph
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph foundations [foundation crates — depend on nothing]
|
||||
P[vlog_parser]
|
||||
C[lucisv_core]
|
||||
end
|
||||
F[vlog_formatter] --> P
|
||||
S[vlog_semantic] --> P
|
||||
L[vlog_linter] --> P
|
||||
L --> S
|
||||
R[vlog_refactor] --> P
|
||||
R --> S
|
||||
CLI[lucisv (CLI)] --> C
|
||||
CLI --> P
|
||||
CLI --> F
|
||||
CLI --> L
|
||||
SRV[lucisv_server] --> C
|
||||
SRV --> P
|
||||
SRV --> S
|
||||
SRV --> R
|
||||
SRV --> F
|
||||
SRV --> L
|
||||
L -.dev-dep (fix harness).-> F
|
||||
VSC[editors/vscode] -.spawn contract.-> SRV
|
||||
VSC -.KEYWORDS grammar lock.-> P
|
||||
NVIM[editors/nvim (docs)] -.spawn contract.-> SRV
|
||||
TOOLS[tools/ release scripts] -.builds/packages.-> CLI
|
||||
TOOLS -.builds/packages.-> SRV
|
||||
TOOLS -.builds/packages.-> VSC
|
||||
CI[Gitea Actions] --> TOOLS
|
||||
CORPUS[scripts/ + tools/corpus_*] -.exit codes, msg prefixes.-> CLI
|
||||
```
|
||||
|
||||
*(The diagram shows direction only; §1.2 is authoritative on `depends` vs
|
||||
`handshake` for each edge.)*
|
||||
|
||||
External dependencies (all exactly pinned in the workspace `Cargo.toml`):
|
||||
`rayon` (CLI only, sanctioned by TODO §3), `lsp-server` + `lsp-types` +
|
||||
`serde`/`serde_json` (server only, sanctioned by TODO §6). Those are the only
|
||||
**direct** external dependencies; everything the workspace itself writes is
|
||||
std (they pull in ~20 transitive crates — see `Cargo.lock` — which is what an
|
||||
audit counts, not what an agent can call). `lsp-types` carries
|
||||
`features = ["proposed"]` for LSP 3.18 `inlineCompletion` (inline-templates).
|
||||
|
||||
### 1.2 Crate edges, documented
|
||||
|
||||
Every edge is directional; "consumes" lists the load-bearing surface, i.e.
|
||||
what a change on the pointed-to side must not silently break.
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `vlog_formatter ──▶ vlog_parser` | depends | `parse(tokens, source)` / `parse_source`, the whole AST, `tokenize` (re-used by `verify.rs` to re-lex both sides of the safety net), trivia attachment (`Meta::{leading,trailing,before_sep,attrs}` — comments are never dropped), `RawText.col` (the dedent column for verbatim re-indent), spans. The formatter is the AST's primary consumer: **every new `ItemKind`/`StmtKind`/`ExprKind` variant costs an arm in `format.rs`** (its matches are exhaustive). |
|
||||
| `vlog_semantic ──▶ vlog_parser` | depends | The AST read-only, `parse_source_tolerant`/`parse_tolerant` (never fails; `Error` nodes are opaque leaves), the **name-span contract** `src[name_span] == name` on every declaring node, `token::is_keyword`, `defines::collect_defines`/`DefineTable`, `TextRange`. `bind.rs`'s `ItemKind`/`ExprKind`/`DimKind` matches are exhaustive — new variants cost an arm here too. |
|
||||
| `vlog_linter ──▶ vlog_parser` | depends | `ParsedSource::parse` = `tokenize` + `parse_tolerant` (one-parse bundle), `LineIndex`, `TextRange`, AST shapes walked by `visit.rs` (which ends in `_ => {}`, so new variants usually cost nothing here), token facts for text rules (a macro use is one `Ident` token; a directive is one `Directive` token). |
|
||||
| `vlog_linter ──▶ vlog_semantic` | depends | `analyze`, `Semantics::{symbols, references, references_of}` for the three semantic rules (`unused-signal`, `undriven-net`, `multiply-driven`). Lazy: a run with no semantic rule enabled never calls `analyze`. Justified in `vlog_linter/Cargo.toml`; adds no external code (`vlog_semantic` is `vlog_parser` + std). |
|
||||
| `vlog_linter ──▶ vlog_formatter` **(dev-only)** | depends (tests) | The `.lint` fix harness asserts a lint fix never produces text `format_source` refuses. **The library dependency list is still `vlog_parser` + `vlog_semantic` + std** — `cargo tree -p vlog_linter -e normal` is the pinned check. Do not promote this to a normal dep; the fence filter deliberately lives in the front ends instead (see shared-fence-filter, §2.4). |
|
||||
| `vlog_refactor ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant` + diagnostics, `LineIndex`, `TextRange`, the port/instantiation/module AST shapes, `token::is_keyword` (new-name validity), `defines` via the index. Every edit span originates in a parsed node — no textual search-and-replace. |
|
||||
| `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). |
|
||||
| `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache). (`walk::is_excluded` is `pub` but currently has no consumer outside the crate.) |
|
||||
| `lucisv ──▶ vlog_formatter` | depends | `format_source` / `format_range` / `LineRanges` / `Config` / `FormatError`, and `fence::{protected_regions, is_protected}` (the `--fix` fence filter — the linter crate deliberately has no fence notion). |
|
||||
| `lucisv ──▶ vlog_linter` | depends | The public linter API for `lucisv check` — `lint` + `LintContext`/`ParsedSource`, `apply_fixes`, `select_rules` (the CLI does not call `run` itself). Relies on: rule names stable, linting never panics/writes, findings sorted by `(span.start, span.end, rule)`. |
|
||||
| `lucisv ──▶ vlog_parser` | depends | Thin: `LineIndex` / `TextRange` for lint report coordinates. (The CLI otherwise reaches the parser through the formatter and linter.) |
|
||||
| `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(8 MiB)` (recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. |
|
||||
| `lucisv_server ──▶ lucisv_core` | depends | Same config discovery and walk as the CLI (that sameness is the point — format-on-save must agree with `lucisv --check`), `filelist::read` (index scope rung 1, `+incdir+` for the include graph), `cache::content_hash` (re-used by the persistent index cache — one FNV-1a, not two). |
|
||||
| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the VS Code grammar is generated from). |
|
||||
| `lucisv_server ──▶ vlog_semantic` | depends | `analyze`/`Semantics` (every navigation answer), `WorkspaceIndex` (build/incremental update, units/members/defines, `instantiations_of`/`subclasses_of` edge tables, `FileFacts` codec for the persistent cache), `resolve_external` overlay, `index_order`/`IndexBuilder` (watched builds). |
|
||||
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Two negotiated additions, both 2026-08-28 and both additive: **`Symbol::detail_span` / `Def::detail_span`** (where a non-ANSI port's body declaration completes the header that names it — the server's hover card and `nav::definition` both read it, and they show/jump to it in the same order), and **`Semantics::symbols_named`** (name → declarations, built in `analyze`, in declaration order — the server replaced two scan-every-symbol loops with it and the *first-match tie-break must stay declaration order* or hover's choice between two live declarations of one name changes). `docs/features/port-detail-spans/README.md`. |
|
||||
| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `instantiation_plan`/`render_with`/`module_definition` (completion skeletons, signature help, inlay hints). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
|
||||
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
|
||||
| `editors/vscode ◀──▶ lucisv_server` | handshake | The **spawn contract**: binary named `lucisv-server`, no args, no env, LSP over stdio, `initialize` works with no roots (single-file mode). Wire shapes pinned on both sides: the custom `lucisv/scopePairs` result, the `lucisv.*` settings section (push and pull), `initializationOptions.storagePath`, the markdown fence tag `systemverilog` (server emits it, extension's grammar registers it), the `bin/` layouts of the platform `.vsix` packages. `smoke.js` drives the contract headlessly; `tests/e2e.rs` and `tests/grammar.rs` pin it server-side. |
|
||||
| `editors/vscode ◀──▶ vlog_parser` | handshake | The TextMate grammar's keyword alternation is **hand-maintained and test-locked to `vlog_parser::KEYWORDS`**: `crates/lucisv_server/tests/grammar.rs` fails, naming the missing/extra words, when they diverge (there is no generator script). Adding a keyword to `token.rs`'s `keywords!` macro is therefore also a hand edit to `editors/vscode/syntaxes/systemverilog.tmLanguage.json`. |
|
||||
| `editors/nvim ──▶ lucisv_server` | depends | Documentation-only module: config snippets consuming the same spawn contract and settings shape. No code. |
|
||||
| `tools/ ◀──▶ crates + editors/vscode` | handshake | `release.sh` parses `lucisv --version` (field 2), runs `smoke.js` against the built server, stages `dist/lucisv[-server]-<version>-<triple>` names, packages seven `.vsix` files and asserts their `bin/` layouts. `audit_artifacts.sh` and `prune_release_assets.sh` key on those exact names. The version number lives in exactly four files (two `Cargo` files, two `package*.json`) and nowhere in Rust source. |
|
||||
| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `release.sh --cross`, `audit_artifacts.sh`, `prune_release_assets.sh`, `release_notes.sh`, `publish_release.sh` — so every release step runs by hand too; its only inline logic is the tag-vs-`lucisv --version` check. `ci.yml` is plain `cargo fmt`/`clippy`/`test` plus `scripts/corpus_gate.sh` (which reaches `tools/corpus_fetch.sh` on a cache miss). Tag `vX.Y.Z` must equal the workspace version; release notes come from `CHANGELOG.md`'s `## <version> — <date>` headings via `release_notes.sh`. |
|
||||
| `scripts/score.sh + tools/corpus_check.sh ──▶ lucisv` | depends | The frozen 0/1/2 exit-code contract, plus a **textual** dependency on the message prefixes `parse error:` / `lex error:` / `verification failed:` (a standing fragile coupling — rewording those means telling corpus-check; see §2.9). |
|
||||
|
||||
**Deliberately absent crate edges** (independence you can rely on):
|
||||
|
||||
- `lucisv` (CLI) does **not** depend on `vlog_semantic` or `vlog_refactor` —
|
||||
the CLI formats and lints; semantic lints reach it only *through*
|
||||
`vlog_linter`, and refactoring is server-only today.
|
||||
- `vlog_refactor` does **not** depend on `vlog_formatter` — refactored output
|
||||
is edited source, not reformatted source (refactor README, by design).
|
||||
- Among `vlog_formatter`, `vlog_semantic`, `vlog_refactor`, `vlog_linter`
|
||||
there are exactly two build-time inter-crate edges — `vlog_linter →
|
||||
vlog_semantic` and `vlog_refactor → vlog_semantic` — plus `vlog_linter →
|
||||
vlog_formatter` as a **dev-dependency only**. All four depend on
|
||||
`vlog_parser`. `vlog_formatter` is the isolated one: nothing in this group
|
||||
depends on it at build time and it depends on none of them. Formatter work
|
||||
and semantic work are parallel-safe except where both touch
|
||||
`vlog_parser::ast`.
|
||||
- `lucisv_core` depends on nothing and nothing in it knows about Verilog —
|
||||
it is "which files, with what settings".
|
||||
- `vlog_parser` depends on nothing. It is also the **highest-contention
|
||||
module in the workspace**: six crates depend on it, five consume the AST
|
||||
(the CLI takes only `LineIndex`/`TextRange`), and two of those match it
|
||||
exhaustively — `vlog_formatter/src/format.rs` and `vlog_semantic/src/bind.rs`
|
||||
— with `vlog_parser`'s own `tests/spans.rs` as a third exhaustive walker.
|
||||
`vlog_linter`, `vlog_refactor` and `lucisv_server` walk it with catch-all
|
||||
arms. See §3.3.
|
||||
|
||||
### 1.3 Intra-crate structure (what matters for parallel work)
|
||||
|
||||
**`vlog_parser`** — `lexer.rs` → `token.rs` (tokens + trivia attachment);
|
||||
`parser.rs` (recursive descent, strict + tolerant entry points over one
|
||||
grammar, depth/chain budgets from recursion-limit) → `ast.rs`; `span.rs`
|
||||
(`TextRange`), `line_index.rs` (offset↔line:col), `defines.rs` (the
|
||||
`` `define`` table, reads the token stream, expands nothing). `tests/spans.rs`
|
||||
is an exhaustive AST walker: **every new node needs an arm there** and must
|
||||
keep the span-nesting invariant.
|
||||
|
||||
**`vlog_formatter`** — the pipeline is `format.rs` (per-node rules) →
|
||||
`doc.rs` (the Wadler IR) → `printer.rs` (width-aware printing);
|
||||
`verify.rs` (the runtime safety net: token equivalence + convergence —
|
||||
CLAUDE.md invariant #4 territory, see §3.3); `fence.rs` (format-off regions +
|
||||
`protected_regions`, consumed by both front ends); `range.rs` (`--lines`);
|
||||
`align.rs` (alignment inference). `format_source` = parse → format → verify;
|
||||
an error means emit nothing.
|
||||
|
||||
**`vlog_semantic`** — `bind.rs` (AST → scopes/symbols/references) →
|
||||
`model.rs`; `resolve.rs` (the lexical walk; misses become
|
||||
`ExternalCandidate`/`InheritedCandidate` carrying candidate paths);
|
||||
`scan.rs` (residual text-scanning for the one span the parser doesn't carry —
|
||||
`DataType`; shrinks to zero when open handshake §2.9-2 lands);
|
||||
`workspace.rs` (`WorkspaceIndex`: units, members, defines, instantiation and
|
||||
inheritance edge tables, incremental `update_file`/`remove_file`,
|
||||
`fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache);
|
||||
`instantiations.rs`, `classes.rs` (the shared walks, lifted from the server
|
||||
so the index census and the request handlers cannot drift).
|
||||
|
||||
**`lucisv_core`** — `config.rs` (`lucisv.toml` parsing + `Discovery`, the
|
||||
upward search with its per-instance cache), `walk.rs` (`collect_files`,
|
||||
`EXTENSIONS`, `.gitignore`/`--exclude` filtering), `filelist.rs` (the `.f`
|
||||
reader: files, `+incdir+`, defines, warnings), `cache.rs` (the format cache +
|
||||
`content_hash` — the one FNV-1a the server's index cache also reuses). Knows
|
||||
nothing of Verilog; depends on nothing; owns two open handshakes (§2.9-1,
|
||||
§2.9-8).
|
||||
|
||||
**`vlog_linter`** — `registry.rs` (`Rule` trait, `all_rules`/`default_rules`/
|
||||
`select_rules`), `rules/` (one file per rule; names are **stable API** — they
|
||||
appear in users' waivers), `context.rs` (`LintContext<'a>`, `ParsedSource`,
|
||||
lazy `semantics()`), `visit.rs` (the item/statement walk), `waiver.rs`,
|
||||
`violation.rs` (+ `Fix`, `Applicability`), `signals.rs` (the shared signal
|
||||
table for the three semantic rules), `naming.rs`, `rule_docs.rs`
|
||||
(`rules_markdown()` — docs generated from the registry).
|
||||
|
||||
**`vlog_refactor`** — `rename.rs` (the `Scope` cache + occurrence walk —
|
||||
also the engine of `references.rs::find_references`), `ports.rs`
|
||||
(add/remove/propagate), `instantiate.rs` (plans + rendering; the one layout
|
||||
both plain and snippet spellings go through), `check.rs` (whole-edit
|
||||
verification: re-tokenize + re-resolve, refuse everything on any drift).
|
||||
|
||||
**`lucisv` (CLI)** — `main.rs` (args → walk → per-file worker pool;
|
||||
`process_file` is the cache-aware unit of work; panic hook installed once at
|
||||
startup — **keep it that way**, cli-polish → parallel-files handshake),
|
||||
`args.rs`, `diff.rs`, `lint.rs` (the `check` subcommand; owns the CLI-side
|
||||
fence filter).
|
||||
|
||||
**`lucisv_server`** — layered, 40 files (`includes.rs` is the one file that
|
||||
spans two layers — the include graph *and* the `documentLink` handler;
|
||||
`perf.rs` is `#[cfg(test)]`-only and is not a layer — see
|
||||
`docs/perf/README.md`):
|
||||
|
||||
| layer | files | role |
|
||||
|---|---|---|
|
||||
| entry | `main.rs` | capabilities advertisement, `InitializeParams` reading, wiring |
|
||||
| loop | `server.rs` | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, reindex orchestration, progress/log senders |
|
||||
| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay) and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
|
||||
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word tables, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync |
|
||||
| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs`, `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion.rs`, `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) |
|
||||
|
||||
**`editors/vscode`** — `extension.js` (spawn + rainbow decorations + storage
|
||||
path; ~everything else is `vscode-languageclient` driven off advertised
|
||||
capabilities), `package.json` (languages, grammar, snippets, settings,
|
||||
colour ids), `syntaxes/` (hand-maintained grammar, test-locked to
|
||||
`KEYWORDS`), `snippets/` (static, server-independent), `smoke.js` (headless
|
||||
handshake check), `README.md` (the Marketplace Details page, owned by
|
||||
editor-marketplace-page).
|
||||
|
||||
---
|
||||
|
||||
## 2. Feature dependency graph
|
||||
|
||||
96 features. They cluster into eight lanes; edges inside a lane are listed in
|
||||
that lane's table, cross-lane edges are repeated where they matter. The
|
||||
mermaid graph shows the lanes and the load-bearing cross-lane edges only.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph FMT [formatter foundations]
|
||||
direction TB
|
||||
safety[safety-net] --- cmts[comment rounds] --- fences[format-fences] --- rangef[range-formatting]
|
||||
end
|
||||
subgraph GRAM [parser grammar / corpus]
|
||||
direction TB
|
||||
corpus[corpus-check] --- pspans[spans / name-spans] --- macro[macro-items] --- classes --- rest[...12 more buckets]
|
||||
end
|
||||
subgraph CLIL [CLI lane]
|
||||
direction TB
|
||||
polish[cli-polish] --- cfg[config-discovery] --- par[parallel-files] --- cache[format-cache]
|
||||
end
|
||||
subgraph LINT [linter lane]
|
||||
direction TB
|
||||
lcore[linter-core] --- lr2[lint-rules-2] --- slint[semantic-lints]
|
||||
end
|
||||
subgraph SEM [semantics & index]
|
||||
direction TB
|
||||
vsem[vlog-semantic] --- widx[workspace-index] --- incr[incremental-index] --- persist[index-persistence]
|
||||
end
|
||||
subgraph REF [refactor lane]
|
||||
direction TB
|
||||
flist[filelist M1] --- ren[refactor-rename M2] --- prt[refactor-ports M3] --- inst[refactor-instantiate M4]
|
||||
end
|
||||
subgraph LSP [LSP server lane]
|
||||
direction TB
|
||||
srv[lucisv-server] --- caps[~30 capability features]
|
||||
end
|
||||
subgraph PKG [packaging & release]
|
||||
direction TB
|
||||
epack[editor-packaging] --- pvsix[editor-platform-vsix] --- cirel[ci-release]
|
||||
end
|
||||
GRAM --> FMT
|
||||
corpus -. measures .-> GRAM
|
||||
LINT --> FMT
|
||||
SEM --> GRAM
|
||||
SEM --> CLIL
|
||||
REF --> SEM
|
||||
LSP --> SEM
|
||||
LSP --> REF
|
||||
LSP --> FMT
|
||||
LSP --> LINT
|
||||
LSP --> CLIL
|
||||
CLIL --> FMT
|
||||
PKG --> LSP
|
||||
PKG --> CLIL
|
||||
PKG --> GRAM
|
||||
```
|
||||
|
||||
### 2.1 Formatter foundations
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `case-tables ──▶ safety-net` | depends | The case harness consumes `format_source`'s post-safety-net `Err` — cases that used to produce wrong output now report `format failed:`. |
|
||||
| `formatter-bug-fixes ◀──▶ safety-net` | handshake | safety-net *filed* the request (comments need positions to re-indent); formatter-bug-fixes *delivered* it: `Comment { line, col }`, `Token::trailing: Option<Comment>`, `RawText { text, col }`. |
|
||||
| `formatter-bug-fixes ──▶ case-tables` | depends | Fixes the five bugs case-tables found and parked; each `#SKIP` case became a live regression case. |
|
||||
| `format-fences ──▶ spans` | depends | The first consumer of byte spans: a fenced region is a source slice by span. Also added `Doc::Verbatim` (leaf; emitted only right after a line break). |
|
||||
| `comments-round ◀──▶ format-fences` | handshake | fences requested a span on `Meta.trailing`; comments-round delivered `Option<Comment>`. Same-line fences remain deliberately inert (matcher unchanged) — documented on both sides. |
|
||||
| `comments-round-2 ──▶ comments-round` | depends | Closes the bracket-position comment shapes round 1 parked; same machinery, four new `Vec<Comment>` slots. |
|
||||
| `corpus-bugs ──▶ corpus-check` | depends | Fixes exactly the four root causes A–D the corpus check catalogued; measured back to 0 verification errors. |
|
||||
| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. |
|
||||
| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. |
|
||||
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
|
||||
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
|
||||
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
|
||||
| `recursion-limit ◀──▶ parallel-files` | handshake | recursion-limit requires ≥8 MiB worker stacks; parallel-files built the pool with `stack_size(8 MiB)` and a test that fails if it is removed. |
|
||||
| `recursion-limit ◀──▶ error-recovery` | handshake | Recovery must not reset `depth`/`links` while unwinding; error-recovery proves it with white-box + mutation tests. |
|
||||
| `one-parse ◀──▶ linter-core / server-lint` | handshake | Both filed the "one parse, two tools" request; one-parse delivered `LintContext::from_parse` + `ParsedSource`, `Document` gained its `tree` field, and both front ends lint from one parse. Behavior byte-identical was the gate. |
|
||||
|
||||
Standing discipline for every feature in this lane (and any feature touching
|
||||
the formatter): **`verify.rs` widening is guilty until proven innocent**
|
||||
(CLAUDE.md #4). The only widening ever shipped is macro-items'
|
||||
backtick-`Ident` arm in `normalize` — the normalization that produced
|
||||
lucisv's one real corruption (2026-08-19, shipped without attack tests). Its
|
||||
repair, `trim_lines_outside_strings`, is a *narrowing*, and it shipped with
|
||||
the rejection tests the widening lacked. Every other round states
|
||||
"`verify.rs` untouched" and adds *rejection/attack tests anyway*. Treat that
|
||||
as the template.
|
||||
|
||||
### 2.2 Parser grammar / corpus lane
|
||||
|
||||
`corpus-check` is the measuring instrument for the whole lane: it defines
|
||||
the buckets, and each grammar feature empties one and *advances* files into
|
||||
the next — a sequencing chain, not a code dependency. The lane's members:
|
||||
the sixteen bucket features (macro-items, classes, **bind**, **dynamic-types**,
|
||||
**types-decls**, item-misc, directives-in-lists, directives-in-instances,
|
||||
dpi-export, assertions, interfaces, expressions-2, dv-statements, mop-up-2,
|
||||
directive-split, ansi-first-port) plus the parser-infrastructure features
|
||||
(spans, name-spans, error-recovery, lexer-cleanup, define-table, and
|
||||
recursion-limit, whose edges sit in §2.1). Code edges:
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| every grammar feature `──▶ corpus-check` | depends | The bucket scores and first-blocker histograms are how each round chose its target and measured its result. |
|
||||
| `classes ◀──▶ vlog_parser::parse` | handshake | `parse(tokens)` became `parse(tokens, source)` — verbatim capture needs source in strict mode; every caller updated in the same change. |
|
||||
| `assertions ──▶ classes` | depends | Reuses `verbatim_since`/`skip_balanced` (the constraint/covergroup capture) unchanged; adds `StmtKind::Verbatim`. |
|
||||
| `directive-split ──▶ assertions / classes` | depends | Fifth producer of `ItemKind::Verbatim`; reuses the capture and `Fmt::raw_text` unchanged. |
|
||||
| `item-misc ──▶ macro-items` | depends | Extends `at_macro_item` (spaced argument lists, `` `error``/`` `warning``); same verbatim contract, `RawText.col` still load-bearing. |
|
||||
| `classes ─▶ macro-items` | refined in place | classes added the one-line `#(`-lookahead refinement to `at_macro_item` (the `` `uvm_component_new`` + parameterized-declaration idiom) — documented in classes' Handshakes, safety property unchanged. |
|
||||
| `dynamic-types ─▶ ast::Dim` consumers | non-additive change | `Dim` became `{ kind: DimKind, span }` — the lane's **only** vector-element/shape change in history; every consumer was found by grep and updated (`Fmt::dim`, `bind_dims`, the spans walker). The precedent §3.3's "prefer additive fields" rule exists to avoid repeating. |
|
||||
| `mop-up-2 ──▶ macro-items / dv-statements` | depends | Delivers the macro-followed-by-symbol fix dv-statements filed against macro-items, plus `new obj` (the expressions request from dv-statements) and base-only numbers. |
|
||||
| `directives-in-instances ──▶ directives-in-lists` | depends | Reuses `ListDirective` and `take_list_directives` verbatim; same additive-fields shape chosen for the same blast-radius reason. |
|
||||
| `dpi-export ─▶ dv-statements` | sequencing | Handed `csr_utils_pkg.sv` on (its next blocker was a `foreach`, a dv-statements shape). Typical of many one-way "your bucket now" notes across this lane. |
|
||||
| `interfaces ─▶ expressions-2` | sequencing | Two files advanced to `->` implication and drive strengths; expressions-2 emptied that bucket. |
|
||||
| `classes ◀──▶ class-semantics` | handshake | classes shipped with the honest gap "no name inside a class body is indexed"; class-semantics closed it (see §2.5). |
|
||||
| `classes ─▶ format-fences` | open request | `fence::scan_nested` has no `Class` arm, so a fence inside a class body is inert **for the formatter** (the `protected_regions` line-scan backstop still protects `--fix`). Filed, not fixed — §2.9. |
|
||||
| `ansi-first-port ◀──▶ type-definition` | handshake | type-definition filed the "first port with no direction doesn't parse" request; ansi-first-port delivered it (parser + one `bind_data_type` arm + one `type_span` tweak), and type-definition's tests flipped. |
|
||||
| `lexer-cleanup ──▶ error-recovery / lint-rules-2` (QA logs) | depends | Fixes three lexer gaps: `@(* )` (TODO §1) plus the BOM and non-ASCII-honesty findings those two QA rounds filed; adds `ParsedSource::lex_error()` so `lucisv check` stops silently passing unlexable files. |
|
||||
| `error-recovery ─▶ lucisv-server / linter-core` | depends (downstream) | `parse_source_tolerant` is the entry point the whole LSP and the linter stand on; the strict/tolerant split (shared grammar, no second parser) is the contract. |
|
||||
| `name-spans ◀──▶ vlog-semantic` | handshake | vlog-semantic filed request 1 (spans on ~15 declaring nodes); name-spans delivered it, shrinking `scan.rs` to the `DataType` case (still open — §2.9). |
|
||||
| `spans ─▶ everything positional` | depends | Byte ranges + `LineIndex` are the prerequisite named by TODO §6 for the LSP effort and by fences/range formatting. |
|
||||
|
||||
Also uniform in this lane: each new AST variant lists its exhaustive-match
|
||||
blast radius (formatter arm, `bind.rs` arm, `spans.rs` arm) — that checklist
|
||||
**is** the interface cost of touching `ast.rs`, and §3.3 restates it as a
|
||||
rule. `vlog_linter`'s `visit.rs` is catch-all **for compilation only**: a new
|
||||
variant that *contains items or statements* still needs an arm there, or no
|
||||
AST lint rule ever descends into it (dv-statements added two such arms;
|
||||
classes' missing one was a filed coverage gap, closed by lint-rules-2).
|
||||
|
||||
### 2.3 CLI lane
|
||||
|
||||
A clean promise chain — each feature consumed the previous one's written
|
||||
promise:
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `config-discovery ──▶ cli-polish` | depends | Consumed `Options.stdin_filename` exactly as promised (discovery anchor only) and `Options.exclude` as the CLI layer config patterns append to. |
|
||||
| `parallel-files ◀──▶ cli-polish` | handshake | cli-polish flagged its hook-swapping `catch_panic` as single-thread-only; parallel-files replaced it with one startup hook + thread-local flag. **Anyone editing `catch_panic` must keep it that way.** |
|
||||
| `parallel-files ──▶ config-discovery` | depends | Consumed the promise that config resolution happens up front in `gather`, producing the exact `Vec<(PathBuf, Config)>` work list a `par_iter` wants. |
|
||||
| `format-cache ──▶ parallel-files` | depends | Consumed the promise that `process_file` is the per-file unit of work and `Outcome` the place a `Cached` bucket goes. |
|
||||
| `format-cache ──▶ config-discovery` | depends | Consumed the cache-key promise: key includes resolved per-file settings (values, not config-file identity). |
|
||||
| `format-cache ─▶ every output-changing feature` | standing promise | **Any change to formatter output must bump the workspace version** or warm caches keep stale verdicts. Same discipline as ruff/black. |
|
||||
| `cli-filelist ──▶ filelist` | depends | Reuses `lucisv_core::filelist::read` unchanged (M1 explicitly parked the `-f` flag for this round); drops `incdirs`/`defines` as meaningless to a non-preprocessing formatter. |
|
||||
| `cli-polish / linter-core ─▶ corpus-check, CI users` | standing promise | The 0/1/2 exit-code contract is frozen; new modes map onto it, never extend it. |
|
||||
| `lucisv-core-lift ◀──▶ lucisv-server` | handshake | Delivered the server's two filed requests (config discovery + ignore-aware walk) by lifting `config.rs`/`walk.rs` into `lucisv_core` unchanged; CLI behavior byte-identical. |
|
||||
|
||||
### 2.4 Linter lane
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `linter-core ──▶ error-recovery` | depends | Lints the tolerant tree so unparseable files are still linted for what is visible. |
|
||||
| `linter-core ──▶ format-fences` | depends | CLI `--fix` reads `fence` (already `pub`) to stay out of fenced regions — one answer to "what is fenced", not two (later formalized by shared-fence-filter). |
|
||||
| `lint-harness ──▶ linter-core` | depends | Consumes only the public API; the `.lint` case format + "marker naming a dead rule fails the suite" is the enforcement of rule-name stability on the test side. |
|
||||
| `lint-harness ──▶ safety-net` (via dev-dep) | depends | Every fix's output must be something `format_source` accepts. |
|
||||
| `lint-rules-2 ◀──▶ classes` | handshake | Closes the classes handshake: `visit.rs` now walks class bodies, so the four AST rules see class members. |
|
||||
| `semantic-lints ──▶ vlog-semantic` | depends | The three symbol-table rules; new (justified) crate dep `vlog_linter → vlog_semantic`; lazy analysis; the lead's pre-authorization to modify `vlog_semantic` went **unused** (recorded so it is not read as taken). |
|
||||
| `semantic-lints ──▶ one-parse` | depends | Reaches the server and CLI through the existing one-parse path (`LintContext::semantics()` / `with_semantics`). |
|
||||
| `server-lint ──▶ linter-core` | depends | Protocol wiring only; relies on the three written promises (stable names, no panics/writes, sorted findings). |
|
||||
| `server-lint ◀──▶ shared-fence-filter, one-parse` | handshake | Both of server-lint's filed requests were delivered by those rounds (fence-safe quick fixes; lint-from-Document). |
|
||||
|
||||
### 2.5 Semantics & index lane
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `vlog-semantic ──▶ error-recovery, spans` | depends | Tolerant trees as input; span conventions throughout. |
|
||||
| `workspace-index ──▶ vlog-semantic` | depends | Finishes `ExternalCandidate`s against what every file declares; the `paths` spelling contract is the coupling — if `bind.rs`/`resolve.rs` change a path's spelling, `workspace.rs::follow_one` changes with it. |
|
||||
| `workspace-index ──▶ define-table` | depends | Each file's `` `define`` table is an index column (`find_define`). |
|
||||
| `class-semantics ◀──▶ classes` | handshake | Delivers the filed gap; adds `SymbolKind::Class`, `ScopeKind::Class`, `InheritedCandidate` — with the two named compile-fix arms in `lucisv_server` (`tokens.rs`, `symbols.rs`). |
|
||||
| `class-semantics ──▶ name-spans` | depends | Built on the delivered span fields; keeps `src[name_span] == name` corpus-asserted. |
|
||||
| `overlay-promotion ◀──▶ type-definition` | handshake | Delivers type-definition's request 1: a **type-position** miss carries the bare name as its last candidate path (both miss spellings), so the overlay answers interfaces and package-less classes; type-definition then deleted its `indexed_type` fallback. Value-position misses unchanged — that asymmetry is the contract. |
|
||||
| `type-hierarchy ──▶ overlay-promotion` | depends | The whole cross-file half is overlay-promotion being consumed at the `extends` offset. |
|
||||
| `incremental-index ◀──▶ code-lens, hierarchy, type-hierarchy` | handshake | Delivers the jointly-filed edge tables: `instantiations_of` / `subclasses_of` recorded at build time; `callers_of_each` and `subtypes` became lookups (92 ms→0.26 ms, 82 ms→0.71 ms). Census policy carried over by construction: the walks (`instantiations.rs`, `classes.rs`) were **lifted into `vlog_semantic`**, not copied. |
|
||||
| `incremental-index ──▶ indexing-ux` | depends | Amends the event story: a one-file update reports no events (one parse is not a scan); invariant: `update_file` yields byte-for-byte the index a full rebuild would (`fingerprint` is the witness; `update_one_checked` the test form). |
|
||||
| `index-scope ◀──▶ indexing-ux` | handshake | Closes indexing-ux's QA finding by making `IndexBuilder` order-insensitive (sort/dedup in `finish`); `index_order` survives for the progress denominator. |
|
||||
| `index-scope ──▶ filelist` | depends | Rung 1 (a filelist defines the scope exactly) is untouched; rungs 2/3 of the scope ladder were re-written (folder-scoped, open-file-first) — the ladder itself is the contract, documented in both READMEs. |
|
||||
| `index-persistence ──▶ incremental-index` | depends | `update_one` writes its record through via `WorkspaceIndex::facts_for` (no double parse). |
|
||||
| `index-persistence ──▶ format-cache` (lucisv_core) | depends | Reuses `lucisv_core::cache::content_hash` — one FNV-1a shared with the format cache, not a second copy. Also one additive `vlog_parser` touch: `DefineTable::from_entries` + `PartialEq`/`Eq` derives, so a record restores a table without re-reading a file. |
|
||||
| `index-persistence ◀──▶ indexing-ux` | handshake | `IndexEvent::Cached` — a new variant, so every consumer is forced to say what it does with an unparsed file; the end message names the cached count. |
|
||||
| `port-detail-spans ◀──▶ index-persistence` | handshake | A declaration record grew two numbers (the detail span, written unconditionally as `0 0` for the `None` every ordinary declaration has), so **`FACTS_FORMAT` went 2 → 3** and every store written by an earlier build is discarded whole rather than read field-shifted. The bump *is* the contract: `index_cache.rs`'s header line carries the number, and the reader's `done()` check is a backstop, not a version scheme. |
|
||||
| `define-table ◀──▶ macro-expansion` | handshake | What began as free-to-change became contract at M14: params stored **as written**, `NAME()` = `Some(vec![])` — `expand.rs` counts arguments against them and declines on mismatch. |
|
||||
|
||||
### 2.6 Refactor lane (the M-plan)
|
||||
|
||||
`refactor` is the umbrella plan; M1–M4 are its milestones plus two follow-ups.
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `filelist (M1) ──▶ refactor` | depends | The scope story: a `.f` filelist is the project file; parser in `lucisv_core` (so the CLI later reuses it — it did, cli-filelist), scope ladder in the server. |
|
||||
| `refactor-rename (M2) ──▶ vlog-semantic / workspace-index` | depends | Every edit from a resolved span; whole-edit verification; refusals from `Resolution` variants. |
|
||||
| `refactor-rename ◀──▶ vlog_semantic` | handshake | The one authorized cross-module change of M2: `Target::Declaration` + `use_end_label` (end labels must rename or the output doesn't compile). Strictly additive; logged in vlog-semantic's work log. |
|
||||
| `refactor-ports (M3) ──▶ refactor-rename` | depends | Reuses M2's `check`/`Scope`; the two preprocessor scans were factored to return *sites* so M3 words its own warnings without inheriting M2's text (M2's wording pinned by its 48 tests). |
|
||||
| `refactor-instantiate (M4) ──▶ workspace-index, editor-scopes` | depends | Plans from the index's real definitions; the item-position gate is built on `pairs::analyze`'s published output only. |
|
||||
| `apply-edit ──▶ refactor-ports` | depends | The port commands now *push* `workspace/applyEdit` (the protocol's actual mechanism) instead of answering the edit as a result no client applies. `ports::execute`'s signature and behavior unchanged — the only `ports.rs` edit was correcting a now-false doc comment, so this is consumption, not a handshake. |
|
||||
| `references-nav ──▶ refactor-rename` | depends | `find_references` is `Scope::collect_occurrences` lifted out of `collect_edits` — the references list and a rename's touch-set **cannot disagree**, by construction (deliberately not moved to `vlog_semantic`; the walk needs refactor-crate concerns). |
|
||||
|
||||
### 2.7 LSP server lane
|
||||
|
||||
`lucisv-server` is the trunk; everything below extends it. Edges to
|
||||
engine-lane features are listed above; this table is the server-internal web.
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `editor-scopes ─▶ (many)` | depends (consumed by) | `pairs.rs` — one stack matcher, eight consumers today: documentHighlight, missing-closer diagnostics, `lucisv/scopePairs` rainbow, folding (references-nav), the item-position gates (completion-core / refactor-instantiate), on-type-formatting's keyword tables, inline-templates' unmatched-`begin` check, expand-selection (`selection.rs`). The `RULES` table + guard list is the shared truth; a keyword change means re-checking it. |
|
||||
| `editor-scopes ◀──▶ editors/vscode` | handshake | The `lucisv/scopePairs` wire shape (pinned as literal JSON in a test) and the `lucisv.rainbow*` colour ids that must match between `package.json` and `extension.js`. |
|
||||
| `completion-core ──▶ define-table, vlog-semantic, workspace-index, refactor-instantiate` | depends | Five tiers over existing facts; the parser widening (`KEYWORDS` export) is its one engine touch. Deliberate duplication recorded: `visible_symbols` vs `ports::visible_in` share an idea, not code. |
|
||||
| `completion-templates ──▶ completion-core, editor-scopes` | depends | Tier 3; `templates.rs` is data + one renderer; tier digits moved (only e2e's word-tier assertion cared). Also consumes `vlog_refactor::Layout` (M4's `{ base, step }`), reused rather than re-declared, so a skeleton and a template indent by one type. |
|
||||
| `completion-templates ◀──▶ editor-snippets` | handshake | Nine overlapping statement/block snippets were **removed** from `editors/vscode/snippets/*.json` when the server started offering them as tier 3; both READMEs' prefix tables are the shared truth. A template added server-side must check the static set, and vice versa. |
|
||||
| `inlay-hints ──▶ refactor-instantiate` | depends | Reads exactly the `module_definition` + `instantiation_plan` facts M4 published (the `PlanPort`/`PlanParam` name lists signature help reads); every plan refusal is swallowed silently — a hint has no place for a sentence. |
|
||||
| `inline-templates ──▶ completion-templates, editor-scopes` | depends | Same skeletons as ghost text (LSP 3.18 `inlineCompletion`, `lsp-types` `proposed` feature); relative-indent contract — the client finishes the whitespace; round 2 dropped its `layout_at` consumption (re-privatized). |
|
||||
| `hover/define ──▶ define-table`; `macro-expansion ──▶ define-table + hover` | depends | See the §2.5 handshake; `expand.rs` is deliberately workspace-blind (two strings + a `Define`). |
|
||||
| `include-nav ──▶ filelist` | depends | First consumer of `incdirs`; the include graph (build/resolve/reachable, one `scan` shared by links, definition and the graph) plus hover's reachability overlay — `find_define`'s contract explicitly unchanged. |
|
||||
| `file-operations ──▶ include-nav, file-watching` | depends | `resolve_as_if` added so willRename asks the *one* resolution engine about a future filesystem; reuses `watch::watched` + `SOURCE_GLOB` as the one scope predicate. |
|
||||
| `file-watching ──▶ filelist / lucisv-core-lift` | depends | `SOURCE_GLOB` pinned to `walk::EXTENSIONS` by test; watches the filelist itself; re-registers on filelist change. |
|
||||
| `folders-and-config ──▶ editor-settings` | depends | Adds the pull door (`workspace/configuration`) wrapped back into the push shape so there is exactly one settings parser; `Pending` generalizes apply-edit's `applying` map. |
|
||||
| `editor-settings ◀──▶ lucisv-core-lift` | handshake | The four-rung precedence ladder (lucisv.toml > `lucisv.*` settings > tab size > defaults), per key — the reason the ladder can exist is the lifted `Discovery`. `will-save-wait-until` reuses the ladder minus rung 3. |
|
||||
| `incremental-sync ◀──▶ pull-diagnostics` | handshake | One `didChange` = one `set_document` = one generation bump, however many ranges — pinned by test; the generation **is** the pull model's `resultId`. `semantic-tokens-delta` promises the inverse: token requests never bump it. **Amended 2026-08-28 by change-debounce**: one *flush* is one `set_document`, one bump and one publish per dirty buffer — however many ranges *and* however many notifications it coalesced. |
|
||||
| `change-debounce ◀──▶ incremental-sync, pull-diagnostics` | handshake | The amendment above. A `didChange` composes its ranges against the *pending* text when there is one (`sync::apply_changes` unchanged) and defers only the analysis; the flush happens at the next request, the next non-`didChange` notification, or a 150 ms quiet period on the `cancel-request` queue (`recv_timeout` — no thread, no timer object). Observable: intermediate diagnostics states are no longer published, pinned in `tests/e2e.rs`. |
|
||||
| `port-detail-spans ──▶ hover-declarations` | depends | The second fenced section, and the comment attached to each, are built on hover-declarations' snippet machinery and its `spells_exactly` guard, both unchanged. `nav::definition` returns the detail location first so a jump and the card cannot disagree. |
|
||||
| `hover-declarations ◀──▶ vlog_semantic` | handshake | `Semantics::symbols_named` (§1.2) replaced `hover::live_symbol`'s and `nav::indexed_references`' scan-every-symbol loops. Behavior-identical **because the lookup preserves declaration order** — the tie-break between two live declarations of one name is pinned on both sides. |
|
||||
| `cancel-request ──▶ lsp-server pin` | depends | See §1.2; queue/burst exists because the pinned transport is a rendezvous channel. |
|
||||
| `work-done-progress ──▶ indexing-ux` | depends (then) | w-d-p put up the bar; indexing-ux made it count (`IndexEvent` stream); index-persistence added `Cached`. |
|
||||
| `large-file-mode ◀──▶ semantic-tokens-delta` | handshake | The windowed lexing serves `semanticTokens/range`; on a large buffer `full`/`full/delta` must answer an ERROR (`ServerCancelled`/`ContentModified`) or the client stops asking the range provider — two sides pinning one wire behavior. `Document::large` is structurally a full `Document` (all fields valid, empty) so no handler changes — the obligation lands on **future** handlers that read `doc.text` (dispatch-table test enforces). |
|
||||
| `lsp-318-extras ──▶ range-formatting` | depends | `rangesFormatting` is a thin adapter over the same n-range `LineRanges` engine `--lines` uses; hand-rolled params because `lsp-types` 0.97 lacks 3.18. |
|
||||
| `on-type-formatting ──▶ range-formatting, editor-scopes` | depends | `;` goes through `format::range_formatting` unchanged; `\n` answers indent only, computed from `pairs.rs`'s own keyword tables (three items widened to `pub(crate)`) — one reader's answer for "what opens a scope". |
|
||||
| `interactive-latency ──▶ change-debounce, editor-scopes, selection-range, on-type-formatting, completion-core, inline-templates` | depends | Round 2 of the perf work (`docs/perf/README.md`). It measures the flush change-debounce coalesces and the round trip it defers, and it replaces one token *sweep* with one token *binary search* in `selection.rs`, `on_type.rs`, `completion.rs` and `inline.rs`. No answer moved — each swap is pinned against the sweep it replaced at every byte — so none of those five features' contracts changed; what they now share is `state.rs`'s two search primitives and the ordering property of `tokenize`'s output they rest on. |
|
||||
| `interactive-latency ◀──▶ lucisv-server` | handshake | Two free functions, `first_token_reaching` and `first_token_from`, are published from `state.rs` beside `Document::token_at`; that is where the monotonicity argument every caller depends on is written down, and `state::tests::the_token_stream_rises_and_never_overlaps` is the test that fails first if `vlog_parser` ever breaks it. `tests/e2e.rs`'s `Live::finish` now returns its publish count (existing callers ignore it), and `perf::generated_module` has a copy in `tests/e2e.rs` — a binary crate's modules are unreachable from an integration test — which must stay the same shape as the original. |
|
||||
| `selection-range / linked-editing ──▶ spans, name-spans` | depends | Pure arrangements of existing ranges; linked-editing's table documents exactly which constructs carry both spans (and which verbatim ones can't — `program`, property/sequence, covergroup). |
|
||||
| `type-definition ──▶ nav / overlay-promotion / ansi-first-port` | depends + 2 delivered handshakes | Now literally `nav::definition` at the type name's offset; both of its filed requests landed (§2.2, §2.5). |
|
||||
| `hierarchy ◀──▶ inlay-hints` | handshake (shared walk) | The instantiation walk was lifted out of `inlay.rs` into a shared module (now `vlog_semantic::instantiations`) rather than copied — the two answers cannot drift; inlay's 34 tests are the regression net. |
|
||||
| `code-lens ◀──▶ hierarchy` | handshake | code-lens split `incoming` into the batch primitive `callers_of_each` so lens and hierarchy share one census; `incoming` is a one-element call into it and its behavior (empty-name guard included) is pinned unchanged. Lens and hierarchy views can never disagree; refresh rides `reindex()` after the bar comes down. |
|
||||
| `server-lint / pull-diagnostics / editor-scopes ──▶ diagnostics.rs` | depends | One `diagnostics::all` composition: parse errors + missing-closer warnings + lint warnings, one publish (or one pull) per change; `send_diagnostics` is the single push gate so a pulling client is never served both models. |
|
||||
|
||||
### 2.8 Packaging & release lane
|
||||
|
||||
| edge | kind | contract |
|
||||
|---|---|---|
|
||||
| `editor-packaging ◀──▶ lucisv-server` | handshake | The spawn contract (§1.2) plus the fence-tag contract: every markdown code block the server emits opens ```` ```systemverilog ```` — three call sites pin the string; the grammar registers the id. |
|
||||
| `editor-packaging ◀──▶ vlog_parser` | handshake | The grammar↔`KEYWORDS` test lock (§1.2). |
|
||||
| `editor-snippets ──▶ editor-packaging` | depends | Static `contributes.snippets` keyed to the two language ids the manifest declares; consumes nothing from the server *at runtime* (works with the server missing — deliberate). Its **content** is negotiated against the server's template tier — see the `completion-templates ◀──▶ editor-snippets` handshake in §2.7. |
|
||||
| `editor-platform-vsix ──▶ editor-packaging, release-prep` | depends | Changes *which path* is spawned, never how; consumes `release.sh`'s artifact naming; promises the three `bin/` layout shapes to `extension.js` (asserted with `unzip -Z1` per package). |
|
||||
| `editor-platform-vsix ◀──▶ editor-marketplace-page` | handshake | The marketplace rewrite must keep the seven-package install table and the two bundled-binary layout sentences (re-applied additively during the concurrent rounds). |
|
||||
| `ci-release ──▶ release-prep / editor-platform-vsix` | depends | Workflow = one-liners over `tools/`; consumes the exact seven `.vsix` names (`prune_release_assets.sh` checks each), the `CHANGELOG.md` heading convention, tag == workspace version. |
|
||||
| `release-prep ──▶ editor-packaging` | depends | `release.sh` runs `smoke.js` as its gate; closed the missing-`LICENSE` item editor-packaging filed. Version lives in exactly four files — a promise to everyone. |
|
||||
| `editor-marketplace-page ──▶ lucisv-server` (docs) | depends | The Details page mirrors the shipped capability table in the server's README; drifts if that table does. |
|
||||
|
||||
### 2.9 Open handshakes (filed, not yet delivered — claim before working)
|
||||
|
||||
These are the known coordination points. An agent picking one up should
|
||||
update the filing README(s) and this file.
|
||||
|
||||
| # | request | filed by | owner it waits on |
|
||||
|---|---|---|---|
|
||||
| 1 | `lucisv_core::path::normalize` — one `.`/`..` folding instead of three private copies (`filelist::Reader::normalize`, `config::Discovery::absolute`, `includes::normalize`, the last now `pub`) | include-nav; restated by file-operations | lucisv_core |
|
||||
| 2 | A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive | vlog-semantic (item 2); restated by class-semantics | vlog_parser |
|
||||
| 3 | `fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off) | classes | vlog_formatter (fence.rs) |
|
||||
| 4 | A `lint` key in `lucisv.toml` (`[lint.<rule>]` config; selected-rules list) with CLI>config precedence | linter-core; restated by lint-rules-2, semantic-lints, server-lint | config-discovery / lucisv_core |
|
||||
| 5 | `lucisv check --rules-doc` printing `rules_markdown()` | lint-rules-2 | crates/lucisv |
|
||||
| 6 | Workspace-wide "does any file mention this name" query — the precondition for the semantic lints defaulting on (cross-file hierarchical use is their one false-positive mode) | semantic-lints | vlog_semantic (index) |
|
||||
| 7 | `SymbolKind::Interface` (interfaces currently indexed as `Module`; modport/clocking names unbound) | interfaces | vlog_semantic (+ mechanical arms in server `symbols.rs`/`hover.rs`) |
|
||||
| 8 | Symlink-cycle detection in the shared walk (both front ends exposed; wants its own round — it changes CLI behavior) | lucisv-core-lift | lucisv_core |
|
||||
| 9 | Chasing `InheritedCandidate` through the member tables (in-file and cross-file) + hover for `extends` — *partially advanced*: overlay-promotion made `resolve_external` answer an `InheritedCandidate` from its paths; the member-table chase and the hover remain absent | class-semantics | vlog_semantic |
|
||||
| ~~10~~ | ~~`Fmt::raw_text`'s string-crossing path emits a `Doc::Text` carrying newlines~~ — **delivered 2026-08-26 (`53f2269`)**: both `raw_text` and the parameterized-type `#( … )` now emit `Doc::Inline`, whose printer arm resumes measuring from the text's own last line. directive-split's README (QA round 3 note) still documents it as open and should be struck there too | directive-split QA | ~~vlog_formatter~~ done |
|
||||
| 11 | Corpus scripts match `parse error:` / `lex error:` / `verification failed:` textually; a structured `--output-format json` for format mode would remove it | corpus-check | crates/lucisv |
|
||||
| 12 | `vlog_refactor::rename::Scope::build` re-derives sort-and-dedup by hand; could call `index_order` | indexing-ux | vlog_refactor |
|
||||
| 13 | Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap | types-decls | vlog_semantic |
|
||||
| 14 | A `program` node with `name_span`/`end_label_span` (today it lands in `Error`/verbatim), which would let linked-editing serve it with one arm | linked-editing | vlog_parser |
|
||||
| 15 | Bind semantics: whether a `bind`'s target scope and connections should resolve through the workspace index (today only the instantiated module name is recorded) | bind | vlog_semantic |
|
||||
| 16 | DPI/package re-export halves as real references (`export pkg::item` doesn't resolve; `*::*` has `"*"` as its package name, which nothing expects) | dpi-export | vlog_semantic |
|
||||
| 17 | Inline aggregate as a parameter-override *argument* (`m #(.T(struct packed { logic a; })) u ();`) is rejected in expression position; M4's `instantiation_plan` drops such a `parameter type` default rather than emit unparseable text | refactor-instantiate (gap 1; its gap 2 was delivered by ansi-first-port) | vlog_parser |
|
||||
|
||||
---## 3. Combined graph — features mapped onto modules
|
||||
|
||||
### 3.1 Feature → primary-home matrix
|
||||
|
||||
Where a feature's code chiefly lives (its README remains the authority on
|
||||
exact file scope). Cross-module touches are recorded per-feature in §2 and in
|
||||
each feature README's Handshakes; this matrix names only the primary home.
|
||||
Grammar-lane features (*italicized*) routinely add exhaustive-match arms in
|
||||
other crates — see §3.3's `ast.rs` row — though not always a formatter arm:
|
||||
directive-split and ansi-first-port shipped with `vlog_formatter/src`
|
||||
untouched, reusing existing arms.
|
||||
|
||||
| module | features whose home it is |
|
||||
|---|---|
|
||||
| `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) |
|
||||
| `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter |
|
||||
| `vlog_semantic` | vlog-semantic (`bind`/`resolve`/`model`), workspace-index (`workspace.rs`), class-semantics, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` in `bind.rs`/`model.rs`/`workspace.rs`, the `facts.rs` codec + `FACTS_FORMAT` bump, and `Semantics::symbols_named` in `lib.rs`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`), incremental-index (`update_file`, edge tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) |
|
||||
| `vlog_linter` | linter-core, lint-harness, lint-rules-2, semantic-lints (`signals.rs`), one-parse (`context.rs`) |
|
||||
| `vlog_refactor` | refactor (plan), refactor-rename, refactor-ports, refactor-instantiate, references-nav (engine half) |
|
||||
| `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`) |
|
||||
| `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract) |
|
||||
| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring→`rename.rs`/`ports.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs`, pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, change-debounce→`server.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` |
|
||||
| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line) |
|
||||
| `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`) |
|
||||
|
||||
### 3.2 The combined picture
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph parser [vlog_parser]
|
||||
gram[grammar-lane features] --- pinfra[spans / name-spans / recursion-limit / error-recovery / define-table]
|
||||
end
|
||||
subgraph fmt [vlog_formatter]
|
||||
net[safety-net verify.rs] --- fmtf[fences / range / alignment / comment rounds]
|
||||
end
|
||||
subgraph sem [vlog_semantic]
|
||||
core[vlog-semantic] --- idx[workspace-index + incremental / persistence / scope / ux]
|
||||
end
|
||||
subgraph lint [vlog_linter]
|
||||
lc[linter-core + rules + harness + semantic-lints]
|
||||
end
|
||||
subgraph refac [vlog_refactor]
|
||||
ms[M2 rename / M3 ports / M4 instantiate / references]
|
||||
end
|
||||
subgraph corelib [lucisv_core]
|
||||
cw[config + walk + filelist + cache]
|
||||
end
|
||||
subgraph cli [lucisv CLI]
|
||||
clif[cli lane features]
|
||||
end
|
||||
subgraph srv [lucisv_server]
|
||||
caps[capability features (~30)]
|
||||
end
|
||||
subgraph ed [editors/vscode + tools/CI]
|
||||
pkg[packaging lane]
|
||||
end
|
||||
gram --> fmt
|
||||
fmt --> parser
|
||||
sem --> parser
|
||||
lint --> parser
|
||||
lint --> sem
|
||||
refac --> parser
|
||||
refac --> sem
|
||||
srv --> parser
|
||||
cli --> parser
|
||||
cli --> corelib
|
||||
cli --> fmt
|
||||
cli --> lint
|
||||
srv --> corelib
|
||||
srv --> sem
|
||||
srv --> refac
|
||||
srv --> fmt
|
||||
srv --> lint
|
||||
pkg --> srv
|
||||
pkg --> cli
|
||||
```
|
||||
|
||||
Reading it feature-side: a grammar feature is by default a
|
||||
**parser+formatter pair** (new AST + its layout, plus minimal arms in
|
||||
`bind.rs`/`spans.rs`) — though one that reuses an existing arm ships with the
|
||||
formatter untouched (directive-split, ansi-first-port); an index feature is a
|
||||
**vlog_semantic + lucisv_server pair** (the data structure and the
|
||||
events/settings around it); a capability feature is usually **server-only
|
||||
plus one manifest line** (one handler module + `main.rs` capability + often a
|
||||
`settings.rs` field, which then owes an `editors/vscode/package.json`
|
||||
`contributes.configuration` entry — the choke point whose mismatches are
|
||||
silent); a packaging feature is **editors/tools-only, save for the two pins
|
||||
it owns in Rust** (editor-packaging's `tests/grammar.rs`, release-prep's
|
||||
`--version` shape). Those shapes are the default that makes the lanes
|
||||
parallel-safe — not an invariant; say in your scope which arms you actually
|
||||
owe.
|
||||
|
||||
### 3.3 Choke points — files where features meet
|
||||
|
||||
These are the highest-contention interfaces. When two agents' scopes both
|
||||
name one of these, they are not parallel — serialize or split the file's
|
||||
ownership explicitly.
|
||||
|
||||
| choke point | owner (feature) | consumers | the rule |
|
||||
|---|---|---|---|
|
||||
| `vlog_parser/src/ast.rs` | the grammar lane collectively | formatter, semantic, linter, refactor, server, `tests/spans.rs` | A new variant costs, at minimum: a `format.rs` arm, a `bind.rs` arm, a `spans.rs` arm. `visit.rs` is catch-all for compilation only — a variant containing items/statements still needs an arm there or AST lint rules never see inside it. Prefer **additive fields / parallel vectors** over changing vector element types — that is why `ListDirective` sits beside the lists instead of inside them (two rounds chose it independently for blast-radius reasons). |
|
||||
| `vlog_formatter/src/verify.rs` | safety-net | every formatter feature; the CLI's exit-2 promise | CLAUDE.md invariant #4. Never widen a normalization without masked-corruption attack tests; the standing pattern is "untouched + rejection tests anyway". The single widening in history is macro-items' backtick-`Ident` arm in `normalize` — which produced lucisv's one real corruption; its repair, `trim_lines_outside_strings`, is a *narrowing*, and the pattern to copy: the widening shipped without attack tests, the fix shipped with them. `line_starts_inside_string` is the one definition of "which line breaks are data" — both `format.rs` and `verify.rs` must read it. |
|
||||
| `vlog_formatter/src/fence.rs` | format-fences | range-formatting, shared-fence-filter, CLI `--fix` (`lucisv/src/lint.rs`), server quick fixes (`lucisv_server/src/lint.rs`) | `protected_regions`/`is_protected` are the **only** supported way to ask "may an automatic edit touch these bytes". One answer, **two** front ends — and `vlog_linter` is deliberately not one of them (it stays fence-blind; the filter lives in each front end). Open gap: no `Class` arm in `scan_nested` (§2.9-3). |
|
||||
| `lucisv_server/src/pairs.rs` | editor-scopes | documentHighlight, missing-closer diagnostics, scopePairs rainbow, folding, completion gates, on-type indent, inline-templates, expand-selection (`selection.rs`) | The `RULES` table + no-closer guard list is shared truth. Any keyword added to/removed from `token.rs` requires re-checking it (a word that stops being a keyword silently stops being matched). |
|
||||
| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, indexing-ux, incremental-index, index-persistence, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`) | every handler | `Workspace` is immutable through request handlers (no caches added by handlers — hierarchy/inlay/type-hierarchy all state it). The scope ladder (filelist > `index.scope: "workspace"` > folder-scope, with the rootless flat sibling read as folder-scope's one exception; buffers overlay everything) is the contract; `update_one`'s answer must equal a full rebuild's (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. |
|
||||
| `lucisv_server/src/settings.rs` | editor-settings | folders-and-config, indexing-ux, index-scope, index-persistence, inline-templates, will-save-wait-until, filelist, large-file-mode | One parser for both doors (push and pull, via `from_section` re-wrapping). Every key drops garbage independently; defaults that are not "silence" (1 MiB cap, log on, persist on, 4 MiB large-file threshold) are hand-written in `Default`. `set_client_settings` returns whether a reindex is owed — new keys must decide that question explicitly. |
|
||||
| `vlog_semantic/src/workspace.rs` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope | server state, hierarchy/lens/type-hierarchy, refactor, completion | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change, edge tables built by the same lifted walks the handlers use. |
|
||||
| `vlog_parser/src/token.rs` keyword table | completion-core (`KEYWORDS` export) | lexer, pairs.rs, editor grammar (test-locked), completion | Adding a keyword = lexer change + `pairs.rs` re-check + a hand edit to the grammar (`tests/grammar.rs` names the missing word) + potentially `verify.rs`-adjacent behavior. dv-statements added `randcase`/`let` to `is_keyword` and recorded it as shared with the adjacent lexer-cleanup round — the precedent for treating this file as coordinated even between back-to-back rounds. |
|
||||
| `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). Version number is one of the four version files. |
|
||||
| `tools/release.sh` artifact names | release-prep / editor-platform-vsix | ci-release (`prune_release_assets.sh`), `audit_artifacts.sh`, extension `bin/` layouts | Renaming a `.vsix` is a two-file change (`release.sh` + `prune_release_assets.sh`'s suffix list); renaming a per-triple binary is a two-file change (`release.sh` + `audit_artifacts.sh`, which skips `.vsix` and hard-fails on an unknown binary name). Get the wrong pair and the release fails by name. |
|
||||
| The frozen CLI contract | cli-polish | corpus scripts, CI users, every new CLI mode | Exit codes 0/1/2 forever; stdout stays machine-readable (JSON mode prints exactly one array; warnings to stderr). |
|
||||
|
||||
### 3.4 Working rules distilled for parallel agents
|
||||
|
||||
1. **Pick lanes, not files.** The eight lanes in §2 are the intended
|
||||
parallelism. Two features in one lane usually share a choke point (§3.3);
|
||||
check before spawning both.
|
||||
2. **A grammar feature is a pair by default** (parser + formatter arms +
|
||||
minimal `bind.rs`/`spans.rs` arms) — unless it reuses an existing arm, as
|
||||
the verbatim producers and ansi-first-port did. Say which arms you owe in
|
||||
the feature scope up front; the compile-fix arms in other crates are
|
||||
legitimate and should be listed in Handshakes, per the established
|
||||
pattern.
|
||||
3. **`cargo fmt` per package** (`-p a -p b`), never `--all`, while another
|
||||
agent is live — this rule already saved two concurrent rounds
|
||||
(directives-in-lists, dynamic-types).
|
||||
4. **Cross-module wants are filed, not done.** Write the request in your
|
||||
README's Handshakes, add it to §2.9 here, and stop — the lead routes it.
|
||||
Delivered requests get struck through in the filing README with a pointer
|
||||
(the ~~strikethrough~~ + "Delivered by X" convention is established).
|
||||
5. **Wire shapes and names are pinned by tests, so change them by test**:
|
||||
scopePairs JSON, the systemverilog fence tag, the seven `.vsix` names,
|
||||
the grammar/KEYWORDS lock, rule names, exit codes, message prefixes
|
||||
(§2.9-11 until structured output lands).
|
||||
6. **Anything touching formatter output**: attack tests for any
|
||||
verify-adjacent machinery, and a version bump or the format cache serves
|
||||
stale verdicts (§2.3).
|
||||
|
||||
---
|
||||
|
||||
*Maintenance: this file is derived documentation. When a feature round adds,
|
||||
delivers, or supersedes a handshake, update the relevant table (§2.9
|
||||
especially) in the same round, the way TODO.md checkboxes are kept current.*
|
||||
Reference in new issue
Block a user