Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7a934080a | ||
|
|
172a034c67 | ||
|
|
20567e1a7f | ||
|
|
17214ac8db | ||
|
|
d4eb8f48ff | ||
|
|
cf32e92e58 | ||
|
|
097498da23 | ||
|
|
4f7b4a9f91 | ||
|
|
574ab833e3 | ||
|
|
12d0bbad51 | ||
|
|
de8a7e129c | ||
|
|
611dd23069 | ||
|
|
a4f23db2c7 | ||
|
|
d94f9e3de0 | ||
|
|
94b130aca1 | ||
|
|
efe67bde65 |
No files matched your search
+148
@@ -4,6 +4,154 @@ 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.14.0 — 2026-08-28
|
||||
|
||||
The first-hover release: the owner's "hover is really slow on first
|
||||
try," traced to three costs and each one removed. Hover's steady state
|
||||
was already microseconds; now the firsts are too — or as close as
|
||||
physics allows.
|
||||
|
||||
### The index carries every declaration's line
|
||||
|
||||
Each indexed declaration — modules, and ports/parameters through the
|
||||
same member entries — now records its line number(s), computed at index
|
||||
time for a `u32` per name (+68 KB over the 860-file corpus). A hover
|
||||
heading into a closed file costs zero I/O: it survives the file being
|
||||
deleted. The persisted facts format moved to 4; an older cache is
|
||||
discarded whole and rebuilt once (~175 ms on the corpus).
|
||||
|
||||
### Closed files are read once, not per hover
|
||||
|
||||
The snippet's one remaining read is served from a small bounded view
|
||||
cache (4 files / 8 MiB, newest kept, invalidated on every path that can
|
||||
change a file's text): a repeat hover into a 12 MB closed file goes
|
||||
5.8 ms → ~1 µs, and mean cross-file hover 40/157 µs → 4.7/12.9 µs.
|
||||
A stale view can only ever omit a snippet — the wrong-line guard is
|
||||
unchanged.
|
||||
|
||||
### The startup scan answers requests as it goes
|
||||
|
||||
A request sent right after `initialized` used to wait out the whole
|
||||
scan: 780 ms cold / 287 ms warm over 200 files. The scan now feeds the
|
||||
live index incrementally and drains the message queue between files —
|
||||
the first hover of a session answers in ~15 ms against the index so
|
||||
far, with the open file indexed first. One merge per drain (per-file
|
||||
merging measured quadratic: 11.7 s over 800 files), scans under 64
|
||||
files stay one-shot, only the startup scan answers mid-way so the
|
||||
request-order contract holds, and the finished index fingerprints
|
||||
byte-identical to the old all-at-once scan. Scan totals unchanged
|
||||
within noise.
|
||||
|
||||
## 0.13.1 — 2026-08-28
|
||||
|
||||
The F12-latency release: the two costs behind a slow jump out of a big
|
||||
open file, found by measurement and removed, plus a stack-safety hole
|
||||
closed.
|
||||
|
||||
### References stop sweeping the open buffer
|
||||
|
||||
The open-document overlay in find-references did index lookups for
|
||||
every reference in every open buffer. A spelled-name prefilter and a
|
||||
hoisted file lookup take a 70 000-reference open `top.sv` from 3.2 ms
|
||||
to **0.11 ms** per request, both directions; in-file references and
|
||||
occurrence highlighting on a heavily used signal drop ~40 %. Answers
|
||||
are byte-identical — the old refactor walk remains the tested oracle.
|
||||
|
||||
### A rescan reuses what open buffers already analyzed
|
||||
|
||||
Jumping into a folder the index scope had not reached triggered a
|
||||
rescan that re-parsed every open buffer's text twice — once for index
|
||||
facts, once for completion words. Both now come from the analysis the
|
||||
buffer already holds (one implementation per path, byte-identical facts
|
||||
pinned over the corpus): the folder-widening jump drops from **228 ms
|
||||
to 23 ms**, and didSave's incremental update rides the same reuse.
|
||||
|
||||
### The stack now fits the nesting limit by construction
|
||||
|
||||
The parser's 64-level nesting limit only turns over-deep input into an
|
||||
error on a stack big enough to reach level 64 — an assumption that had
|
||||
drifted out from under the 2026-08 measurement (~94 KiB per level in
|
||||
debug under rustc 1.97; a default 2 MiB thread aborted near level 30).
|
||||
`PARSE_STACK_SIZE` (16 MiB) is now applied at every parse-reaching
|
||||
thread, both binaries' work included — the CLI previously aborted under
|
||||
a 1 MiB main stack (`ulimit`, win32 default) on 500 nested `begin`s and
|
||||
now emits an ordinary diagnostic. Deep-nesting suites across four
|
||||
crates pin it, sabotage-verified.
|
||||
|
||||
## 0.13.0 — 2026-08-28
|
||||
|
||||
Editor responsiveness, and hover for old-style ports.
|
||||
|
||||
### Typing costs one reanalysis, not one per keystroke
|
||||
|
||||
`didChange` no longer reparses and re-lints the buffer on every
|
||||
keystroke. The text the server holds is still exactly current after
|
||||
every notification; only the analysis is deferred, and it runs at the
|
||||
first moment anything needs it — the next request, the next
|
||||
non-`didChange` notification, or a 150 ms quiet period. A burst of ten
|
||||
keystrokes in a 10 000-line file therefore costs one 31 ms reanalysis
|
||||
instead of ten. The visible consequence: intermediate diagnostics
|
||||
states are no longer published, so squiggles for a half-typed line that
|
||||
was finished a moment later never appear. Every state that is published
|
||||
is one the buffer really passed through. Closing a file that was
|
||||
mid-edit discards its pending change instead of analyzing it, so it
|
||||
costs one publish — the one that clears its squiggles — and not two.
|
||||
|
||||
The one case this makes slower is a single keystroke followed by
|
||||
nothing at all: it now waits out the quiet period before publishing,
|
||||
164 ms instead of one reanalysis. Editors ask for something after every
|
||||
change — semantic tokens, inlay hints, highlights — and any request
|
||||
flushes the buffer before it is answered, so the latency a user
|
||||
actually meets is 4.4 ms in a 1 000-line file and 37.6 ms in a
|
||||
10 000-line one.
|
||||
|
||||
### Hover shows a non-ANSI port's real declaration
|
||||
|
||||
A port declared the old way — named in the module header, completed in
|
||||
the body by `input signed [31:0] data_in;` — now hovers as two fenced
|
||||
sections: the header line, then the body declaration that carries the
|
||||
direction, the type and the width. Go-to-definition offers both, the
|
||||
body declaration first. It works cross-file, into files that are not
|
||||
open, because the span travels through the workspace index. An
|
||||
old-style task or function argument (`task t(a);` finished by
|
||||
`input [7:0] a;`) reads the same way. Each section also carries every
|
||||
comment that documents it: the lines above it, the comment beside it,
|
||||
and the lines below it when nothing else could claim them — all three
|
||||
at once where all three are written.
|
||||
|
||||
### Faster hover and navigation
|
||||
|
||||
A hover into a closed file reads that file once instead of twice (34 ms
|
||||
→ 16.3 ms on a 31.7 MB file), and resolving a live declaration looks
|
||||
its name up instead of walking every symbol in the buffer. Measurements
|
||||
and how to reproduce them: `docs/perf/README.md`.
|
||||
|
||||
### Cursor-position answers stop walking the whole buffer
|
||||
|
||||
Expand-selection, on-type formatting, the completion scope gates and
|
||||
the inline template trigger each used to scan every token in the file
|
||||
to find the one at the cursor. They now binary-search for it: 77 µs →
|
||||
20 ns in a 10 000-line buffer, and 130 µs → 36 ns for the widest of
|
||||
them. No answer changed — each swap is pinned by a test that compares
|
||||
it against the scan it replaced at every byte of the buffer.
|
||||
|
||||
The persistent index cache's record format changed to carry the new
|
||||
span, so the first session after upgrading rebuilds its index rather
|
||||
than reading the old store.
|
||||
|
||||
## 0.12.1 — 2026-08-27
|
||||
|
||||
Hover shows the cross-file declaration itself. A name declared in
|
||||
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
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
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.
|
||||
@@ -573,6 +573,44 @@ later:
|
||||
written to a content-keyed store as a scan parses them, so the recompute a
|
||||
*new session* would otherwise repeat is skipped instead — 1.8x on a whole
|
||||
corpus rescan, and a scan interrupted halfway resumes where it stopped.
|
||||
**A third piece answered without salsa, 2026-08-28**
|
||||
(`docs/features/change-debounce/README.md`): the per-keystroke recompute a
|
||||
query graph would have made unnecessary is instead *not started* — a burst
|
||||
of `didChange`s is coalesced into one reanalysis. Still no query graph and
|
||||
no dependency tracking; the salsa question remains open and deferred.
|
||||
Measured costs for what a recompute actually is are now recorded in
|
||||
`docs/perf/README.md`. **Round 2, 2026-08-28**
|
||||
(`docs/features/interactive-latency/README.md`): that recompute is now
|
||||
broken down stage by stage, and 79 % of it is lexing and parsing. If the
|
||||
salsa question is ever reopened, that is the number it has to beat —
|
||||
incremental *lexing and parsing*, not incremental queries over a whole-file
|
||||
parse, and it lands squarely on `CLAUDE.md`'s hard invariants 1 and 2.
|
||||
**A fourth piece answered without salsa, 2026-08-28**
|
||||
(`docs/features/hover-line-index/README.md`): a derived fact a query used to
|
||||
recompute — the *line* a declaration is written on, which cost a whole file
|
||||
read and a whole `LineIndex` per request — is now computed once when the
|
||||
file is indexed and stored beside the span (`Def::lines`, `FACTS_FORMAT`
|
||||
3 → 4), and the one thing still needing that file's text is served from a
|
||||
small bounded cache of closed files. A repeat hover into a 12 MB closed file
|
||||
goes 5.75 ms → 0.95 µs; a whole scan is unchanged and the store grows 2.9 %.
|
||||
Still no query graph: what is cached is a value, invalidated at four named
|
||||
points, not a node in a dependency graph. **The larger number the same round
|
||||
measured is not an incrementality problem at all**: the first request of a
|
||||
session waits out the startup scan (780 ms cold, 287 ms warm), because
|
||||
`Server::new` scans before the message loop starts. Filed there, not fixed.
|
||||
→ **Fixed 2026-08-28** (`docs/features/scan-interleave/README.md`): the scan
|
||||
is now per-file steps with the message queue drained between them, so a
|
||||
startup scan of more than 64 files answers requests while it runs — 780 ms →
|
||||
**15.5 ms** cold, 287 ms → **12.8 ms** warm, with the scan's own total moving
|
||||
under a percent (860-file corpus: 351 → 353 ms cold, 187 → 189 ms warm). The
|
||||
merge cost was measured first and ruled per-file feeding out: a merge is a
|
||||
pass over the whole index, so one per file would have cost 631 ms of merging
|
||||
on 200 files against 464 ms of parsing. Records are staged per file and folded
|
||||
in with one `WorkspaceIndex::absorb` per *drain*, and a drain only happens
|
||||
when a message is waiting — so a scan nobody is waiting on pays nothing.
|
||||
Answers given mid-scan read the index as of that moment, and only the startup
|
||||
scan gives them: a request queued behind a message that asked for a rescan
|
||||
waits for that rescan, which is the order contract the loop always kept.
|
||||
- [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version
|
||||
bumped to 0.2.0 across the workspace and the extension, `tools/release.sh`
|
||||
(release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and
|
||||
@@ -610,6 +648,10 @@ section only tracks the milestones.
|
||||
**the open files' own folders since 2026-08-27 (index-scope), with the
|
||||
workspace walk behind `lucisv.index.scope: "workspace"`; the filelist
|
||||
still outranks both. See `docs/features/index-scope/README.md`.**
|
||||
**Since 2026-08-28 a rescan no longer re-parses the buffers it already
|
||||
analyzed** — an open buffer's index facts and completion words come from the
|
||||
analysis it holds — so a scope-widening `didOpen` with a 1.4 MB buffer open
|
||||
costs ~23 ms rather than ~228 ms.
|
||||
- [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.
|
||||
@@ -721,6 +763,18 @@ and are not gaps.
|
||||
publish — per notification. Advertised as `TextDocumentSyncOptions`
|
||||
with the open/close and `save.includeText: false` values a bare `Kind`
|
||||
already implied, so no client's save behavior moved.
|
||||
**Amended 2026-08-28** (`docs/features/change-debounce/README.md`): a
|
||||
`didChange` now only records the composed text; the reparse, the
|
||||
generation bump and the publish happen at the next *flush* — the next
|
||||
request, the next non-`didChange` notification, or a 150 ms quiet period —
|
||||
so a typing burst costs one of each instead of one per keystroke. The
|
||||
buffer's text is still exactly current after every notification; only its
|
||||
analysis is deferred, and intermediate diagnostics states are no longer
|
||||
published. **Measured 2026-08-28**
|
||||
(`docs/features/interactive-latency/README.md`): a burst of ten keystrokes
|
||||
over the wire produces exactly one `publishDiagnostics`, and a keystroke a
|
||||
request follows — the shape a real editor sends — round-trips in 4.8 ms at
|
||||
1 000 lines and 37 ms at 10 000.
|
||||
- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native
|
||||
format-on-save hook (client-side `editor.formatOnSave` already works;
|
||||
this serves the editors without it).
|
||||
@@ -780,6 +834,11 @@ and are not gaps.
|
||||
persistent index cache logs `cached:` rather than `indexing:` and is counted
|
||||
in the `end` message — `860 files indexed, 860 from cache` — so a rescan that
|
||||
flew past says why.
|
||||
→ **Extended once more, 2026-08-28**
|
||||
(`docs/features/index-scope/README.md`): a file that went into the index from
|
||||
an open buffer's own finished analysis — no parse, no store — logs
|
||||
`analyzed:` and adds nothing to the `end` message, so "from cache" still
|
||||
means the persistent store alone.
|
||||
→ **The other half of the size story, 2026-08-27**
|
||||
(`docs/features/large-file-mode/README.md`): the walk cap covers files
|
||||
nobody opened, and `lucisv.largeFile.threshold` (4 MiB) now covers the file
|
||||
|
||||
+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");
|
||||
|
||||
@@ -24,7 +24,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
|
||||
@@ -71,14 +71,28 @@ 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 {
|
||||
///
|
||||
/// `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 = words_in(text);
|
||||
let words = match known.remove(path) {
|
||||
Some(words) => words,
|
||||
None => words_in(text),
|
||||
};
|
||||
for word in &words {
|
||||
*out.word_files.entry(word.clone()).or_default() += 1;
|
||||
}
|
||||
@@ -101,9 +115,30 @@ impl Candidates {
|
||||
/// so nothing else is re-lexed. The result is what a whole
|
||||
/// [`Candidates::build`] over the same files would have produced.
|
||||
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
|
||||
self.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);
|
||||
}
|
||||
|
||||
/// [`Candidates::update_words`] for a batch of files — the form a scan
|
||||
/// publishing what it has indexed so far uses.
|
||||
///
|
||||
/// One re-derivation of the two index tables for the whole batch rather
|
||||
/// than one per file: they are read off the index and nothing else, so
|
||||
/// doing it once at the end of the batch is doing it once with the same
|
||||
/// answer. The word table is patched per file exactly as it is there.
|
||||
pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec<String>)>) {
|
||||
for (path, words) in batch {
|
||||
self.set_words(&path, words);
|
||||
}
|
||||
self.units = units_of(index);
|
||||
self.macros = macros_of(index);
|
||||
self.set_words(path, words_in(text));
|
||||
}
|
||||
|
||||
/// Drop one file's contribution entirely.
|
||||
@@ -209,11 +244,26 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
/// orders of magnitude more identifier *tokens* than distinct identifiers
|
||||
/// (900k against 17k over this repo's corpus), and copying every one of them
|
||||
/// only to sort the copies away costs more than the lexing does.
|
||||
fn words_in(text: &str) -> Vec<String> {
|
||||
///
|
||||
/// `pub(crate)` because a scan lexes each file as it reaches it rather than in
|
||||
/// one pass at the end: no part of a scan may be longer than one file, or the
|
||||
/// message queue goes unanswered for the length of it
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(crate) fn words_in(text: &str) -> Vec<String> {
|
||||
// A file that does not lex contributes nothing rather than being guessed
|
||||
// at with a regex — the same all-or-nothing rule the lexer gives every
|
||||
// other consumer.
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
words_of_tokens(&tokens)
|
||||
}
|
||||
|
||||
/// [`words_in`] over a token stream the caller already lexed.
|
||||
///
|
||||
/// The whole of `words_in` after the lex, so a caller holding an open buffer's
|
||||
/// tokens gets the same words without lexing the buffer again. A buffer that
|
||||
/// did not lex holds no tokens and contributes nothing here either, which is
|
||||
/// the same all-or-nothing rule from the other side.
|
||||
pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
|
||||
if !seen.contains(token.text.as_str()) {
|
||||
@@ -289,7 +339,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]
|
||||
@@ -408,7 +458,7 @@ mod tests {
|
||||
];
|
||||
let srcs = sources(&raw);
|
||||
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut candidates = Candidates::build(&index, &srcs);
|
||||
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
|
||||
assert_eq!(candidates.words("shared").len(), 1, "premise: two files, one word");
|
||||
|
||||
let mut current = index.clone();
|
||||
@@ -431,7 +481,7 @@ mod tests {
|
||||
let raw = [("/rtl/a.sv", "module a;\n logic w1;\nendmodule\n")];
|
||||
let srcs = sources(&raw);
|
||||
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut candidates = Candidates::build(&index, &srcs);
|
||||
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
|
||||
|
||||
let mut current = index.clone();
|
||||
let text2 = "module a;\n logic w2;\nendmodule\n";
|
||||
|
||||
@@ -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,
|
||||
|
||||
+1167
-18
File diff suppressed because it is too large.
Load diff
@@ -144,6 +144,30 @@ impl IncludeGraph {
|
||||
};
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
|
||||
/// the scope resolves to right now — the form a scan publishing what it
|
||||
/// has indexed so far uses.
|
||||
///
|
||||
/// `known` is the scan's whole work list rather than the files it has
|
||||
/// reached, so the known-file and folded-spelling tables are complete from
|
||||
/// the first publish: which files *exist* is settled the moment the scope
|
||||
/// is resolved, and only the edges are discovered file by file. One
|
||||
/// `relearn` for the batch, for the same reason
|
||||
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
|
||||
/// its index tables once.
|
||||
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
|
||||
self.incdirs = incdirs.to_vec();
|
||||
self.relearn(known);
|
||||
for (path, text) in batch {
|
||||
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]) {
|
||||
|
||||
@@ -568,6 +568,76 @@ mod tests {
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_from_any_previous_facts_format_is_dropped_not_misread() {
|
||||
// Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT`
|
||||
// and `VERSION` — so the header's format field is the only thing that
|
||||
// can catch them. Written as a loop rather than against one number so
|
||||
// it cannot go stale the next time a record grows a field: it was
|
||||
// pinned at 2 for the `detail_span` bump (QA finding,
|
||||
// `docs/features/port-detail-spans/README.md`) and would have gone on
|
||||
// testing 2 forever.
|
||||
let dir = TempDir::new("factsformats");
|
||||
let file = dir.file("m.sv", M);
|
||||
let encoded = facts(&file, M).encode().expect("encodes");
|
||||
for format in 1..FACTS_FORMAT {
|
||||
let old_format_store = format!(
|
||||
"lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n",
|
||||
line(content_hash(M.as_bytes()), &encoded)
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), old_format_store).expect("write");
|
||||
let cache = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(
|
||||
cache.facts_for(&file, M).is_none(),
|
||||
"a format-{format} record must not be read as a format-{FACTS_FORMAT} one"
|
||||
);
|
||||
}
|
||||
|
||||
// And the belt to that brace: a record really written in the previous
|
||||
// format — this one is a format-3 record, which is today's minus the
|
||||
// two per-declaration line fields `hover-line-index` added — does not
|
||||
// decode as one of today's *even if* something served it past the
|
||||
// header. Field-shifting is what the length prefixes and the
|
||||
// end-of-record check exist to make impossible.
|
||||
let format_3 = strip_the_line_fields(&encoded);
|
||||
assert_ne!(format_3, encoded, "premise: the fixture has a declaration to strip");
|
||||
assert!(
|
||||
FileFacts::decode(&format_3).is_none(),
|
||||
"a format-3 record decoded as a format-4 one: {format_3}"
|
||||
);
|
||||
|
||||
// Finally, the store is replaced under this build's header rather than
|
||||
// appended to, and reopening reads the fresh record back.
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.record(&facts(&file, M), M);
|
||||
let text = dir.store_text();
|
||||
assert!(
|
||||
text.starts_with(&header()),
|
||||
"the store was replaced under this build's header: {text}"
|
||||
);
|
||||
assert!(
|
||||
IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some(),
|
||||
"reopening reads the freshly written record back"
|
||||
);
|
||||
}
|
||||
|
||||
/// Today's encoded record, minus the two line fields every declaration
|
||||
/// gained in `FACTS_FORMAT` 4 — i.e. what format 3 wrote for the same
|
||||
/// file. `M` declares exactly one unit and no members, so the fields to
|
||||
/// drop are the two immediately after that unit's four span offsets.
|
||||
fn strip_the_line_fields(encoded: &str) -> String {
|
||||
let mut fields: Vec<&str> = encoded.split('\t').collect();
|
||||
let Some(units) = fields.iter().position(|f| *f == "U") else {
|
||||
return encoded.to_string();
|
||||
};
|
||||
// U, count, name, kind, name_span×2, detail×2, then the two lines.
|
||||
let lines_at = units + 8;
|
||||
if fields.len() > lines_at + 1 {
|
||||
fields.drain(lines_at..lines_at + 2);
|
||||
}
|
||||
fields.join("\t")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() {
|
||||
// The one shape `create_new` introduces: a zero-byte store, left by a
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
//! The workspace index deliberately keeps no file contents
|
||||
//! (`docs/features/workspace-index/README.md`), so a span in another file has
|
||||
//! to be converted against that file's text, fetched here with the same
|
||||
//! open-buffer-beats-disk precedence the index rebuild uses.
|
||||
//! open-buffer-beats-disk precedence the index rebuild uses — from the
|
||||
//! buffer's own line index when there is one, and otherwise through
|
||||
//! `Workspace::file_view`, which reads a closed file at most once per
|
||||
//! generation of it rather than once per question about it.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Location;
|
||||
use vlog_parser::{LineIndex, TextRange};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
@@ -17,17 +20,28 @@ use crate::uri::path_to_uri;
|
||||
/// The location of a byte span inside a workspace file.
|
||||
pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location> {
|
||||
let uri = path_to_uri(path)?;
|
||||
let text = ws.text_of(path)?;
|
||||
let index = LineIndex::new(&text);
|
||||
let range = Positions::new(&text, &index).range(span);
|
||||
Some(Location { uri, range })
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(Location { uri, range: doc.positions().range(span) });
|
||||
}
|
||||
let view = ws.file_view(path)?;
|
||||
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
|
||||
}
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
/// An open buffer answers from the line index it already carries; a closed
|
||||
/// file answers from the shared view cache. **An indexed declaration should
|
||||
/// not come here at all** — `Def::lines` already holds its line, recorded when
|
||||
/// the file was indexed, and that answer costs nothing
|
||||
/// (`docs/features/hover-line-index/README.md`). What is left for this
|
||||
/// function is the spans the index records no line for, which today is a
|
||||
/// `` `define``'s.
|
||||
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
let text = ws.text_of(path)?;
|
||||
Some(LineIndex::new(&text).line_col(offset).0)
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(doc.line_index.line_col(offset).0);
|
||||
}
|
||||
Some(ws.file_view(path)?.lines.line_col(offset).0)
|
||||
}
|
||||
|
||||
/// How a file is named in hover text: its file name, which is what a Verilog
|
||||
|
||||
@@ -29,6 +29,8 @@ mod locate;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
#[cfg(test)]
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod selection;
|
||||
@@ -62,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;
|
||||
|
||||
@@ -94,7 +98,19 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
Server::new(connection, roots, abilities, storage).run()?;
|
||||
// The message loop parses every buffer it is handed, so it does not run
|
||||
// on the main thread: that stack is whatever the OS and `ulimit -s` left
|
||||
// it, and the parser's nesting limit only turns over-deep input into a
|
||||
// diagnostic above `PARSE_STACK_SIZE` (below it the overflow aborts the
|
||||
// whole server, taking the editor session with it). Nothing else here
|
||||
// parses — `lsp-server`'s reader and writer threads move JSON, and the
|
||||
// forwarder in `Server::queue` moves messages.
|
||||
std::thread::Builder::new()
|
||||
.name("lucisv-main".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || Server::new(connection, roots, abilities, storage).run())?
|
||||
.join()
|
||||
.map_err(|_| "the server thread panicked")??;
|
||||
io_threads.join()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+443
-12
@@ -31,7 +31,19 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
}
|
||||
match path_to_uri_or_self(ws, uri) {
|
||||
Some(target) => {
|
||||
vec![Location { uri: target, range: doc.positions().range(symbol.name_span) }]
|
||||
let positions = doc.positions();
|
||||
// A non-ANSI port's *complete* declaration is the body
|
||||
// `input wire clk;`, so that is where a jump lands first —
|
||||
// the header name it jumped from stays second, exactly the
|
||||
// two sections its hover card shows.
|
||||
let mut locations = Vec::with_capacity(2);
|
||||
if let Some(detail) = symbol.detail_span.filter(|span| !span.is_empty()) {
|
||||
locations
|
||||
.push(Location { uri: target.clone(), range: positions.range(detail) });
|
||||
}
|
||||
locations
|
||||
.push(Location { uri: target, range: positions.range(symbol.name_span) });
|
||||
locations
|
||||
}
|
||||
None => Vec::new(),
|
||||
}
|
||||
@@ -157,13 +169,31 @@ fn indexed_target(ws: &Workspace, doc: &Document, offset: u32) -> Option<Indexed
|
||||
///
|
||||
/// Matching is logical (path, owner, name and kind), not positional: edits
|
||||
/// above a declaration may move its live span before the next save.
|
||||
fn indexed_def_for_symbol<'a>(
|
||||
///
|
||||
/// 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,
|
||||
symbol: &Symbol,
|
||||
) -> Option<&'a Def> {
|
||||
let path = doc.path.as_deref()?;
|
||||
let file = ws.index().file_id(path)?;
|
||||
let file = ws.index().file_id(doc.path.as_deref()?)?;
|
||||
indexed_def_in_file(ws, doc, symbol, file)
|
||||
}
|
||||
|
||||
/// [`indexed_def_for_symbol`] with the document's own [`FileId`] already in
|
||||
/// hand.
|
||||
///
|
||||
/// Split out for `indexed_references`, which asks about every reference in one
|
||||
/// buffer: the path lookup is a binary search whose comparisons are whole path
|
||||
/// `cmp`s, and it answers the same thing for all of them.
|
||||
fn indexed_def_in_file<'a>(
|
||||
ws: &'a Workspace,
|
||||
doc: &Document,
|
||||
symbol: &Symbol,
|
||||
file: vlog_semantic::FileId,
|
||||
) -> Option<&'a Def> {
|
||||
let defs = if symbol.scope == doc.semantics.file_scope() {
|
||||
ws.index().units(&symbol.name)
|
||||
} else {
|
||||
@@ -202,9 +232,27 @@ fn indexed_references(
|
||||
|
||||
for (_, doc) in ws.open_documents() {
|
||||
let Some(path) = doc.path.as_ref() else { continue };
|
||||
// Every reference in this buffer is answered against the same indexed
|
||||
// file, so the path lookup — a binary search comparing whole paths —
|
||||
// is taken once per buffer rather than once per reference.
|
||||
let file = ws.index().file_id(path);
|
||||
for (id, reference) in doc.semantics.references().iter().enumerate() {
|
||||
// A use can only name `target.def` if it spells the name that
|
||||
// declaration declares, and `target.name` is exactly that name.
|
||||
// One string compare replaces two index lookups and a scope walk
|
||||
// for every *other* name in the buffer, which in a big top is all
|
||||
// but a handful of them. The argument that this changes no answer
|
||||
// is in `docs/features/references-nav/README.md`. The empty-span
|
||||
// check below is deliberately *not* hoisted here: an ambiguous use
|
||||
// aborts the whole collection whether or not it has a span.
|
||||
if reference.name != target.name {
|
||||
continue;
|
||||
}
|
||||
let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) {
|
||||
Some(symbol) => indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def),
|
||||
Some(symbol) => {
|
||||
file.and_then(|file| indexed_def_in_file(ws, doc, symbol, file))
|
||||
== Some(&target.def)
|
||||
}
|
||||
None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) {
|
||||
Some(ExternalTarget::Resolved(def)) => def == &target.def,
|
||||
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(&target.def) => {
|
||||
@@ -223,11 +271,15 @@ fn indexed_references(
|
||||
let span = ws
|
||||
.document_for_path(&target.declaration_path)
|
||||
.and_then(|doc| {
|
||||
doc.semantics.symbols().iter().find_map(|symbol| {
|
||||
(symbol.name == target.name
|
||||
&& indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def))
|
||||
.then_some(symbol.name_span)
|
||||
})
|
||||
// Same name-keyed lookup `hover.rs::live_symbol` makes, for
|
||||
// the same reason: only same-named declarations can be this
|
||||
// one, and the order they come in is declaration order either
|
||||
// way, so the first match is unchanged.
|
||||
doc.semantics
|
||||
.symbols_named(&target.name)
|
||||
.filter_map(|id| doc.semantics.symbol(id))
|
||||
.find(|symbol| indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def))
|
||||
.map(|symbol| symbol.name_span)
|
||||
})
|
||||
.unwrap_or(target.declaration_span);
|
||||
found.push((target.declaration_path, span));
|
||||
@@ -288,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()
|
||||
}
|
||||
|
||||
@@ -312,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(),
|
||||
@@ -358,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;
|
||||
@@ -597,6 +658,56 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member() {
|
||||
// A harder equivalence case than the one above: `W` is a module (a
|
||||
// *unit*, filed in `units`) and, spelled identically, a package
|
||||
// member (filed in `members`) — the prefilter's one string compare
|
||||
// must not let either bucket answer for the other. `top.sv` is also
|
||||
// edited live after opening, so the overlay's answer has to come from
|
||||
// the unsaved buffer, not the file `find_references`'s own oracle
|
||||
// would otherwise re-read from disk.
|
||||
let dir = temp_dir("xrefs_equivalence_unit_and_member");
|
||||
let w_mod = "module W;\nendmodule\n";
|
||||
let w_pkg = "package p;\n localparam W = 4;\nendpackage\n";
|
||||
let top_saved = "module top;\n W u_w ();\n wire [p::W-1:0] x;\nendmodule\n";
|
||||
for (name, text) in [("w.sv", w_mod), ("p.sv", w_pkg), ("top.sv", top_saved)] {
|
||||
fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let top_uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||||
// An unsaved edit: a second live instantiation of `W`, not yet saved.
|
||||
let top_live = "module top;\n W u_w ();\n W u_w2 ();\n wire [p::W-1:0] x;\nendmodule\n";
|
||||
ws.set_document(top_uri, top_live.to_string());
|
||||
let w_uri = path_to_uri(&dir.join("w.sv")).expect("uri");
|
||||
ws.set_document(w_uri.clone(), w_mod.to_string());
|
||||
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
|
||||
ws.set_document(p_uri.clone(), w_pkg.to_string());
|
||||
|
||||
// The module `W`: its declaration and both live instantiations, never
|
||||
// the package member spelled the same way.
|
||||
let module_offset = at(w_mod, "W");
|
||||
let indexed_module = references(&ws, &w_uri, module_offset, true);
|
||||
let walked_module =
|
||||
vlog_refactor::find_references(&ws.sources(), &dir.join("w.sv"), module_offset, true)
|
||||
.expect("the walk answers");
|
||||
assert_eq!(indexed_module, locations(&ws, walked_module));
|
||||
assert_eq!(indexed_module.len(), 3, "declaration + 2 live instantiations, not the member");
|
||||
|
||||
// The package member `W`: its declaration and the one qualified use,
|
||||
// never the module.
|
||||
let member_offset = at(w_pkg, "W");
|
||||
let indexed_member = references(&ws, &p_uri, member_offset, true);
|
||||
let walked_member =
|
||||
vlog_refactor::find_references(&ws.sources(), &dir.join("p.sv"), member_offset, true)
|
||||
.expect("the walk answers");
|
||||
assert_eq!(indexed_member, locations(&ws, walked_member));
|
||||
assert_eq!(indexed_member.len(), 2, "declaration + the one qualified use, not the module");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual indexed-navigation latency probe"]
|
||||
fn qa_indexed_references_latency_over_a_large_workspace() {
|
||||
@@ -644,6 +755,223 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// latency probes for a big open buffer
|
||||
//
|
||||
// `#[ignore]`d, asserting nothing about duration — the house shape from
|
||||
// `perf.rs`, whose `mean` they borrow so every number in this repo is
|
||||
// taken the same way. The numbers they print are recorded in
|
||||
// `docs/features/references-nav/README.md`.
|
||||
//
|
||||
// cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored \
|
||||
// --nocapture --test-threads=1
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A declaration small enough that nothing about it is the measurement.
|
||||
const PROBE_SUB: &str =
|
||||
"module sub (input logic clk, input logic [31:0] data_in);\nendmodule\n";
|
||||
|
||||
/// A big top level: `blocks` four-line blocks of ordinary RTL — a wire, an
|
||||
/// assign, a register and its update — then `instances` instantiations of
|
||||
/// `sub`. Every block declares two names and uses four, so ten thousand
|
||||
/// blocks is a forty-thousand-line file carrying tens of thousands of
|
||||
/// locally resolved references: exactly the buffer the open-document
|
||||
/// overlay in `indexed_references` has to walk past to answer anything.
|
||||
///
|
||||
/// One `acc` is used by every block, so the file also carries a *local*
|
||||
/// name with thousands of occurrences — the worst case for the in-file
|
||||
/// fallback, which converts one span at a time.
|
||||
///
|
||||
/// Its own generator rather than `perf::generated_module`'s, because that
|
||||
/// one instantiates nothing and a probe about instantiations needs some.
|
||||
fn generated_top(blocks: usize, instances: usize) -> String {
|
||||
let mut src = String::from(
|
||||
"module top (\n input logic clk,\n input logic rst_n,\n \
|
||||
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n \
|
||||
wire acc;\n assign acc = rst_n;\n",
|
||||
);
|
||||
for n in 0..blocks {
|
||||
src.push_str(&format!(
|
||||
" wire [31:0] w_{n};\n \
|
||||
assign w_{n} = data_in ^ {{32{{rst_n}}}} ^ {{32{{acc}}}};\n \
|
||||
reg [31:0] r_{n};\n always @(posedge clk) r_{n} <= w_{n};\n"
|
||||
));
|
||||
}
|
||||
for n in 0..instances {
|
||||
src.push_str(&format!(" sub u_{n} (.clk(clk), .data_in(data_in));\n"));
|
||||
}
|
||||
src.push_str(" assign data_out = data_in;\nendmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// Both directions of a cross-file references request, with a big buffer
|
||||
/// open — the owner's report of 2026-08-28, measured.
|
||||
#[test]
|
||||
#[ignore = "manual references-latency probe — see docs/features/references-nav/README.md"]
|
||||
fn qa_references_latency_with_a_big_open_top() {
|
||||
use std::hint::black_box;
|
||||
|
||||
let dir = temp_dir("refs_big_top");
|
||||
let top_text = generated_top(10_000, 4);
|
||||
let sub_path = dir.join("sub.sv");
|
||||
let top_path = dir.join("top.sv");
|
||||
fs::write(&sub_path, PROBE_SUB).expect("write");
|
||||
fs::write(&top_path, &top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let top_uri = path_to_uri(&top_path).expect("uri");
|
||||
let sub_uri = path_to_uri(&sub_path).expect("uri");
|
||||
ws.set_document(top_uri.clone(), top_text.clone());
|
||||
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
|
||||
|
||||
let use_site = at(&top_text, "sub u_0");
|
||||
let declaration = at(PROBE_SUB, "sub");
|
||||
let local = top_text.rfind("<= w_").expect("a local use") as u32 + 3;
|
||||
let common = top_text.rfind("{32{acc}}").expect("a use of acc") as u32 + 4;
|
||||
let references_in_top =
|
||||
ws.document(&top_uri).map(|doc| doc.semantics.references().len()).expect("top is open");
|
||||
|
||||
// The answers, before any timing: a measurement of a request that
|
||||
// answered nothing is worthless.
|
||||
assert_eq!(references(&ws, &top_uri, use_site, true).len(), 5, "declaration + 4 instances");
|
||||
assert_eq!(references(&ws, &sub_uri, declaration, true).len(), 5, "the same five");
|
||||
assert_eq!(definition(&ws, &top_uri, use_site).len(), 1);
|
||||
assert_eq!(references(&ws, &top_uri, local, true).len(), 3, "one wire, in this file only");
|
||||
assert_eq!(references(&ws, &top_uri, common, true).len(), 10_002, "`acc`, everywhere");
|
||||
|
||||
let runs = 20;
|
||||
let from_use = mean(runs, || {
|
||||
black_box(references(&ws, &top_uri, black_box(use_site), true));
|
||||
});
|
||||
let from_declaration = mean(runs, || {
|
||||
black_box(references(&ws, &sub_uri, black_box(declaration), true));
|
||||
});
|
||||
let to_definition = mean(runs, || {
|
||||
black_box(definition(&ws, &top_uri, black_box(use_site)));
|
||||
});
|
||||
let in_file = mean(runs, || {
|
||||
black_box(references(&ws, &top_uri, black_box(local), true));
|
||||
});
|
||||
let in_file_common = mean(runs, || {
|
||||
black_box(references(&ws, &top_uri, black_box(common), true));
|
||||
});
|
||||
let highlights = mean(runs, || {
|
||||
let doc = ws.document(&top_uri).expect("open");
|
||||
black_box(document_highlights(doc, black_box(common)));
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"big open top ({} KB, {references_in_top} references): \
|
||||
references from the use site {from_use:?}, \
|
||||
from the declaration {from_declaration:?}, \
|
||||
definition from the use site {to_definition:?}, \
|
||||
references on a local wire used 3× (the in-file fallback) {in_file:?}, \
|
||||
on one used 10 001× {in_file_common:?}, \
|
||||
documentHighlight on that one {highlights:?}",
|
||||
top_text.len() / 1000,
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The other half of the owner's report: what jumping *into* a file costs
|
||||
/// when the folder it lives in was not in the index's scope yet.
|
||||
#[test]
|
||||
#[ignore = "manual didOpen/scope-widening latency probe — see docs/features/references-nav/README.md"]
|
||||
fn qa_didopen_latency_when_a_new_folder_widens_the_scope() {
|
||||
use std::hint::black_box;
|
||||
|
||||
let dir = temp_dir("didopen_scope");
|
||||
fs::create_dir_all(dir.join("rtl")).expect("rtl dir");
|
||||
fs::create_dir_all(dir.join("lib")).expect("lib dir");
|
||||
for n in 0..400 {
|
||||
fs::write(
|
||||
dir.join("rtl").join(format!("m{n}.sv")),
|
||||
format!("module m{n};\n wire w;\n assign w = 1'b0;\nendmodule\n"),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
fs::write(dir.join("lib").join("sub.sv"), PROBE_SUB).expect("write");
|
||||
let top_text = generated_top(10_000, 4);
|
||||
let top_path = dir.join("rtl").join("top.sv");
|
||||
fs::write(&top_path, &top_text).expect("write");
|
||||
|
||||
// The default rung: the folder scope. Nothing is in scope until a
|
||||
// buffer is opened, so the first `didOpen` is itself a widening.
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let top_uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(top_uri.clone(), top_text.clone());
|
||||
ws.rebuild_index();
|
||||
let covered = ws.index().files().len();
|
||||
|
||||
// A `didOpen` the scope already covers: one `Document::new` and a
|
||||
// publish, and `server.rs` runs no rescan at all.
|
||||
let sibling = dir.join("rtl").join("m0.sv");
|
||||
let sibling_uri = path_to_uri(&sibling).expect("uri");
|
||||
let sibling_text = fs::read_to_string(&sibling).expect("read");
|
||||
let inside = mean(20, || {
|
||||
ws.set_document(sibling_uri.clone(), sibling_text.clone());
|
||||
});
|
||||
|
||||
// A `didOpen` in a folder the scope does not cover: the same
|
||||
// `Document::new`, and then the whole rescan `server.rs` runs when
|
||||
// `scope_dirs()` moved — which re-reads and re-parses every file in
|
||||
// the widened scope. Until 2026-08-28 the open big buffer was one of
|
||||
// them; it now goes in from the analysis it already holds, which is
|
||||
// what the last two pairs of numbers below are about
|
||||
// (`docs/features/index-scope/README.md`).
|
||||
let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri");
|
||||
let widening = mean(5, || {
|
||||
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
|
||||
black_box(ws.rebuild_index());
|
||||
});
|
||||
let rescan = mean(5, || {
|
||||
black_box(ws.rebuild_index());
|
||||
});
|
||||
// Where the buffer's share goes, on the same buffer: what a rescan
|
||||
// used to pay for one open file — a whole parse for the index facts,
|
||||
// then a second lex for the completion words — against what it pays
|
||||
// since 2026-08-28, which is the two walks over the analysis and the
|
||||
// token stream the buffer already holds.
|
||||
let (reparse, reused, relex, rewords) = {
|
||||
let doc = ws.document(&top_uri).expect("open");
|
||||
(
|
||||
mean(3, || {
|
||||
black_box(vlog_semantic::FileFacts::of(top_path.clone(), &top_text));
|
||||
}),
|
||||
mean(3, || {
|
||||
black_box(doc.facts(top_path.clone()));
|
||||
}),
|
||||
mean(3, || {
|
||||
let tokens = vlog_parser::tokenize(&top_text).expect("it lexes");
|
||||
black_box(crate::candidates::words_of_tokens(&tokens));
|
||||
}),
|
||||
mean(3, || {
|
||||
black_box(doc.words());
|
||||
}),
|
||||
)
|
||||
};
|
||||
|
||||
// The same rescan with the big buffer closed, so its share of the
|
||||
// rescan is a subtraction rather than a guess.
|
||||
ws.close_document(&top_uri);
|
||||
let without = mean(5, || {
|
||||
black_box(ws.rebuild_index());
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"didOpen with a {} KB buffer already open, {covered} files in scope: \
|
||||
a file the scope already covers {inside:?}; \
|
||||
one in a new folder (didOpen + rescan) {widening:?}; \
|
||||
the rescan alone {rescan:?}, and {without:?} with the big buffer closed. \
|
||||
That buffer's own share: facts {reparse:?} parsed vs {reused:?} reused, \
|
||||
words {relex:?} re-lexed vs {rewords:?} reused",
|
||||
top_text.len() / 1000,
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn include_declaration_drops_the_declaration_and_nothing_else() {
|
||||
let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv");
|
||||
@@ -751,6 +1079,109 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_named_port_in_another_open_buffer_is_a_different_symbol() {
|
||||
// The name prefilter's risk case, asserted from both sides: two
|
||||
// modules declare a port `clk`, both files are open, and each port's
|
||||
// references are its own. A prefilter that let a spelling stand in for
|
||||
// an identity would merge these two answers.
|
||||
let dir = temp_dir("xrefs_same_name");
|
||||
let sub = "module sub (input logic clk);\nendmodule\n";
|
||||
let top = "module top;\n sub u_a (.clk(1'b0));\nendmodule\n";
|
||||
let other = "module other (input logic clk);\n wire w;\n assign w = clk;\nendmodule\n";
|
||||
for (name, text) in [("sub.sv", sub), ("top.sv", top), ("other.sv", other)] {
|
||||
fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let mut uri_of = |name: &str, text: &str| {
|
||||
let uri = path_to_uri(&dir.join(name)).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
uri
|
||||
};
|
||||
let sub_uri = uri_of("sub.sv", sub);
|
||||
uri_of("top.sv", top);
|
||||
let other_uri = uri_of("other.sv", other);
|
||||
|
||||
assert_eq!(
|
||||
places(&references(&ws, &sub_uri, at(sub, "clk"), true)),
|
||||
vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)],
|
||||
"`sub`'s port: its declaration and the connection to it"
|
||||
);
|
||||
assert_eq!(
|
||||
places(&references(&ws, &other_uri, at(other, "clk"), true)),
|
||||
vec![("other.sv".to_string(), 0), ("other.sv".to_string(), 2)],
|
||||
"`other`'s port: its declaration and its own use"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_packages_declaring_one_name_keep_their_references_apart() {
|
||||
// The same attack through the member table rather than the port table:
|
||||
// `p::WIDTH` and `q::WIDTH` spell one name and are two declarations,
|
||||
// and the file using both is open.
|
||||
let dir = temp_dir("xrefs_two_packages");
|
||||
let p = "package p;\n localparam WIDTH = 8;\nendpackage\n";
|
||||
let q = "package q;\n localparam WIDTH = 16;\nendpackage\n";
|
||||
let a = "module a;\n wire [p::WIDTH-1:0] x;\n wire [q::WIDTH-1:0] y;\nendmodule\n";
|
||||
for (name, text) in [("p.sv", p), ("q.sv", q), ("a.sv", a)] {
|
||||
fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri");
|
||||
ws.set_document(a_uri.clone(), a.to_string());
|
||||
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
|
||||
ws.set_document(p_uri.clone(), p.to_string());
|
||||
|
||||
assert_eq!(
|
||||
places(&references(&ws, &p_uri, at(p, "WIDTH"), true)),
|
||||
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)],
|
||||
"`p`'s WIDTH only — `q::WIDTH` on the next line is another symbol"
|
||||
);
|
||||
// And from the use side, the same set.
|
||||
assert_eq!(
|
||||
places(&references(&ws, &a_uri, at(a, "p::WIDTH") + 3, true)),
|
||||
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)]
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_in_file_occurrence_is_converted_against_its_own_line() {
|
||||
// The in-file fallback converts its spans with one walker now. A
|
||||
// walker handed an out-of-order span answers a stale column, so the
|
||||
// shape that would catch it: many occurrences, each on a line with a
|
||||
// wide character before it, plus one on the same line as another.
|
||||
let mut text = String::from("module m;\n wire a;\n");
|
||||
for n in 0..20 {
|
||||
text.push_str(&format!(" // é 🎉 {n}\n assign b{n} = a + a;\n"));
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
let (ws, uri) = document(&text);
|
||||
let found = references(&ws, &uri, at(&text, "wire a") + 5, true);
|
||||
assert_eq!(found.len(), 41, "the declaration and two uses per block");
|
||||
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let positions = doc.positions();
|
||||
for location in &found {
|
||||
let line = location.range.start.line as usize;
|
||||
let offset = positions.offset(location.range.start);
|
||||
assert_eq!(
|
||||
text.get(offset as usize..offset as usize + 1),
|
||||
Some("a"),
|
||||
"line {line} must point at the name"
|
||||
);
|
||||
assert_eq!(location.range.end.character, location.range.start.character + 1);
|
||||
}
|
||||
|
||||
// documentHighlight walks the same list and must agree with it.
|
||||
let highlights = document_highlights(doc, at(&text, "wire a") + 5).expect("a symbol");
|
||||
let ranges: Vec<_> = highlights.iter().map(|h| h.range).collect();
|
||||
assert_eq!(ranges, found.iter().map(|l| l.range).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() {
|
||||
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv");
|
||||
|
||||
@@ -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,503 @@
|
||||
//! 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
|
||||
// comes from the index (`Def::lines`, no read at all) and its snippet from
|
||||
// the workspace's shared view of that file — read once, then held. This
|
||||
// is a *mean of twenty*, so nineteen of the runs are the held case: it is
|
||||
// the steady-state hover, not the first touch (which
|
||||
// `hovering_into_a_big_closed_file_first_touch_and_repeat` reports on its
|
||||
// own). Measured beside it is the read the first touch pays and every
|
||||
// later one does not.
|
||||
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 only the first touch pays)"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::hovering_into_a_big -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn hovering_into_a_big_closed_file_first_touch_and_repeat() {
|
||||
// The owner's report, measured: hovering an *instantiation* and hovering
|
||||
// one of its *ports* into a closed file that is big — the netlist-adjacent
|
||||
// shape a real workspace has one of. Two numbers per hover: the first
|
||||
// touch of that file in the session, and the touch after it, which is the
|
||||
// one a text cache can make free.
|
||||
//
|
||||
// "First touch" is cold to *this process* and to nothing else: the file
|
||||
// was written moments ago, so the OS page cache still holds it and the
|
||||
// read below is the cheap kind. A genuinely cold disk is worse than this,
|
||||
// never better.
|
||||
let sub = big_module("sub", 12_000_000);
|
||||
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
|
||||
let dir = scratch("bighover", &[("sub.sv", sub.as_str()), ("top.sv", top)]);
|
||||
let uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||||
let instantiation = top.find("sub u").expect("an instantiation") as u32;
|
||||
let port = top.find("data_in(").expect("a port connection") as u32;
|
||||
|
||||
for (what, offset) in [("instantiation", instantiation), ("port", port)] {
|
||||
// A fresh workspace per measurement, so "first touch" really is one.
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
max_file_size: 100_000_000,
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
|
||||
let start = Instant::now();
|
||||
let card = hover(&ws, &uri, black_box(offset)).expect("a cross-file card");
|
||||
let first = start.elapsed();
|
||||
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
|
||||
let repeat = mean(10, || {
|
||||
black_box(hover(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
eprintln!(
|
||||
"hover on a {what} into a {:.1} MB closed file: first touch {first:?}, \
|
||||
repeat {repeat:?}",
|
||||
sub.len() as f64 / 1_000_000.0
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A module of at least `bytes` bytes: a small ANSI header — the declaration a
|
||||
/// hover actually lands on — behind a wall of filler lines, which is the shape
|
||||
/// of the files the owner's report is about.
|
||||
fn big_module(name: &str, bytes: usize) -> String {
|
||||
let mut src = format!("module {name} (\n input logic [31:0] data_in\n);\n");
|
||||
let mut n = 0;
|
||||
while src.len() < bytes {
|
||||
src.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n"));
|
||||
n += 1;
|
||||
}
|
||||
src.push_str("endmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// `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::what_a_scan -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn what_a_scan_does_before_its_first_file() {
|
||||
// The floor under a mid-scan answer's latency. A scan answers messages
|
||||
// between two *files*, so whatever it does before the first one is a
|
||||
// block no drain can break up: resolving the scope, reading every
|
||||
// in-scope file, and opening the persistent store. Measured because
|
||||
// `docs/features/scan-interleave/README.md` files "read the files lazily"
|
||||
// as a deliberate not-done, and a not-done is only honest with a number.
|
||||
let files: Vec<(String, String)> =
|
||||
(0..200).map(|n| (format!("m{n}.sv"), generated_module(&format!("m{n}"), 1_000))).collect();
|
||||
let refs: Vec<(&str, &str)> =
|
||||
files.iter().map(|(name, text)| (name.as_str(), text.as_str())).collect();
|
||||
let dir = scratch("scanhead", &refs);
|
||||
let mut workspace = Workspace::default();
|
||||
workspace.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
workspace.adopt_roots(vec![dir.clone()]);
|
||||
let started = Instant::now();
|
||||
let mut scan = workspace.begin_scan(&mut |_| {});
|
||||
let head = started.elapsed();
|
||||
let started = Instant::now();
|
||||
workspace.scan_step(&mut scan, &mut |_| {});
|
||||
let one = started.elapsed();
|
||||
let started = Instant::now();
|
||||
while workspace.scan_step(&mut scan, &mut |_| {}) {}
|
||||
let rest = started.elapsed();
|
||||
let started = Instant::now();
|
||||
workspace.finish_scan(scan);
|
||||
let tail = started.elapsed();
|
||||
eprintln!(
|
||||
"scan of {} files of 1k lines: before the first file {head:?}, \
|
||||
one file {one:?}, the other {} {rest:?}, finishing {tail:?}",
|
||||
files.len(),
|
||||
files.len() - 1
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::publishing -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn publishing_a_half_built_index_mid_scan() {
|
||||
// What an interleaved scan's *publish* costs, against the per-file work it
|
||||
// is interleaved with. `docs/features/scan-interleave/README.md` chose the
|
||||
// publish rhythm from these numbers: a merge is a whole-index pass, so one
|
||||
// per file would be quadratic and one per drain is not.
|
||||
for files in [50usize, 200, 800] {
|
||||
let sources: Vec<(PathBuf, String)> = (0..files)
|
||||
.map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), 1_000)))
|
||||
.collect();
|
||||
let records: Vec<vlog_semantic::FileFacts> = sources
|
||||
.iter()
|
||||
.map(|(path, src)| vlog_semantic::FileFacts::of(path.clone(), src))
|
||||
.collect();
|
||||
let parse = mean(3, || {
|
||||
let (path, src) = &sources[0];
|
||||
black_box(vlog_semantic::FileFacts::of(black_box(path.clone()), black_box(src)));
|
||||
});
|
||||
let build = mean(3, || {
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
for facts in &records {
|
||||
builder.add_facts(facts.clone());
|
||||
}
|
||||
black_box(builder.finish());
|
||||
});
|
||||
let clone = mean(3, || {
|
||||
black_box(records.clone());
|
||||
});
|
||||
let index = WorkspaceIndex::build(
|
||||
sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::<Vec<_>>(),
|
||||
);
|
||||
let held = mean(10, || {
|
||||
let mut index = index.clone();
|
||||
index.update_facts(black_box(records[files / 2].clone()));
|
||||
black_box(index);
|
||||
});
|
||||
let index_clone = mean(10, || {
|
||||
black_box(index.clone());
|
||||
});
|
||||
eprintln!(
|
||||
"{files} files of 1k lines: one file's parse {parse:?}; \
|
||||
one whole merge {:?} (build {build:?} less {clone:?} of record cloning); \
|
||||
one update_facts on a held file {:?} (less {index_clone:?} of index cloning); \
|
||||
per-file feeding would cost {:?} of merging against {:?} of parsing",
|
||||
build.saturating_sub(clone),
|
||||
held.saturating_sub(index_clone),
|
||||
held.saturating_sub(index_clone) * files as u32,
|
||||
parse * files as u32,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
+1057
-115
File diff suppressed because it is too large.
Load diff
+1452
-37
File diff suppressed because it is too large.
Load diff
@@ -2221,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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3055,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
|
||||
@@ -3386,6 +3400,89 @@ fn the_size_cap_and_the_file_log_work_over_the_wire() {
|
||||
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");
|
||||
@@ -4592,3 +4689,235 @@ fn a_five_megabyte_buffer_opens_on_the_fast_path_over_the_wire() {
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server --test e2e a_hover_issued -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn a_hover_issued_during_the_initial_scan_is_answered_during_it() {
|
||||
// The probe the hover-latency round left behind, now measuring the other
|
||||
// side of the change it filed for. It used to read
|
||||
// `..._waits_for_it`, because `Server::new` ran the whole startup scan
|
||||
// *before* `run()`'s message loop took its first message and anything a
|
||||
// client sent the moment it had sent `initialized` sat in the OS pipe
|
||||
// until that scan was done: 780 ms cold / 287 ms warm over these 200
|
||||
// files. The scan now answers messages between its files
|
||||
// (`docs/features/scan-interleave/README.md`), so what this prints is
|
||||
// one file's step and not a whole scan.
|
||||
//
|
||||
// A `lucisv.toml` naming a filelist is what makes the startup scan index
|
||||
// the whole tree: it is the top rung of the scope ladder and the only one
|
||||
// that answers before any buffer has been opened.
|
||||
let dir = temp_dir("firsthover");
|
||||
let files = 200usize;
|
||||
let mut list = String::new();
|
||||
for n in 0..files {
|
||||
let name = format!("m{n}.sv");
|
||||
std::fs::write(dir.join(&name), generated_module(&format!("m{n}"), 1_000)).expect("write");
|
||||
list.push_str(&format!("{name}\n"));
|
||||
}
|
||||
std::fs::write(dir.join("files.f"), &list).expect("write");
|
||||
let top = "module top;\n m7 u (.data_in(32'h0));\nendmodule\n";
|
||||
let top_path = dir.join("top.sv");
|
||||
std::fs::write(&top_path, top).expect("write");
|
||||
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write");
|
||||
// `top.sv` is not in the filelist, so it is not indexed — but it is what
|
||||
// the hover is *issued from*, and a buffer is indexed by being opened.
|
||||
std::fs::write(dir.join("files.f"), format!("{list}top.sv\n")).expect("write");
|
||||
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", top_path.display());
|
||||
let hover = |id: u32| {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
|
||||
)
|
||||
};
|
||||
|
||||
// Two whole sessions over the same storage folder: the first fills the
|
||||
// persistent index cache, the second reads it. Both are measured, because
|
||||
// "does the cache fix this?" is the second half of the question — it makes
|
||||
// the scan cheaper, and the first hover still waits out whatever is left.
|
||||
let mut took = Vec::new();
|
||||
for session in 0..2 {
|
||||
let mut live = Live::start();
|
||||
// The progress capability is what makes "the scan is over" observable
|
||||
// to the client, and therefore to the second measurement below.
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}},"initializationOptions":{{"storagePath":"{}"}}}}}}"#,
|
||||
dir.join("storage").display()
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
|
||||
// Everything a client sends the instant the handshake is done, in one
|
||||
// go — which is exactly what VS Code does with the editor already open.
|
||||
let started = std::time::Instant::now();
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(top).expect("json")
|
||||
));
|
||||
live.send(&hover(2));
|
||||
live.wait_for(|m| m["id"] == 2);
|
||||
let queued_behind_the_scan = started.elapsed();
|
||||
|
||||
// The same hover, with the scan long finished — which is where the
|
||||
// cross-file answer is required, because *that* one reads a finished
|
||||
// index. The mid-scan one above reads the index as of the moment it
|
||||
// was asked, and `m7.sv` sorts a long way down 200 paths.
|
||||
live.wait_for(|m| m["params"]["value"]["kind"] == "end");
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&hover(3));
|
||||
let done = live.wait_for(|m| m["id"] == 3);
|
||||
let after_the_scan = started.elapsed();
|
||||
assert!(
|
||||
format!("{done:#?}").contains("m7.sv"),
|
||||
"the hover must really answer across files once the scan is done: {done:#?}"
|
||||
);
|
||||
|
||||
live.finish();
|
||||
took.push((session, queued_behind_the_scan, after_the_scan));
|
||||
}
|
||||
for (session, behind, after) in took {
|
||||
let store = if session == 0 { "cold store" } else { "warm store" };
|
||||
eprintln!(
|
||||
"hover issued the moment `initialized` was sent, over {files} files of 1k lines \
|
||||
({store}): {behind:?}; the same hover once the scan is done: {after:?}"
|
||||
);
|
||||
}
|
||||
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()
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,13 +20,13 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::model::SymbolKind;
|
||||
use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact};
|
||||
use crate::workspace::{Decl, DeclLines, DeclSite, FileFacts, ReferenceFact, SiteFact};
|
||||
|
||||
/// The version of the encoding below. Bump it on **any** change to what a
|
||||
/// record holds or to how it is written: a store stamped with another number
|
||||
/// is discarded whole, which is the only way a reader can be sure it is not
|
||||
/// reading last month's field order as this month's.
|
||||
pub const FACTS_FORMAT: u32 = 2;
|
||||
pub const FACTS_FORMAT: u32 = 4;
|
||||
|
||||
impl FileFacts {
|
||||
/// These facts as one line's worth of fields, tab-separated.
|
||||
@@ -185,6 +185,25 @@ impl Writer {
|
||||
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);
|
||||
}
|
||||
}
|
||||
// The declaration's lines, on the same unconditional-pair rule: the
|
||||
// name's line, then the detail span's or `0` for the `None` above.
|
||||
// `FACTS_FORMAT` is bumped for these two fields, so a store written
|
||||
// before them is discarded rather than read short by two
|
||||
// (`docs/features/hover-line-index/README.md`).
|
||||
self.num(decl.lines.name);
|
||||
self.num(decl.lines.detail.unwrap_or(0));
|
||||
}
|
||||
|
||||
fn site(&mut self, site: &DeclSite) {
|
||||
@@ -298,7 +317,21 @@ impl<'a> Reader<'a> {
|
||||
fn decl(&mut self) -> Option<Decl> {
|
||||
let name = self.text()?;
|
||||
let kind = kind_of(self.next()?)?;
|
||||
Some(Decl { name, name_span: self.range()?, kind })
|
||||
let name_span = self.range()?;
|
||||
// The mirror of the encoder's unconditional pair: `(0, 0)` is the
|
||||
// `None`, and a real span can never be, because a declaration's span
|
||||
// is never empty.
|
||||
let start = self.num()?;
|
||||
let end = self.num()?;
|
||||
let detail_span = (start != 0 || end != 0).then_some(TextRange::new(start, end));
|
||||
// A line is 1-based, so `0` is the `None` here too — and a detail line
|
||||
// is present exactly when a detail span is, which a record written by
|
||||
// this format always agrees with.
|
||||
let name_line = self.num()?;
|
||||
let detail_line = self.num()?;
|
||||
let lines =
|
||||
DeclLines { name: name_line, detail: (detail_line != 0).then_some(detail_line) };
|
||||
Some(Decl { name, name_span, kind, detail_span, lines })
|
||||
}
|
||||
|
||||
fn site(&mut self) -> Option<DeclSite> {
|
||||
|
||||
@@ -31,9 +31,9 @@ pub use model::{
|
||||
SymbolId, SymbolKind,
|
||||
};
|
||||
pub use workspace::{
|
||||
index_order, resolve_external, DeclSite, Def, Definition, DefinitionKey, ExternalResolutions,
|
||||
ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge,
|
||||
InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
|
||||
index_order, resolve_external, DeclLines, DeclSite, Def, Definition, DefinitionKey,
|
||||
ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts,
|
||||
InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
|
||||
};
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -52,6 +52,12 @@ pub struct Semantics {
|
||||
symbol_positions: Vec<(TextRange, SymbolId)>,
|
||||
/// Non-empty reference-name spans, sorted by start for cursor lookup.
|
||||
reference_positions: Vec<(TextRange, ReferenceId)>,
|
||||
/// Every symbol id, sorted by the name it declares, ties in declaration
|
||||
/// order — so looking a name up is a binary search rather than a walk of
|
||||
/// every symbol. A side table rather than a `HashMap<String, _>` because
|
||||
/// this way `Semantics` does not carry a second copy of every name it
|
||||
/// already holds, and it is cloned per document.
|
||||
by_name: Vec<SymbolId>,
|
||||
}
|
||||
|
||||
/// Build the symbol table for one parsed file. `src` must be the text the
|
||||
@@ -97,7 +103,12 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
||||
.map(|(i, reference)| (reference.name_span, ReferenceId(i as u32)))
|
||||
.collect();
|
||||
reference_positions.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions }
|
||||
// A *stable* sort by name, so symbols sharing a name keep the order they
|
||||
// were declared in — the order a caller filtering `symbols()` by name
|
||||
// would have seen, which is what makes swapping the two an identity.
|
||||
let mut by_name: Vec<SymbolId> = (0..symbols.len() as u32).map(SymbolId).collect();
|
||||
by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name));
|
||||
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name }
|
||||
}
|
||||
|
||||
/// Point every import at the package it names, when this file declares it.
|
||||
@@ -145,6 +156,19 @@ impl Semantics {
|
||||
self.symbols.get(id.0 as usize)
|
||||
}
|
||||
|
||||
/// Every declaration that spells `name`, in declaration order — the same
|
||||
/// symbols, in the same order, that filtering [`Semantics::symbols`] by
|
||||
/// name yields, without walking the ones that cannot match.
|
||||
pub fn symbols_named(&self, name: &str) -> impl Iterator<Item = SymbolId> + '_ {
|
||||
// Two binary searches over the name-sorted side table: the first name
|
||||
// that is not less than the one asked for, then the first one past it.
|
||||
let spelling = |id: &SymbolId| self.symbol(*id).map_or("", |symbol| symbol.name.as_str());
|
||||
let start = self.by_name.partition_point(|id| spelling(id) < name);
|
||||
let rest = self.by_name.get(start..).unwrap_or(&[]);
|
||||
let end = rest.partition_point(|id| spelling(id) == name);
|
||||
rest.get(..end).unwrap_or(&[]).iter().copied()
|
||||
}
|
||||
|
||||
/// The declaration whose *name* covers `offset` — a cursor sitting on a
|
||||
/// declared name, not anywhere in its declaration.
|
||||
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::path::{Path, PathBuf};
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
|
||||
|
||||
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
|
||||
use crate::{analyze, classes, instantiations, Semantics};
|
||||
@@ -37,6 +37,48 @@ 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>,
|
||||
/// Which lines those spans fall on, read while the file was indexed.
|
||||
pub lines: DeclLines,
|
||||
}
|
||||
|
||||
/// Where a declaration sits in its file, counted in **lines**, computed when
|
||||
/// that file is indexed.
|
||||
///
|
||||
/// The index keeps no file text, so before this every `file:line` a server
|
||||
/// printed for an indexed declaration cost a read of the declaring file and a
|
||||
/// whole [`LineIndex`] over it — the thing a cross-file hover into a closed
|
||||
/// file was mostly spending its time on. A line is four bytes per declaration,
|
||||
/// a few tens of KB for a workspace of 20 000 modules, and it is the whole of
|
||||
/// what a heading needs.
|
||||
///
|
||||
/// **One value per declaration, so it extends by gaining a field.** Members
|
||||
/// are [`Decl`]s exactly as units are, so a module's ports already carry their
|
||||
/// own lines here; a column, or a rendered preview, is another field written
|
||||
/// beside these two — plus the [`crate::FACTS_FORMAT`] bump any change to a
|
||||
/// record owes — and not a second table to keep in step with this one.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct DeclLines {
|
||||
/// 1-based line the declared name is on.
|
||||
pub name: u32,
|
||||
/// 1-based line the `detail_span` starts on, `None` exactly when there is
|
||||
/// no detail span.
|
||||
pub detail: Option<u32>,
|
||||
}
|
||||
|
||||
impl DeclLines {
|
||||
/// The lines a declaration's spans fall on, read off its file's line
|
||||
/// index. 1-based, so `name` is what `LineIndex::line_col` reports and
|
||||
/// what a `file:line` prints.
|
||||
fn of(lines: &LineIndex, name_span: TextRange, detail_span: Option<TextRange>) -> DeclLines {
|
||||
DeclLines {
|
||||
name: lines.line_col(name_span.start).0,
|
||||
detail: detail_span.map(|span| lines.line_col(span.start).0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable identity of one indexed declaration inside the current index.
|
||||
@@ -375,7 +417,19 @@ impl WorkspaceIndex {
|
||||
/// server refreshes every overlay after it, exactly as it does after a
|
||||
/// rebuild).
|
||||
pub fn update_file(&mut self, path: PathBuf, src: &str) {
|
||||
let facts = facts_of(path.clone(), src);
|
||||
self.update_facts(facts_of(path, src));
|
||||
}
|
||||
|
||||
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
|
||||
/// known — read from a cache, or from an analysis the caller already holds
|
||||
/// ([`FileFacts::from_analysis`]) — so the update costs no parse at all.
|
||||
///
|
||||
/// Exactly [`WorkspaceIndex::update_file`] with the parse already done, the
|
||||
/// same way [`IndexBuilder::add_facts`] is [`IndexBuilder::add_file`] with
|
||||
/// the parse already done: same contract, same result. Whether the record
|
||||
/// really describes the file is the caller's business.
|
||||
pub fn update_facts(&mut self, facts: FileFacts) {
|
||||
let path = facts.path.clone();
|
||||
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
|
||||
// The common case — a saved file the index already holds. Only the
|
||||
// names this file declared before or declares now can have moved,
|
||||
@@ -396,6 +450,52 @@ impl WorkspaceIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
|
||||
/// many files at once — and for **one** merge rather than one each.
|
||||
///
|
||||
/// Same contract as both — what comes out is the index a full
|
||||
/// [`WorkspaceIndex::build`] over the records it now holds would have
|
||||
/// produced — **provided each path appears once in `records`**. It holds
|
||||
/// for the same reason theirs does: the records are kept path-sorted and
|
||||
/// one file to a path, and [`WorkspaceIndex::merge`] is then the same loop
|
||||
/// [`IndexBuilder::finish`] runs over the same list. A batch that names
|
||||
/// one path twice is an update applied twice, so the **last** record wins,
|
||||
/// where a `build` over the same duplicated input keeps the *first*
|
||||
/// (`index_order` dedups) — the update semantic is the right one for an
|
||||
/// "absorb what changed" API, and the one caller that feeds a scan
|
||||
/// (`Scan::work`) is deduped before anything is staged. QA pinned the
|
||||
/// divergence
|
||||
/// (`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`).
|
||||
///
|
||||
/// One merge, because a merge is a pass over **every** record the index
|
||||
/// holds: a scan that merged after each of its files would be quadratic in
|
||||
/// the size of the workspace, which is measured rather than argued in
|
||||
/// `docs/features/scan-interleave/README.md`. A caller feeding a scan
|
||||
/// therefore batches — it stages records as it takes them and folds a
|
||||
/// batch in only when something is about to read the index.
|
||||
///
|
||||
/// `gone` is dropped first, so a path in both lists ends up held: a file
|
||||
/// that moved out of one scan's scope and back into the next's is one
|
||||
/// file, not a removal that happens to run second.
|
||||
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]) {
|
||||
for path in gone {
|
||||
if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) {
|
||||
self.files.remove(at);
|
||||
self.facts.remove(at);
|
||||
}
|
||||
}
|
||||
for facts in records {
|
||||
match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) {
|
||||
Ok(at) => self.facts[at] = facts,
|
||||
Err(at) => {
|
||||
self.files.insert(at, facts.path.clone());
|
||||
self.facts.insert(at, facts);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.merge(None);
|
||||
}
|
||||
|
||||
/// Drop one file from the index, reporting whether it was there.
|
||||
///
|
||||
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
|
||||
@@ -425,13 +525,15 @@ impl WorkspaceIndex {
|
||||
}
|
||||
for symbol in self.workspace_symbols("") {
|
||||
out.push_str(&format!(
|
||||
"sym {} in {:?} {:?} {}:{}..{}\n",
|
||||
"sym {} in {:?} {:?} {}:{}..{} line={} detail={:?}\n",
|
||||
symbol.name,
|
||||
symbol.container,
|
||||
symbol.def.kind,
|
||||
symbol.def.file.0,
|
||||
symbol.def.name_span.start,
|
||||
symbol.def.name_span.end
|
||||
symbol.def.name_span.end,
|
||||
symbol.def.lines.name,
|
||||
symbol.def.lines.detail
|
||||
));
|
||||
}
|
||||
for (definition, sites) in &self.reference_sites {
|
||||
@@ -644,15 +746,29 @@ pub(crate) struct Decl {
|
||||
pub(crate) name: String,
|
||||
pub(crate) name_span: TextRange,
|
||||
pub(crate) kind: SymbolKind,
|
||||
pub(crate) detail_span: Option<TextRange>,
|
||||
pub(crate) lines: DeclLines,
|
||||
}
|
||||
|
||||
impl Decl {
|
||||
fn of(symbol: &Symbol) -> Decl {
|
||||
Decl { name: symbol.name.clone(), name_span: symbol.name_span, kind: symbol.kind }
|
||||
fn of(symbol: &Symbol, lines: &LineIndex) -> Decl {
|
||||
Decl {
|
||||
name: symbol.name.clone(),
|
||||
name_span: symbol.name_span,
|
||||
kind: symbol.kind,
|
||||
detail_span: symbol.detail_span,
|
||||
lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span),
|
||||
}
|
||||
}
|
||||
|
||||
fn def(&self, file: FileId) -> Def {
|
||||
Def { file, name_span: self.name_span, kind: self.kind }
|
||||
Def {
|
||||
file,
|
||||
name_span: self.name_span,
|
||||
kind: self.kind,
|
||||
detail_span: self.detail_span,
|
||||
lines: self.lines,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -716,10 +832,42 @@ impl FileFacts {
|
||||
/// Read off what one file contributes to an index — the parse
|
||||
/// [`IndexBuilder::add_file`] does, exposed so a caller that stores the
|
||||
/// result can do the parse itself exactly once.
|
||||
///
|
||||
/// Parses `src` internally, so call this only on a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one lets
|
||||
/// sufficiently nested input abort the process instead of producing a
|
||||
/// diagnostic (see `docs/features/recursion-limit/README.md`).
|
||||
pub fn of(path: PathBuf, src: &str) -> FileFacts {
|
||||
facts_of(path, src)
|
||||
}
|
||||
|
||||
/// The same record read off an analysis the caller **already has** — the
|
||||
/// tree, the `` `define`` table and the [`Semantics`] of one file — instead
|
||||
/// of from that file's text.
|
||||
///
|
||||
/// This is the second half of [`FileFacts::of`], made callable on its own:
|
||||
/// `of` is `tokenize` + `parse_tolerant` + [`analyze`] followed by exactly
|
||||
/// this function, so a caller that has done that work once (a language
|
||||
/// server holding an open buffer's finished analysis) gets the record the
|
||||
/// parse would have produced without paying for the parse a second time.
|
||||
/// The two paths are the same code and cannot drift; what the caller
|
||||
/// promises is only that `tree`, `defines`, `sem` and `lines` all describe
|
||||
/// the text `path` currently holds.
|
||||
///
|
||||
/// `lines` is asked for rather than built here because a caller with a
|
||||
/// finished analysis in hand — a server holding an open buffer — already
|
||||
/// has one, and because a record now carries each declaration's line
|
||||
/// ([`DeclLines`]).
|
||||
pub fn from_analysis(
|
||||
path: PathBuf,
|
||||
tree: &SourceFile,
|
||||
defines: &DefineTable,
|
||||
sem: &Semantics,
|
||||
lines: &LineIndex,
|
||||
) -> FileFacts {
|
||||
facts_from_analysis(path, tree, defines.clone(), sem, lines)
|
||||
}
|
||||
|
||||
/// The file these facts were read from.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
@@ -730,13 +878,28 @@ impl FileFacts {
|
||||
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
|
||||
let (tree, defines) = parse_and_collect(src);
|
||||
let sem = analyze(&tree, src);
|
||||
// One pass over the source's newlines, so every declaration below can be
|
||||
// given its line without anyone reading the file again later. It is a
|
||||
// percent of the parse it sits beside (`docs/perf/README.md`).
|
||||
let lines = LineIndex::new(src);
|
||||
facts_from_analysis(path, &tree, defines, &sem, &lines)
|
||||
}
|
||||
|
||||
/// Read off what one file contributes, from its finished analysis.
|
||||
fn facts_from_analysis(
|
||||
path: PathBuf,
|
||||
tree: &SourceFile,
|
||||
defines: DefineTable,
|
||||
sem: &Semantics,
|
||||
lines: &LineIndex,
|
||||
) -> FileFacts {
|
||||
let mut facts = FileFacts {
|
||||
path,
|
||||
defines,
|
||||
units: Vec::new(),
|
||||
members: Vec::new(),
|
||||
instantiations: edges_of(&tree),
|
||||
subclasses: inheritance_of(&tree),
|
||||
instantiations: edges_of(tree),
|
||||
subclasses: inheritance_of(tree),
|
||||
references: Vec::new(),
|
||||
};
|
||||
let Some(file_scope) = sem.scope(sem.file_scope()) else {
|
||||
@@ -749,8 +912,8 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
|
||||
if !is_unit(unit.kind) || unit.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
facts.units.push(Decl::of(unit));
|
||||
collect_members(&sem, unit, &mut facts.members);
|
||||
facts.units.push(Decl::of(unit, lines));
|
||||
collect_members(sem, unit, lines, &mut facts.members);
|
||||
}
|
||||
let exported: HashSet<(u32, u32)> = facts
|
||||
.units
|
||||
@@ -831,7 +994,12 @@ fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> {
|
||||
}
|
||||
|
||||
/// Read off the names another file may reach *into* this unit for.
|
||||
fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) {
|
||||
fn collect_members(
|
||||
sem: &Semantics,
|
||||
unit: &Symbol,
|
||||
lines: &LineIndex,
|
||||
out: &mut Vec<(String, Decl)>,
|
||||
) {
|
||||
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
|
||||
return;
|
||||
};
|
||||
@@ -842,13 +1010,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
|
||||
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push((unit.name.clone(), Decl::of(member)));
|
||||
out.push((unit.name.clone(), Decl::of(member, lines)));
|
||||
// A class nested in a package (the dominant UVM shape) is not a unit,
|
||||
// but an external `cls::x` candidate looks its members up under the
|
||||
// *class's* name — register them there too. The scope tree is acyclic,
|
||||
// so this recursion terminates.
|
||||
if member.kind == SymbolKind::Class {
|
||||
collect_members(sem, member, out);
|
||||
collect_members(sem, member, lines, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -862,10 +1030,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
|
||||
/// the first file is parsed. Getting that ordering from here rather than
|
||||
/// re-deriving it is what keeps a watched build and a plain
|
||||
/// [`WorkspaceIndex::build`] the same index in the same order.
|
||||
pub fn index_order<'a>(
|
||||
files: impl IntoIterator<Item = (PathBuf, &'a str)>,
|
||||
) -> Vec<(PathBuf, &'a str)> {
|
||||
let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect();
|
||||
///
|
||||
/// Generic in what rides beside the path — a borrowed `&str` for a caller that
|
||||
/// holds the texts, an owned `String` for one that is handing them over — so a
|
||||
/// scan that owns its work list gets the same ordering from the same function
|
||||
/// rather than sorting for itself.
|
||||
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)> {
|
||||
let mut sources: Vec<(PathBuf, T)> = files.into_iter().collect();
|
||||
sources.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
// A path handed over twice is one file; the first copy wins.
|
||||
sources.dedup_by(|a, b| a.0 == b.0);
|
||||
|
||||
@@ -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 = "\
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! package members, and the corpus acceptance run.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
|
||||
Semantics, SymbolKind, WorkspaceIndex,
|
||||
@@ -1102,6 +1103,122 @@ fn removing_a_file_gives_the_index_a_whole_build_would_have() {
|
||||
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_a_batch_gives_the_index_a_whole_build_would_have() {
|
||||
// The batch form the interleaved scan feeds
|
||||
// (`docs/features/scan-interleave/README.md`), against the same witness
|
||||
// every other incremental path is held to. Every shape at once: a file
|
||||
// replaced, two files added — one of which sorts *first*, so every id
|
||||
// moves — and one dropped.
|
||||
let held = [
|
||||
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||||
("gone.sv", "module gone;\nendmodule\n"),
|
||||
];
|
||||
let mut ws = index(&held);
|
||||
assert_eq!(ws.files().len(), 3, "premise");
|
||||
|
||||
let batch = [
|
||||
("a.sv", "module sub;\nendmodule\n"),
|
||||
("m.sv", "module m;\n sub u1 ();\n sub u2 ();\nendmodule\n"),
|
||||
("zz.sv", "class leaf extends base;\nendclass\n"),
|
||||
];
|
||||
ws.absorb(
|
||||
batch.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(),
|
||||
&[PathBuf::from("gone.sv")],
|
||||
);
|
||||
|
||||
let mut expected: Vec<(&str, &str)> = vec![("z.sv", held[1].1)];
|
||||
expected.extend(batch);
|
||||
assert_eq!(
|
||||
ws.fingerprint(),
|
||||
index(&expected).fingerprint(),
|
||||
"a batch folded in is the index a whole build over what is left would have"
|
||||
);
|
||||
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the added file took FileId(0)");
|
||||
assert!(ws.units("gone").is_empty(), "and the dropped one is gone");
|
||||
assert_eq!(ws.instantiations_of("sub").len(), 2, "the replaced file's new edges are in");
|
||||
assert_eq!(ws.subclasses_of("base").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index() {
|
||||
// What makes a *publish* free of consequence: the scan folds records in
|
||||
// whenever it happens to be asked a question, so how the same records are
|
||||
// grouped into batches must not reach the result.
|
||||
let records = |files: &[(&str, &str)]| -> Vec<FileFacts> {
|
||||
files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect()
|
||||
};
|
||||
let files = [
|
||||
("a.sv", "module sub;\nendmodule\n"),
|
||||
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||||
("dup.sv", "module m;\nendmodule\n"),
|
||||
];
|
||||
let mut whole = WorkspaceIndex::default();
|
||||
whole.absorb(records(&files), &[]);
|
||||
|
||||
let mut piecemeal = WorkspaceIndex::default();
|
||||
for one in &files {
|
||||
piecemeal.absorb(records(std::slice::from_ref(one)), &[]);
|
||||
}
|
||||
assert_eq!(whole.fingerprint(), piecemeal.fingerprint());
|
||||
assert_eq!(whole.fingerprint(), index(&files).fingerprint(), "and both are a whole build");
|
||||
assert_eq!(piecemeal.units("m").len(), 2, "the duplicate name is still disambiguated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records() {
|
||||
// QA attack (`docs/features/scan-interleave/README.md`, absorb attacks):
|
||||
// a duplicate path inside one batch. Not constructible through the scan
|
||||
// that actually feeds `absorb` — `Scan::work` is built from `index_order`,
|
||||
// which already dedupes by path — but `absorb` is a public entry point on
|
||||
// `WorkspaceIndex`, and its doc comment claims "what comes out is the
|
||||
// index a full build over the records it now holds would have produced."
|
||||
// `WorkspaceIndex::build` goes through `index_order`, which keeps the
|
||||
// *first* of a duplicate path (`Vec::dedup_by`'s contract). `absorb`'s own
|
||||
// loop walks `records` left to right and overwrites on a hit, keeping the
|
||||
// *last*. So handed the exact same two records for one path, the two
|
||||
// entry points disagree — the claimed equivalence does not hold for a
|
||||
// batch with a duplicate path. Filed as a finding, not fixed here: which
|
||||
// one should win is a design call, not a QA fix.
|
||||
let files = [
|
||||
("a.sv", "module first_shape;\nendmodule\n"),
|
||||
("a.sv", "package second_shape;\nendpackage\n"),
|
||||
];
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
|
||||
|
||||
let mut absorbed = WorkspaceIndex::default();
|
||||
absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]);
|
||||
|
||||
assert_eq!(absorbed.files().len(), 1, "one file survives either way");
|
||||
assert_ne!(
|
||||
built.fingerprint(),
|
||||
absorbed.fingerprint(),
|
||||
"build (first-wins) and absorb (last-wins) disagree on a duplicate path in one batch"
|
||||
);
|
||||
// Naming what absorb actually did, so a fix that changes this is a
|
||||
// deliberate, visible diff rather than a silent behavior change.
|
||||
assert_eq!(
|
||||
absorbed.fingerprint(),
|
||||
index(&[("a.sv", files[1].1)]).fingerprint(),
|
||||
"absorb kept the second (last) record for the duplicate path"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_nothing_changes_nothing() {
|
||||
// A publish with nothing staged and a finish with nothing left are both
|
||||
// this call, and neither may disturb an index that is already right.
|
||||
let files = [("a.sv", "module a;\nendmodule\n")];
|
||||
let mut ws = index(&files);
|
||||
let before = ws.fingerprint();
|
||||
ws.absorb(Vec::new(), &[]);
|
||||
assert_eq!(ws.fingerprint(), before);
|
||||
ws.absorb(Vec::new(), &[PathBuf::from("never_held.sv")]);
|
||||
assert_eq!(ws.fingerprint(), before, "dropping a file the index never held is harmless");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_file_moves_the_disambiguation_winner() {
|
||||
// The sharpest thing a removal can do to a *derived* answer: the file that
|
||||
@@ -1553,6 +1670,149 @@ fn a_records_every_field_survives_the_round_trip() {
|
||||
assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte");
|
||||
}
|
||||
|
||||
/// Every indexed declaration carries the line it is written on, so a caller
|
||||
/// printing `file:line` never has to read the file
|
||||
/// (`docs/features/hover-line-index/README.md`). The awkward offsets are the
|
||||
/// point: line 1 has no newline before it, the last line has none after it,
|
||||
/// and both are where an off-by-one lives.
|
||||
#[test]
|
||||
fn every_declared_names_line_is_recorded_when_the_file_is_indexed() {
|
||||
// No trailing newline, so `last_t` really is on the file's last line.
|
||||
let src = "module first;\nendmodule\n\n// a comment\npackage p;\n localparam W = 8;\n\
|
||||
endpackage\ntypedef int last_t;";
|
||||
let index = index(&[("/w/m.sv", src)]);
|
||||
let line_of = |name: &str| index.units(name).first().expect(name).lines.name;
|
||||
assert_eq!(line_of("first"), 1, "a declaration on line 1");
|
||||
assert_eq!(line_of("p"), 5);
|
||||
assert_eq!(line_of("last_t"), 8, "the last line, with no newline after it");
|
||||
assert_eq!(index.member("p", "W").first().expect("W").lines.name, 6, "members too");
|
||||
|
||||
// The line really is the line the text says it is: every recorded line's
|
||||
// range, sliced out of the source, contains the name it was recorded for.
|
||||
for (name, line) in [("first", 1), ("p", 5), ("last_t", 8)] {
|
||||
let text = src.lines().nth(line as usize - 1).expect("that many lines");
|
||||
assert!(text.contains(name), "line {line} is {text:?}, which does not declare {name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `\r\n` file and multi-byte text before a declaration do not shift its
|
||||
/// line: lines are counted in newlines, not in bytes or in characters.
|
||||
#[test]
|
||||
fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() {
|
||||
let crlf = "// one\r\n// two\r\nmodule m;\r\nendmodule\r\n";
|
||||
assert_eq!(index(&[("/w/c.sv", crlf)]).units("m").first().expect("m").lines.name, 3);
|
||||
|
||||
// Three-byte characters and a four-byte emoji ahead of the declaration:
|
||||
// the byte offset of `m` is far past 3, its line is not.
|
||||
let wide = "// héllo ✓ 🎉\n// ünïcödé\nmodule m;\nendmodule\n";
|
||||
assert!(wide.find("module m").expect("a module") > 20, "premise: the bytes are wide");
|
||||
assert_eq!(index(&[("/w/w.sv", wide)]).units("m").first().expect("m").lines.name, 3);
|
||||
}
|
||||
|
||||
/// A non-ANSI port is named in the header and finished in the body, and the
|
||||
/// carrier holds a line for each — the extension the shape was chosen for:
|
||||
/// richer per-declaration position data is another field on `DeclLines`, not
|
||||
/// another table.
|
||||
#[test]
|
||||
fn a_split_ports_two_lines_ride_the_same_carrier() {
|
||||
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
|
||||
let split = index(&[("/w/s.sv", src)]);
|
||||
let def = split.member("m", "clk").first().expect("the port");
|
||||
assert!(def.detail_span.is_some(), "premise: this port is split");
|
||||
assert_eq!(def.lines.name, 2, "the header names it on line 2");
|
||||
assert_eq!(def.lines.detail, Some(4), "and the body finishes it on line 4");
|
||||
|
||||
// An ANSI port is complete where it is named, and says so in both fields.
|
||||
let ansi = index(&[("/w/a.sv", "module m (\n input wire clk\n);\nendmodule\n")]);
|
||||
let def = ansi.member("m", "clk").first().expect("the port");
|
||||
assert_eq!(def.detail_span, None);
|
||||
assert_eq!((def.lines.name, def.lines.detail), (2, None));
|
||||
}
|
||||
|
||||
/// The lines survive the record format, which is what makes them free on a
|
||||
/// cached scan rather than only on a parsed one.
|
||||
#[test]
|
||||
fn a_declarations_lines_survive_the_record_round_trip() {
|
||||
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
|
||||
let facts = FileFacts::of(PathBuf::from("/w/s.sv"), src);
|
||||
let line = facts.encode().expect("encodes");
|
||||
let back = FileFacts::decode(&line).expect("decodes");
|
||||
assert_eq!(back, facts, "every field, lines included");
|
||||
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
builder.add_facts(back);
|
||||
let restored = builder.finish();
|
||||
let def = restored.member("m", "clk").first().expect("the port");
|
||||
assert_eq!((def.lines.name, def.lines.detail), (2, Some(4)));
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): the single-decl fixture `index_cache`'s own format-bump
|
||||
/// test strips is not the only shape a genuine format-3 record could take —
|
||||
/// a file declaring *two* units is the shape where a field-shift attack would
|
||||
/// actually have somewhere plausible to land: if stripping the first decl's
|
||||
/// two line fields shifted every read two fields early, the fields it would
|
||||
/// then misread as `(name_line, detail_line)` are the *second* decl's own
|
||||
/// `name` and `kind` strings. Both are always non-numeric — a Verilog
|
||||
/// identifier cannot start with a digit and `kind_name` writes only letters —
|
||||
/// so `Reader::num` fails on them and `decode` returns `None` rather than
|
||||
/// quietly building a `Decl` out of someone else's fields. Proved directly
|
||||
/// here, generalizing `index_cache`'s stripper to more than one declaration,
|
||||
/// rather than only argued.
|
||||
#[test]
|
||||
fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
|
||||
let src = "module a; endmodule\nmodule b; endmodule\n";
|
||||
let facts = FileFacts::of(PathBuf::from("/w/two.sv"), src);
|
||||
let encoded = facts.encode().expect("encodes");
|
||||
let format_3 = strip_every_decls_line_fields(&encoded, 2, 0);
|
||||
assert_ne!(format_3, encoded, "premise: fields were actually removed");
|
||||
assert!(
|
||||
FileFacts::decode(&format_3).is_none(),
|
||||
"a two-unit format-3 record decoded as a format-4 one: {format_3}"
|
||||
);
|
||||
|
||||
// The mixed case: one unit with a member that has a real detail span (a
|
||||
// split port), so the decls being stripped are not even the same width
|
||||
// of *content* — only of field count, which is what the format promises.
|
||||
let split = "module m (\n clk\n);\n input wire clk;\nendmodule\n\
|
||||
module other; endmodule\n";
|
||||
let facts = FileFacts::of(PathBuf::from("/w/mixed.sv"), split);
|
||||
let encoded = facts.encode().expect("encodes");
|
||||
let format_3 = strip_every_decls_line_fields(&encoded, 2, 1);
|
||||
assert_ne!(format_3, encoded, "premise: fields were actually removed");
|
||||
assert!(
|
||||
FileFacts::decode(&format_3).is_none(),
|
||||
"a mixed unit+member format-3 record decoded as a format-4 one: {format_3}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The generalization of `index_cache`'s `strip_the_line_fields`: remove the
|
||||
/// two trailing (`name_line`, `detail_line`) fields from every one of
|
||||
/// `units` unit-decls and `members` member-decls in an encoded record —
|
||||
/// i.e. what `FACTS_FORMAT` 3 wrote for the same file. Assumes `D0` (no
|
||||
/// `` `define``s), which every fixture here satisfies, so the `U` tag's
|
||||
/// field index is fixed and decl positions can be computed directly rather
|
||||
/// than parsed.
|
||||
fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) -> String {
|
||||
let mut fields: Vec<&str> = encoded.split('\t').collect();
|
||||
let units_at = fields.iter().position(|f| *f == "U").expect("a U tag");
|
||||
assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count");
|
||||
// decl = name, kind, name_span×2, detail_span×2, line×2 — 8 fields.
|
||||
let unit_decls_end = units_at + 2 + units * 8;
|
||||
let members_at = unit_decls_end;
|
||||
assert_eq!(fields[members_at], "M", "premise: members tag follows the units");
|
||||
assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count");
|
||||
// A member entry is the owning unit's name (one text field) plus a decl.
|
||||
let member_decl_starts: Vec<usize> = (0..members).map(|m| members_at + 2 + m * 9 + 1).collect();
|
||||
let unit_decl_starts: Vec<usize> = (0..units).map(|u| units_at + 2 + u * 8).collect();
|
||||
// Highest index first, so removing one strip does not move the others.
|
||||
let mut starts: Vec<usize> = unit_decl_starts.into_iter().chain(member_decl_starts).collect();
|
||||
starts.sort_unstable_by(|a, b| b.cmp(a));
|
||||
for start in starts {
|
||||
fields.drain(start + 6..start + 8);
|
||||
}
|
||||
fields.join("\t")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_built_from_records_is_the_index_the_parse_would_have_given() {
|
||||
// The claim the cache rests on: facts through the record format and back
|
||||
@@ -1658,3 +1918,173 @@ fn a_degenerate_file_still_makes_a_record() {
|
||||
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Facts from an analysis the caller already has (index-scope, 2026-08-28)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The analysis a server holds for an open buffer, built exactly the way
|
||||
/// `lucisv_server::state::Document::new` builds it — one lex, the tree from a
|
||||
/// clone of that token stream, the define table off the same tokens, and the
|
||||
/// same all-or-nothing lex-failure branch.
|
||||
fn as_a_server_analyzes(
|
||||
src: &str,
|
||||
) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics, vlog_parser::LineIndex) {
|
||||
let (tokens, tree) = match tokenize(src) {
|
||||
Ok(tokens) => {
|
||||
let (tree, _) = parse_tolerant(tokens.clone(), src);
|
||||
(tokens, tree)
|
||||
}
|
||||
Err(_) => (Vec::new(), parse_source_tolerant(src).0),
|
||||
};
|
||||
let defines = collect_defines(&tokens);
|
||||
let sem = analyze(&tree, src);
|
||||
(tree, defines, sem, vlog_parser::LineIndex::new(src))
|
||||
}
|
||||
|
||||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||||
///
|
||||
/// The record format is the comparison — the encoded line is every field the
|
||||
/// index and the persistent store ever read — so a byte-equal line is the
|
||||
/// whole equivalence. Two paths that could drift here would be a corruption
|
||||
/// seed: the index would describe a buffer by facts its own parse disagrees
|
||||
/// with.
|
||||
#[test]
|
||||
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
let crafted = [
|
||||
// Nothing at all, and nothing that lexes.
|
||||
"",
|
||||
" \n\t\n",
|
||||
"this is not verilog\n",
|
||||
"module m;\n \"unterminated\n",
|
||||
"// just a comment\n",
|
||||
// The declaration kinds `facts_of` reads off the file scope.
|
||||
"package p;\n localparam W = 8;\n typedef logic [W-1:0] word_t;\n\
|
||||
\x20 function int f(int a); return a; endfunction\nendpackage\n",
|
||||
"module top #(parameter N = 4) (input logic clk, output logic q);\n\
|
||||
\x20 sub u_a (.clk(clk));\n sub u_b (.clk(clk));\nendmodule\n",
|
||||
// Classes, inheritance, and a class nested in a package.
|
||||
"class base; endclass\nclass derived extends base;\n int x;\nendclass\n",
|
||||
"package pkg;\n class inner extends outer_base;\n typedef int t;\n endclass\nendpackage\n",
|
||||
// `define`s, including a parameterised one and an `undef`.
|
||||
"`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n`undef WIDTH\n\
|
||||
module m; logic [`WIDTH-1:0] w; endmodule\n",
|
||||
// External candidates: imports, scope resolution, port connections.
|
||||
"import other_pkg::*;\nimport third_pkg::thing;\nmodule m;\n\
|
||||
\x20 other_pkg::word_t w;\n assign w = thing;\n child u (.port_a(w));\nendmodule\n",
|
||||
// An instantiation at file scope — deliberately *not* an edge — and a
|
||||
// generate body, which is one site however many instances it makes.
|
||||
"sub u_orphan (.clk(clk));\nmodule m;\n generate for (genvar i = 0; i < 4; i++) begin\n\
|
||||
\x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n",
|
||||
// A tree with error nodes: the tolerant parse still contributes.
|
||||
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n",
|
||||
];
|
||||
for src in crafted {
|
||||
let path = PathBuf::from("/w/x.sv");
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
|
||||
let from_text = FileFacts::of(path.clone(), src);
|
||||
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, &lines);
|
||||
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
|
||||
assert_eq!(
|
||||
from_analysis.encode(),
|
||||
from_text.encode(),
|
||||
"and so do their encoded forms for {src:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same claim over every file of the real corpus, which is where the
|
||||
/// constructs nobody thought to craft live.
|
||||
#[test]
|
||||
fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !root.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
corpus_files(&root, &mut files);
|
||||
files.sort();
|
||||
assert!(!files.is_empty(), "corpus/ exists but holds no Verilog");
|
||||
let mut checked = 0usize;
|
||||
for path in &files {
|
||||
let Ok(src) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(&src);
|
||||
let from_text = FileFacts::of(path.clone(), &src);
|
||||
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &lines);
|
||||
assert_eq!(
|
||||
from_analysis.encode(),
|
||||
from_text.encode(),
|
||||
"the records differ for {}",
|
||||
path.display()
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
eprintln!("facts equivalence: {checked} corpus files, every record byte-identical");
|
||||
}
|
||||
|
||||
fn corpus_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
corpus_files(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An index built from records read off analyses is the index the parses
|
||||
/// build, byte for byte — the house witness, at index scale rather than at one
|
||||
/// file's.
|
||||
#[test]
|
||||
fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text() {
|
||||
let files = [
|
||||
("/w/pkg.sv", "package p;\n localparam W = 8;\n class c; int x; endclass\nendpackage\n"),
|
||||
("/w/sub.sv", "module sub (input logic clk, input logic [7:0] d);\nendmodule\n"),
|
||||
(
|
||||
"/w/top.sv",
|
||||
"import p::*;\n`define TAG 1\nmodule top;\n logic [W-1:0] w;\n\
|
||||
\x20 sub u_a (.clk(w[0]), .d(w));\n sub u_b (.clk(w[0]), .d(w));\nendmodule\n",
|
||||
),
|
||||
("/w/kid.sv", "class kid extends c;\nendclass\n"),
|
||||
("/w/junk.sv", "module broken (;\n"),
|
||||
];
|
||||
let from_text = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
|
||||
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
// Deliberately not path order: the reuse must not smuggle an ordering in.
|
||||
for (path, src) in files.iter().rev() {
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
|
||||
builder.add_facts(FileFacts::from_analysis(
|
||||
PathBuf::from(*path),
|
||||
&tree,
|
||||
&defines,
|
||||
&sem,
|
||||
&lines,
|
||||
));
|
||||
}
|
||||
let from_analyses = builder.finish();
|
||||
assert_eq!(from_analyses.fingerprint(), from_text.fingerprint());
|
||||
|
||||
// And the same through the incremental door: `update_facts` must leave the
|
||||
// index `update_file` would have left.
|
||||
let mut updated = from_text.clone();
|
||||
let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n";
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(changed);
|
||||
updated.update_facts(FileFacts::from_analysis(
|
||||
PathBuf::from("/w/pkg.sv"),
|
||||
&tree,
|
||||
&defines,
|
||||
&sem,
|
||||
&lines,
|
||||
));
|
||||
let mut parsed = from_text.clone();
|
||||
parsed.update_file(PathBuf::from("/w/pkg.sv"), changed);
|
||||
assert_eq!(updated.fingerprint(), parsed.fingerprint(), "update_facts == update_file");
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
# 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).
|
||||
**Superseded again 2026-08-28 by `docs/features/hover-line-index/README.md`**,
|
||||
which adds `Def::lines` (each declaration's line number) and bumps
|
||||
`FACTS_FORMAT` 3 → 4. Same reading: a line number is not text either, and
|
||||
it is what makes this feature's heading free.
|
||||
- The heading line `**label** — declared in `file:line`` is unchanged, so a
|
||||
client (or a test) reading only that half sees exactly what it saw before.
|
||||
|
||||
## 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.
|
||||
- [x] **2026-08-28** (`docs/features/hover-line-index/README.md`): the disk
|
||||
path's heading costs no read at all (`Def::lines`) and its snippet's
|
||||
read is shared across hovers, so the second hover into a closed file is
|
||||
free. `disk_view` is gone, subsumed by `Workspace::file_view`.
|
||||
|
||||
## Work log
|
||||
|
||||
### 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 (the heading stops reading the file at all)
|
||||
|
||||
Round `hover-line-index` — full argument, measurements and tests in
|
||||
`docs/features/hover-line-index/README.md`. What changed *here*:
|
||||
|
||||
- **The `External` arm's disk branch no longer reads anything for the
|
||||
heading.** `Def` now carries `lines: DeclLines`, recorded when the file was
|
||||
indexed, so `**port** — declared in `sub.sv:2`` is a field lookup. The live
|
||||
branch is untouched and still asks the open buffer's own line index, because
|
||||
that buffer may hold unsaved edits the index has not seen — the same reason
|
||||
`declaration_snippet` matches a `Def` to a live symbol logically.
|
||||
- **`disk_view` was deleted.** Its job — one read per file per hover — is now
|
||||
`Workspace::file_view`'s, which does it once per file per *generation of that
|
||||
file*, so the next hover into the same file reads nothing. The four points
|
||||
that drop a held view are listed in that round's Handshakes.
|
||||
- **`spells_exactly` and both caps are untouched**, and a stale held view can
|
||||
only ever make a snippet vanish. Every existing test in this file passed
|
||||
unmodified.
|
||||
- **One corner moved deliberately**: a closed file that cannot be *read* now
|
||||
still gets its line in the heading (`sub.sv:2` rather than a bare `sub.sv`),
|
||||
because the line no longer depends on the read. Pinned by
|
||||
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read`.
|
||||
- Measured: a hover into a 12 MB closed file, 6.2 ms → **0.95 µs** on the
|
||||
second hover; the 31.7 MB probe above, 17.0 ms → **4.4 µs** on the second.
|
||||
The first touch is unchanged, because the snippet genuinely wants the text.
|
||||
|
||||
### 2026-08-28 — dev (CRLF, closing QA finding 2)
|
||||
|
||||
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
|
||||
`\r` inside the fence — is **fixed**, as part of `port-detail-spans`' PDS-4.
|
||||
Every line a card shows now goes through `attached_lines`, which strips a
|
||||
trailing `\r` as it composes each line; that covers both this feature's
|
||||
snippet path and `local_text`'s in-file path, which QA named as having the
|
||||
same property, because both reach it through `fenced_sections`. Display
|
||||
text only: no buffer is written.
|
||||
- QA's pinned regression test was named for the old behaviour
|
||||
(`a_crlf_multiline_snippet_keeps_interior_carriage_returns`) and asserted
|
||||
it; it is now `a_crlf_multiline_snippet_carries_no_carriage_returns` and
|
||||
asserts the opposite, plus that the lines read as written. The QA log below
|
||||
still names the old spelling; that section is QA's to amend.
|
||||
- No other change to this feature. `spells_exactly`, the caps and the
|
||||
disk/live split are untouched.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA
|
||||
|
||||
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,543 @@
|
||||
# hover-line-index
|
||||
|
||||
## Goal
|
||||
|
||||
The owner's report (2026-08-28): hovering a module instantiation is slow, and
|
||||
hovering one of its ports — to see the port's own declaration — is slow on the
|
||||
**first** try. Both land on the same code: a hover whose target is declared in
|
||||
a *closed* file read that whole file and built a whole `LineIndex` over it, for
|
||||
two things at once — the heading's `file:line`, and the fenced snippet of the
|
||||
declaration. On a netlist-adjacent file that read is milliseconds, and nothing
|
||||
was kept, so the *next* hover into the same file paid it again. The owner's
|
||||
design, which this round implements: put each declared name's **line number**
|
||||
into the index itself, where it costs a `u32` per declaration and is computed
|
||||
once when the file is scanned. The heading then costs no file access at all,
|
||||
and only the snippet still wants text — served from a small bounded cache of
|
||||
closed files' text in `Workspace`, so the first touch pays one read and no
|
||||
touch after it pays anything.
|
||||
|
||||
The shape of what that buys, measured below: a hover into a 12 MB closed file
|
||||
goes **6.2 ms → 0.9 µs on the second hover** and stays 6.2 ms on the first;
|
||||
the steady-state cross-file hover on a 10 000-line file goes **157 µs →
|
||||
13 µs**. The round also *measured the other suspect* and did not fix it — see
|
||||
Handshakes.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A line is a fact about the same snapshot the span is.** `Def::name_span`
|
||||
and `Def::lines.name` are read off one text in one pass, so a heading and a
|
||||
snippet can never name different generations of a file. Where the file has
|
||||
changed on disk with nothing telling the server, both are stale together,
|
||||
which is strictly better than the previous shape — a stale *offset* looked
|
||||
up in *fresh* text, whose line was arbitrary.
|
||||
- **Lines are 1-based, and are exactly what `LineIndex::line_col` reports.**
|
||||
That is what `locate::line_number` returned before, so the same headings come
|
||||
out.
|
||||
- **`FileFacts::from_analysis`'s caller has a line index already.** It is a
|
||||
server holding an open buffer's finished `Document`, which carries one. So
|
||||
the extra parameter costs the caller nothing, and `FileFacts::of` builds its
|
||||
own — one pass over the source's newlines, about 1 % of the parse it sits
|
||||
beside (`docs/perf/README.md`: `LineIndex::new` 115 µs against
|
||||
`parse_tolerant` 14.3 ms at 10 000 lines).
|
||||
- **The view cache is a cache and never a correctness input.** Every entry can
|
||||
be dropped at any moment with no change to any answer; a *stale* entry can
|
||||
only ever make a snippet disappear, never make it wrong, because
|
||||
`hover::spells_exactly` still checks the text at the span against the hovered
|
||||
name before anything is shown. That guard is unchanged and is still the last
|
||||
line of defence.
|
||||
- **Only closed files are cached.** `Workspace::file_view` returns `None` for a
|
||||
path an open buffer speaks for: that buffer's `Document` already holds its
|
||||
text and line index, and a second copy here would be a second opinion.
|
||||
- **The index is still text-free.** A line number is not text, exactly as a
|
||||
span is not text (`docs/features/workspace-index/README.md`'s promise, and
|
||||
the same reading `port-detail-spans` took for `detail_span`).
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `vlog_semantic` — `DeclLines`, and the carrier's extension story
|
||||
|
||||
```rust
|
||||
/// Where a declaration sits in its file, counted in lines.
|
||||
pub struct DeclLines {
|
||||
pub name: u32, // 1-based line of the declared name
|
||||
pub detail: Option<u32>, // 1-based line the detail span starts on
|
||||
}
|
||||
|
||||
pub struct Def {
|
||||
pub file: FileId,
|
||||
pub name_span: TextRange,
|
||||
pub kind: SymbolKind,
|
||||
pub detail_span: Option<TextRange>,
|
||||
pub lines: DeclLines, // new
|
||||
}
|
||||
|
||||
// One added parameter, because a record now carries lines:
|
||||
impl FileFacts {
|
||||
pub fn from_analysis(path, tree, defines, sem, lines: &LineIndex) -> FileFacts;
|
||||
}
|
||||
pub const FACTS_FORMAT: u32 = 4; // was 3
|
||||
```
|
||||
|
||||
**The carrier is one value per declaration, and it extends by gaining a
|
||||
field.** That is the owner's explicit ask ("keep the implementation flexible so
|
||||
we might even cache the port location") answered structurally rather than
|
||||
promised:
|
||||
|
||||
- **Ports already ride it.** A module's ports and parameters are indexed as
|
||||
*members*, and a member is a `Decl` exactly as a unit is — so
|
||||
`index.member("sub", "addr").lines.name` is that port's line, recorded in the
|
||||
same pass, with no extra table, no extra pass and no extra decision about
|
||||
"small projects". The owner's optional second step was already paid for by
|
||||
the first.
|
||||
- **A split port's two lines ride it too.** A non-ANSI port is named in the
|
||||
header and finished in the body (`detail_span`,
|
||||
`docs/features/port-detail-spans/README.md`), and `DeclLines::detail` is that
|
||||
body's line — the second position datum, already present, in the same value.
|
||||
- **A third one is a field.** A column, a rendered preview, an end line: add it
|
||||
to `DeclLines`, write it in `Writer::decl`, read it in `Reader::decl`, bump
|
||||
`FACTS_FORMAT`. Nothing else moves, because nothing else knows how many
|
||||
fields a `DeclLines` has. A *parallel table* keyed by declaration was the
|
||||
alternative and was rejected: it would have to be kept in step with `Decl`
|
||||
through every merge, every incremental update and every record round-trip,
|
||||
and there is no second consumer to justify the indirection
|
||||
(`CLAUDE.md`, "Simplicity first").
|
||||
|
||||
### `vlog_semantic` — `FACTS_FORMAT` 3 → 4, justified
|
||||
|
||||
A record's per-declaration group grew two fields. The rule written at the
|
||||
constant is that **any** change to what a record holds bumps the format, and
|
||||
the reason it is a whole-store discard rather than a migration is
|
||||
`docs/features/index-persistence/README.md`'s: a reader that guessed at an
|
||||
older layout would read last month's field order as this month's. Concretely,
|
||||
a format-3 record read as a format-4 one would shift every field after the
|
||||
first declaration by two — which is why the format field in the store's header
|
||||
catches it first, and why `decode` rejects it even if something served it past
|
||||
the header (both pinned, see Tests). The cost is one re-parse of the workspace
|
||||
on the first scan after upgrading; the corpus measurement below says that is
|
||||
about 175 ms.
|
||||
|
||||
### `vlog_semantic` — fingerprint
|
||||
|
||||
`WorkspaceIndex::fingerprint`'s `sym` line now carries `line=` and `detail=`.
|
||||
That is what makes the house witness — incremental index == fresh build —
|
||||
cover the new field rather than ignore it; every existing equivalence test
|
||||
(`update_file`, `update_facts`, `add_facts` from records, the corpus sweep)
|
||||
now compares lines as well as spans, and all of them stayed green unmodified.
|
||||
|
||||
### `lucisv_server::state` — the closed-file view cache
|
||||
|
||||
```rust
|
||||
pub struct FileView { pub path: PathBuf, pub text: String, pub lines: LineIndex }
|
||||
impl Workspace {
|
||||
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>>;
|
||||
}
|
||||
```
|
||||
|
||||
Bounded by **four entries** and **8 MiB of text**, newest first, oldest
|
||||
evicted. Two bounds because they answer two questions: how many files one
|
||||
answer can name (a card names one or two; a references list walks a handful
|
||||
before moving on), and how much memory a netlist-shaped file may cost. The
|
||||
newest entry is kept whatever it weighs — one file can exceed the whole byte
|
||||
budget on its own, and a cache that refused to hold it would be useless for
|
||||
exactly the file it exists for — so a huge file simply evicts everything else.
|
||||
|
||||
**Every invalidation point, in full.** A view is dropped when:
|
||||
|
||||
| event | what is dropped | why |
|
||||
|---|---|---|
|
||||
| `set_document(uri, text)` — `didOpen`, `didChange`, a text-carrying `didSave` | that path's view | the buffer becomes the authority, and the held disk copy may predate the edits it carries |
|
||||
| `close_document(uri)` | that path's view | disk is the authority again, and the view predates every save that buffer made |
|
||||
| `update_one(path)` | that path's view | re-indexing one file *is* the claim its bytes moved |
|
||||
| `rebuild_index_with(..)` | **all** views | a rescan says nothing about which file moved |
|
||||
|
||||
Those four are every path in the server that can change what a file holds:
|
||||
`server.rs` reaches the first two directly from the sync notifications, and the
|
||||
last two through `reindex_one` / `reindex`, which is where a save, a watched
|
||||
file change, a client file operation and a settings change all land.
|
||||
|
||||
What survives all four is a file changed on disk with nothing telling this
|
||||
server — and there the *index* is stale by the same event, which is precisely
|
||||
what `spells_exactly` exists for.
|
||||
|
||||
### `lucisv_server::locate` — the sweep
|
||||
|
||||
`locate::line_number` and `locate::location` were the only two functions that
|
||||
read a whole file to answer a position question, and `line_number`'s only
|
||||
callers were `hover.rs`'s two. Both now take an open buffer's own line index
|
||||
when there is one and the shared view otherwise; neither reads a file directly
|
||||
any more. `location`'s open-buffer arm also stops cloning the whole buffer text
|
||||
(`text_of` returns a `String`) on the way to a range. Mechanical, no behaviour
|
||||
change: `location` is what `textDocument/definition`, references, the lens and
|
||||
the hierarchies build their `Location`s from, and a references list over one
|
||||
file now reads that file once instead of once per site.
|
||||
|
||||
An indexed declaration's line no longer goes through `line_number` at all —
|
||||
`Def::lines` is the answer. What is left for it is the spans the index records
|
||||
no line for, which today is a `` `define``'s (the macro hover card's
|
||||
`defined in file:line`). Those ride the shared view, so a second macro hover
|
||||
into one file is free; giving `Define` its own line would mean a field in
|
||||
`vlog_parser`'s `Define` and is filed rather than done — it buys the first
|
||||
touch of one card and costs a second crate a field.
|
||||
|
||||
### Suspect 2 — **reported, not fixed here; DELIVERED 2026-08-28** by `docs/features/scan-interleave/README.md`
|
||||
|
||||
The brief named a second suspect and asked for it to be measured and filed
|
||||
rather than redesigned. It is real, and on the owner's own complaint it is by
|
||||
far the larger of the two:
|
||||
|
||||
`Server::new` runs the whole startup scan **before** `run()`'s message loop
|
||||
takes its first message. `main.rs` answers `initialize` (through
|
||||
`initialize_finish`, which also consumes `initialized`) and only then builds
|
||||
the `Server` — so everything a client sends the instant the handshake is done
|
||||
sits in the OS pipe until the scan is over. Measured over a 200-file, 1 000-
|
||||
line-each workspace with a filelist (so the startup scan really indexes it):
|
||||
|
||||
| the first hover of a session | cold store | warm store |
|
||||
|---|---:|---:|
|
||||
| issued the moment `initialized` was sent | **780 ms** | **287 ms** |
|
||||
| the same hover once the scan is done | 64 µs | 61 µs |
|
||||
|
||||
Four orders of magnitude, and this round does not touch it: fixing it means
|
||||
answering requests during the scan (or scanning on another thread), which is a
|
||||
change to request scheduling and to what an answer *means* while the index is
|
||||
half-built. `docs/features/index-persistence`'s store already takes it from
|
||||
780 ms to 287 ms; the rest is the read, the completion word table's lex and
|
||||
the include scan, which that feature's README already names as uncached.
|
||||
**Request to whoever owns the message loop next:** this is where "the first
|
||||
hover is really slow" mostly lives, and the probe that measures it is
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`.
|
||||
|
||||
**DELIVERED, 2026-08-28.** `docs/features/scan-interleave/README.md` took the
|
||||
scan apart into per-file steps and drains the message queue between them, so a
|
||||
startup scan long enough to be worth it answers requests while it runs. The
|
||||
same probe, flipped and renamed
|
||||
(`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`), now
|
||||
reports **15.5 ms cold / 12.8 ms warm** where the table above says 780 / 287 —
|
||||
and the scan's own total moved by under a percent. The request is closed; what
|
||||
that round did *not* do (the files are still read eagerly, a rescan still makes
|
||||
requests wait) is filed in its own Status/TODO with numbers.
|
||||
|
||||
## Measured
|
||||
|
||||
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
|
||||
`--release`, `#[ignore]`d probes, `--test-threads=1`, means where the numbers
|
||||
are small enough to need one. Every figure below was taken on 2026-08-28,
|
||||
before and after, in the same session.
|
||||
|
||||
### Suspect 1 — the per-hover read
|
||||
|
||||
| what | before | after |
|
||||
|---|---:|---:|
|
||||
| hover on an **instantiation** into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms |
|
||||
| — the same hover again | 5.75 ms | **0.95 µs** |
|
||||
| hover on a **port** into the same file, first touch | 5.85 ms | 5.92 ms |
|
||||
| — the same hover again | 5.71 ms | **0.99 µs** |
|
||||
| hover into a 31.7 MB closed file, first touch (QA's own probe) | 17.0 ms | 16.8 ms |
|
||||
| — the same hover again | 17.0 ms | **4.4 µs** |
|
||||
| cross-file hover, 1 000-line target, mean of 20 | 39.8 µs | **4.7 µs** |
|
||||
| cross-file hover, 10 000-line target, mean of 20 | 157 µs | **12.9 µs** |
|
||||
| — one read + `LineIndex` of that file, for comparison | 149 µs | 158 µs |
|
||||
|
||||
Read the table as two claims. **The first touch is unchanged**, and it should
|
||||
be: the snippet genuinely wants that file's text, and reading it is what the
|
||||
6.2 ms is. **Every touch after it is free**, which is the shape the owner's
|
||||
"slow on the FIRST try" report describes — and the heading half is free even
|
||||
on the first touch, which is why a card with no snippet (an unreadable file, a
|
||||
guard miss) now costs nothing at all.
|
||||
|
||||
### The price paid for it
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| whole 860-file corpus scan, no cache | 338 ms | 343 ms |
|
||||
| — cold, filling the store | 372 ms | 374 ms |
|
||||
| — warm, every file from the store | 197 ms | 200 ms |
|
||||
| the store, 860 files | 2 312 802 B | 2 380 790 B |
|
||||
|
||||
The scan times are inside their own run-to-run noise: the added work is one
|
||||
`LineIndex::new` per parsed file, which the flush breakdown puts at under 1 %
|
||||
of that file's parse. The store grows **68 KB over 860 files — 2.9 %**, which
|
||||
is the two decimal numbers per declaration over roughly 13 000 declarations,
|
||||
and is the owner's "a few KB for 20 000 modules" measured on real source.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Measure both suspects before touching anything; both recorded above.
|
||||
- [x] `DeclLines` on `Decl` and on `Def`, computed in `facts_from_analysis`
|
||||
from the file's own `LineIndex`.
|
||||
- [x] `FileFacts::from_analysis` takes the line index; `FileFacts::of` builds
|
||||
one.
|
||||
- [x] Record codec: two fields per declaration, `FACTS_FORMAT` 3 → 4, with the
|
||||
justification above.
|
||||
- [x] `WorkspaceIndex::fingerprint` carries the lines, so incremental == fresh
|
||||
covers them.
|
||||
- [x] `Workspace::file_view` — bounded, LRU, four named invalidation points.
|
||||
- [x] `hover.rs`: heading from `Def::lines`, snippet from the shared view; the
|
||||
per-request `disk_view` memo is gone, subsumed.
|
||||
- [x] `locate.rs` swept onto the buffer's index / the shared view.
|
||||
- [x] Tests (11 new, listed in the work log) and two new `#[ignore]`d probes.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- [ ] **Not done, deliberately: `` `define``s get no indexed line.** A
|
||||
`Define` is `vlog_parser`'s, and giving it a line means a field in
|
||||
another crate's public type plus its own record fields, to save the
|
||||
*first* macro hover into one file and nothing after it. The shared view
|
||||
already covers the repeat.
|
||||
- [ ] **Not done, deliberately: the other `text_of` callers are untouched.**
|
||||
`rename`, `ports`, `hierarchy`, `type_hierarchy`, `completion`,
|
||||
`signature`, `inlay` and `nav` read whole files because they want whole
|
||||
files, not a line — the sweep was for the position-only readers. Routing
|
||||
them through the view cache would mean `text_of` handing out an `Rc`
|
||||
instead of a `String`, which is a different change with a different
|
||||
argument.
|
||||
- [x] **Reported, not fixed *here*: the first request of a session waits out
|
||||
the startup scan.** Numbers and the filed request are in Handshakes;
|
||||
**delivered 2026-08-28** by `docs/features/scan-interleave/README.md`
|
||||
(780 ms → 15.5 ms cold, 287 ms → 12.8 ms warm).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-28 — dev
|
||||
|
||||
**Measured first, both suspects, before a line of the fix was written.** Two
|
||||
new probes were needed and are part of the round:
|
||||
`perf::hovering_into_a_big_closed_file_first_touch_and_repeat` (an
|
||||
instantiation and a port, into a 12 MB file, first touch and repeat separately
|
||||
— the existing probes all reported means, which hide exactly the first/repeat
|
||||
split the owner's report is about) and
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` (over the wire,
|
||||
against the real binary, two whole sessions so the persistent store is cold in
|
||||
one and warm in the other). The second answered the brief's question about
|
||||
suspect 2 with a number four orders of magnitude larger than suspect 1's, which
|
||||
is worth saying plainly even though this round could not act on it.
|
||||
|
||||
**The carrier: a struct, not a bare `u32`.** `DeclLines { name, detail }`
|
||||
rather than `line: u32` on `Decl`, because the *second* datum already exists —
|
||||
a split port's body line — and because the owner asked for room for more. The
|
||||
alternative shapes were both worse: a bare `u32` would have needed a second
|
||||
field the day `detail` was wanted (and `detail` was wanted on day one), and a
|
||||
parallel table keyed by declaration would have to be kept in step with `Decl`
|
||||
through the merge, the incremental update and the record round-trip, for no
|
||||
consumer that exists. `Option<u32>` for `detail` rather than a `0` sentinel in
|
||||
the *type*, even though the *record* writes `0` for `None`: the record's
|
||||
sentinel is a framing decision (the stream stays flat, exactly as
|
||||
`detail_span`'s `0 0` already does) and the type's is an API decision, and
|
||||
those two should not be forced to be the same thing.
|
||||
|
||||
**`from_analysis` grew a parameter rather than growing a `&str`.** It could
|
||||
have taken `src: &str` and built its own index, but its one real caller —
|
||||
`Document::facts` — already holds a `LineIndex` over exactly that text, and
|
||||
handing it over is both cheaper and more honest about what the function needs.
|
||||
The test helper `as_a_server_analyzes` grew a fourth return value for the same
|
||||
reason.
|
||||
|
||||
**`FACTS_FORMAT` 3 → 4, not 2 → 3 as the brief said.** The brief was written
|
||||
against a tree where `port-detail-spans` had not yet been counted; the constant
|
||||
was already at 3 when this round started. Same rule, next number.
|
||||
|
||||
**The heading now comes from the index on the disk path, and that is a small
|
||||
behaviour change in one corner.** Before, a closed file that could not be read
|
||||
produced a bare `` `sub.sv` `` heading with no line; now it produces
|
||||
`` `sub.sv:2` ``, because the line no longer depends on the file being
|
||||
readable. That is more information and not less, it is the line the index
|
||||
recorded from the text it indexed, and it is pinned by
|
||||
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` — which
|
||||
deletes the file and requires the heading to survive. Every other card is
|
||||
byte-identical: the full suite passed unmodified before a single new test was
|
||||
added, including the stale-span, guard, CRLF, cap and ambiguity tests.
|
||||
|
||||
**The live path was deliberately left alone.** An open buffer's heading still
|
||||
comes from that buffer's own line index and *not* from `Def::lines`, because
|
||||
the buffer may hold unsaved edits the index has not seen — the same reason
|
||||
`declaration_snippet` matches a `Def` to a live symbol logically instead of
|
||||
reading at the indexed span (`docs/features/hover-declarations/README.md`).
|
||||
Zero I/O either way, so there is nothing to win by unifying them and a
|
||||
correctness property to lose.
|
||||
|
||||
**`disk_view` is gone, subsumed.** Its whole job — one read per file per hover
|
||||
— is now the view cache's, which does the same thing per *session* instead of
|
||||
per request. The per-request memo would have been a second cache in front of
|
||||
the first.
|
||||
|
||||
**Files touched.** `crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`,
|
||||
`crates/vlog_semantic/tests/workspace.rs`,
|
||||
`crates/lucisv_server/src/{state.rs,locate.rs,hover.rs,index_cache.rs,perf.rs}`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, this README,
|
||||
`docs/features/{hover-declarations,workspace-index,index-persistence}/README.md`,
|
||||
`docs/perf/README.md`, `TODO.md`. No new dependency, no `unsafe`, no
|
||||
`#[allow]`, no version bump, no commits.
|
||||
|
||||
**Tests added.**
|
||||
|
||||
| test | where | pins |
|
||||
|---|---|---|
|
||||
| `every_declared_names_line_is_recorded_when_the_file_is_indexed` | `vlog_semantic/tests/workspace.rs` | line 1, a middle line, the last line with no trailing newline, and a member's line — each checked against the source line's own text |
|
||||
| `crlf_and_multibyte_text_do_not_shift_a_declarations_line` | same | `\r\n` line endings, and three- and four-byte characters ahead of the declaration |
|
||||
| `a_split_ports_two_lines_ride_the_same_carrier` | same | the extension story: a non-ANSI port's header line *and* body line, and an ANSI port's `None` |
|
||||
| `a_declarations_lines_survive_the_record_round_trip` | same | encode → decode → equal, and through `IndexBuilder` to a `Def` |
|
||||
| `a_store_from_any_previous_facts_format_is_dropped_not_misread` | `lucisv_server/src/index_cache.rs` | **rewritten**: every format `1..FACTS_FORMAT` is discarded by the header, *and* a genuine format-3 record (today's minus the two line fields) fails `decode` even served past the header. Was pinned at the literal `2` and would have gone on testing 2 forever |
|
||||
| `a_closed_files_text_is_read_once_and_then_reused` | `lucisv_server/src/state.rs` | the cache exists: the file is rewritten behind the server's back and the second view is the first |
|
||||
| `a_file_an_open_buffer_speaks_for_has_no_view_of_its_own` | same | closed files only |
|
||||
| `every_way_a_files_text_can_move_drops_its_view` | same | all four invalidation points, each by the same warm-change-event-check experiment |
|
||||
| `the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text` | same | both bounds, LRU order, and that a file over the whole byte budget is still cached and evicts the rest |
|
||||
| `a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` | `lucisv_server/src/hover.rs` | the round's central claim: the file is deleted and the heading still names its line, snippet correctly dropped |
|
||||
| `a_second_hover_into_one_closed_file_reads_nothing` | same | the snippet's read is shared: the file is rewritten and the second card is the first |
|
||||
|
||||
Two `#[ignore]`d probes added (`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`,
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`); one existing probe
|
||||
(`hovering_into_a_large_closed_file_reads_it_once`) grew a second timing so it
|
||||
reports the repeat beside the first touch.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` silent. `cargo test --workspace` green, 0 failed. The counts, by
|
||||
binary: `lucisv_server`'s unit tests **1 210 passed / 24 ignored** (+6 passing,
|
||||
+1 `#[ignore]`d probe), its `e2e` suite **56 passed / 2 ignored** (+1
|
||||
`#[ignore]`d probe), `vlog_semantic`'s `workspace` suite **66 passed** (+4).
|
||||
One test was renamed rather than added
|
||||
(`a_store_from_the_previous_facts_format_is_dropped_not_misread` →
|
||||
`a_store_from_any_previous_facts_format_is_dropped_not_misread`), so nothing
|
||||
was quietly dropped.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-28 — QA
|
||||
|
||||
Verdict: **SHIP.** No correctness bug found in the round's own code — every
|
||||
finding below is a test-coverage gap, closed in this pass with permanent
|
||||
regression tests. All seven charter items checked; details follow.
|
||||
|
||||
**1. Heading staleness — reproduced, and the documented window holds.**
|
||||
Constructed the exact attack: index `sub.sv` from its original text, then
|
||||
rewrite it on disk (`addr` moved from line 2 to line 6, and the byte offset
|
||||
the index still holds for it now lands inside a comment) with no `didSave`, no
|
||||
watcher event and no `update_one`/`rebuild_index` call — before any hover has
|
||||
ever read the file, so the view cache is empty and the read the snippet does
|
||||
is genuinely against the *new* bytes. Result: the heading still shows
|
||||
`sub.sv:2` (the index's last-scanned line, not the file's true current one),
|
||||
and the snippet is dropped by `spells_exactly` rather than showing whatever
|
||||
now sits at that byte range — no wrong line and no wrong snippet, matching the
|
||||
README's Assumptions ("both are stale together") exactly. Pinned:
|
||||
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`
|
||||
(`crates/lucisv_server/src/hover.rs`). The docs (this README's Assumptions
|
||||
section, and `Workspace::file_view`'s doc comment at
|
||||
`crates/lucisv_server/src/state.rs:1043`) already state this honestly — no
|
||||
doc fix needed.
|
||||
|
||||
**2. `DeclLines` correctness — dev's tests already cover the awkward
|
||||
offsets** (line 1, the last line with no trailing newline, CRLF, multi-byte
|
||||
text ahead of the declaration, a split port's two lines, an ANSI port's
|
||||
`None`) and check each recorded line against the source line's own text, not
|
||||
just against a hand-computed expectation. No drift found; ran unmodified.
|
||||
|
||||
**3. View-cache attacks — three untested-but-correct paths, now covered.**
|
||||
The cache's own logic (`trim_views`, `cached_view`,
|
||||
`crates/lucisv_server/src/state.rs:349` and `:1061`) was already right by
|
||||
inspection and by trace, but three of the charter's named attacks had no
|
||||
regression test, meaning a future refactor could break any of them silently:
|
||||
- *Recency, not insertion order.* `cached_view`'s `rotate_right` had no test
|
||||
at all. Added
|
||||
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`:
|
||||
fills the cache, re-touches the oldest entry, adds a fifth file, and
|
||||
requires the just-touched file to survive while the untouched one is what
|
||||
falls off instead.
|
||||
- *`update_one` selectivity.* Every existing invalidation test warms one
|
||||
file's view at a time, so a hypothetical `update_one` that widened to
|
||||
`views.clear()` would still pass all of them. Added
|
||||
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`.
|
||||
- *A second oversized file.* The existing bound test caches exactly one
|
||||
file over the byte budget; it never tries a second one. Added
|
||||
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`,
|
||||
confirming the cache stays at one entry (the newest) rather than
|
||||
accumulating unbounded huge files.
|
||||
All three pass against the round's code unmodified — genuine coverage gaps,
|
||||
not bugs.
|
||||
|
||||
**4. Format bump — the single-decl test's premise checked, and generalized.**
|
||||
`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread`
|
||||
genuinely constructs a format-3 record (verified by hand: `strip_the_line_
|
||||
fields` removes exactly the two trailing fields of the one declaration `M`
|
||||
has, and the record that results is what format 3 actually wrote — not merely
|
||||
a v3 header over v4 bytes). That fixture has only one declaration, so it could
|
||||
not have caught a field-shift that landed on a *second* declaration's fields
|
||||
rather than on a tag literal. Added
|
||||
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_
|
||||
rejected_not_misread`, generalizing the stripper to N declarations (both units
|
||||
and members) and covering a two-unit file and a mixed unit+split-port-member
|
||||
file. Both decode to `None`, confirming the structural reason this is safe in
|
||||
general: a field-shift by exactly one declaration's two line-fields always
|
||||
lands either on a tag literal (`"M"`, `"I"`, …) or on the next declaration's
|
||||
`name`/`kind` string fields, and a Verilog identifier can never parse as
|
||||
`u32`, so `Reader::num` fails and `decode` returns `None` rather than building
|
||||
a `Decl` out of someone else's fields. No misread constructed; the
|
||||
"guilty until proven innocent" bar is met.
|
||||
|
||||
**5. Equivalence — confirmed, not just claimed.** `cargo test --workspace`
|
||||
green with 0 failures both before and after this pass's additions (dev's
|
||||
counts: `lucisv_server` 1210 passed/24 ignored, `vlog_semantic` `workspace` 66
|
||||
passed — both unmodified by this pass except for the new tests below). Read
|
||||
the `hover.rs` and `locate.rs` diffs directly: the live-buffer branch is
|
||||
untouched, `location()`'s open-buffer arm is a straight substitution
|
||||
(`doc.positions()` for the old `Positions::new(&text, &index)` built from a
|
||||
clone of the same text), and the disk branch is the only place behavior can
|
||||
differ — which is exactly the one documented corner (an unreadable closed
|
||||
file now shows its indexed line). No other behavior change found.
|
||||
|
||||
**6. Numbers reproduced**, `--release`, this machine, this session:
|
||||
- `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`: first
|
||||
touch 5.75 ms (instantiation) / 5.65 ms (port), repeat 1.35 µs / 1.89 µs —
|
||||
same order as the README's 6.23 ms / 0.95 µs and 5.92 ms / 0.99 µs; run-
|
||||
to-run noise, not drift.
|
||||
- `state::tests::qa_perf_cold_warm_and_half_warm_scans` (860-file corpus):
|
||||
store size **2 380 790 bytes** — an exact match to the README's "after"
|
||||
figure, confirming the +68 KB / 2.9 % growth claim against the real
|
||||
corpus rather than trusting the doc's arithmetic. Scan times (325 / 350 /
|
||||
186 ms) were in the same band as the README's (343 / 374 / 200 ms);
|
||||
machine noise, no regression.
|
||||
- `e2e::a_hover_issued_during_the_initial_scan_waits_for_it`: 748.7 ms cold
|
||||
/ 274.0 ms warm for the first hover issued the moment `initialized` is
|
||||
sent, vs. 26.3 µs / 40.2 µs once the scan is done — the same four-orders-
|
||||
of-magnitude gap the README reports (780 / 287 ms vs. 64 / 61 µs). The
|
||||
test genuinely exercises the wait (it asserts the answer resolves
|
||||
correctly across files, and the two timings are taken across the real
|
||||
wire protocol against the shipped binary) — the Handshake in this
|
||||
README's "Suspect 2" section is accurate and not overstated.
|
||||
|
||||
**7. Full gates**, run after adding the tests above:
|
||||
- `cargo fmt --all -- --check`: clean (after formatting the new tests —
|
||||
two blocks needed `cargo fmt`'s wrapping, applied).
|
||||
- `cargo clippy --all-targets --workspace`: clean, no warnings.
|
||||
- `cargo test --workspace`: green. `lucisv_server` unit tests **1214
|
||||
passed** (dev's 1210 + this pass's 4), `vlog_semantic` `workspace` suite
|
||||
**67 passed** (dev's 66 + this pass's 1). 0 failed anywhere in the
|
||||
workspace, including doctests.
|
||||
- `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**Tests added this pass** (5, all permanent regressions, all green):
|
||||
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`,
|
||||
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`,
|
||||
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`,
|
||||
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`
|
||||
(all `crates/lucisv_server/src/`), and
|
||||
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_rejected_not_misread`
|
||||
(`crates/vlog_semantic/tests/workspace.rs`).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
|
||||
independently (fmt clean, clippy silent, 2440 workspace tests green).
|
||||
This round is the owner's design implemented at the right altitude:
|
||||
`DeclLines` as a field on the carrier the index already had — not a
|
||||
parallel table — so ports got their lines for free through the member
|
||||
entries and the extension story is "add a field, bump the format",
|
||||
exactly the flexibility the owner asked for. The +68 KB store growth
|
||||
on the 860-file corpus scales to the owner's 20 000-module thought
|
||||
experiment at the few-tens-of-KB order they predicted. The `FileView`
|
||||
cache is honest about its one unwatchable staleness case and leans on
|
||||
`spells_exactly` correctly (a stale view omits, never lies); QA's
|
||||
staleness repro pins the heading/snippet pair going stale *together*.
|
||||
The dev's rewrite of the format-discard test from a pinned literal to
|
||||
all-previous-formats is the kind of fix that outlives the round.
|
||||
Suspect 2 — the first request of a session waiting 287–780 ms behind
|
||||
the startup scan — is confirmed genuine by dev and QA independently
|
||||
and is the dominant remainder of the owner's "slow on first try";
|
||||
correctly filed as a Handshake, next round's work. Accepted; committed
|
||||
by the lead.
|
||||
@@ -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
|
||||
|
||||
@@ -216,7 +216,18 @@ impl WorkspaceIndex {
|
||||
- Since indexed navigation (2026-08-27), the private facts also carry compact
|
||||
local/external reference records used to rebuild declaration-to-occurrence
|
||||
postings. That encoding change bumped `FACTS_FORMAT` from 1 to 2; no cache
|
||||
migration is attempted or needed.
|
||||
migration is attempted or needed. **2 → 3** (2026-08-28,
|
||||
`docs/features/port-detail-spans/README.md`): each declaration gained its
|
||||
`detail_span`. **3 → 4** (2026-08-28,
|
||||
`docs/features/hover-line-index/README.md`): each declaration gained its two
|
||||
*line numbers*, which is what lets a server print `file:line` for an indexed
|
||||
declaration without reading that file. Same rule each time, same
|
||||
consequence: the store is discarded whole on the first scan after the
|
||||
upgrade and rewritten — measured at about 175 ms over the 860-file corpus,
|
||||
once. `a_store_from_any_previous_facts_format_is_dropped_not_misread` now
|
||||
checks **every** format this build is not, rather than the one literal
|
||||
number it was pinned at, so the next bump inherits the test.
|
||||
The store grew 68 KB (2.9 %) for the lines.
|
||||
- `record_path` is public separately because a store keyed by path reads that
|
||||
field out of every record it holds and decodes only the ones it is asked
|
||||
for.
|
||||
@@ -350,7 +361,13 @@ name span `19..20`), no members, one instantiation edge (of `sub`, owned by
|
||||
`m` whose name is at `19..20` and whose declaration runs `12..41`, with the
|
||||
site's own name span `22..25`), no subclasses, and one external reference fact
|
||||
(`e`, name `sub`, one resolution path also named `sub`, occurrence `22..25`),
|
||||
then the checksum. The record is what lies between the hash field and the
|
||||
then the checksum. **The example is written at `FACTS_FORMAT` 2 and is kept
|
||||
for its shape, not its field count**: since then every declaration also
|
||||
carries its detail span (`0 0` when there is none, format 3) and its two line
|
||||
numbers (format 4), so a real record today has four more numbers per
|
||||
declaration than the one above. The framing — one line, tab-separated,
|
||||
length-prefixed lists, checksum last — is what the example is for and is
|
||||
unchanged. The record is what lies between the hash field and the
|
||||
checksum; both hashes above are illustrative.
|
||||
|
||||
**Any change to what a record holds or how it is written bumps
|
||||
|
||||
@@ -161,6 +161,65 @@ pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups,
|
||||
- `index_order` stays public and unchanged: the server needs the work list's
|
||||
*length* before the first parse for the progress denominator.
|
||||
|
||||
### `vlog_semantic` — facts from an analysis the caller already has (2026-08-28)
|
||||
|
||||
Two additions, both "the same thing with the parse already done", in the shape
|
||||
`IndexBuilder::add_facts` already had:
|
||||
|
||||
```rust
|
||||
impl FileFacts {
|
||||
pub fn from_analysis(path: PathBuf, tree: &SourceFile,
|
||||
defines: &DefineTable, sem: &Semantics) -> FileFacts;
|
||||
}
|
||||
impl WorkspaceIndex {
|
||||
pub fn update_facts(&mut self, facts: FileFacts); // update_file, no parse
|
||||
}
|
||||
```
|
||||
|
||||
- **`FileFacts::of` is now literally `parse_and_collect` + `analyze` +
|
||||
`from_analysis`.** The fact walk moved into the new function and `of` calls
|
||||
it, so there is one implementation and not two: the equivalence the reuse
|
||||
needs holds by construction, not by care. What a caller promises is only that
|
||||
`tree`, `defines` and `sem` really are the analysis of the text at `path`.
|
||||
- **`update_facts` is `update_file`'s body**, with the same contract: what is
|
||||
left is the index a whole build over the same file set would have produced.
|
||||
`update_file` is now `self.update_facts(facts_of(path, src))`.
|
||||
- No `FACTS_FORMAT` change, no new field, no new dependency: this round adds a
|
||||
second *door* to the record, never a second *shape* of it.
|
||||
|
||||
### `lucisv_server::state` — a `Document` can hand over its own facts
|
||||
|
||||
- `Document::facts(path) -> FileFacts` and `Document::words() -> Vec<String>`
|
||||
are **new and public**: what an open buffer contributes to the index and to
|
||||
the completion word table, read off the `tree`/`defines`/`semantics` and the
|
||||
`tokens` it already holds. Never called for a fast-path buffer, whose analysis
|
||||
is the analysis of the empty file and which contributes nothing anyway.
|
||||
- **`IndexEvent::Analyzed { done, total, path }` is a new variant** — one file
|
||||
went into the index from an open buffer's own analysis. Its own variant rather
|
||||
than `Cached` so that "from cache" keeps meaning the persistent store and
|
||||
nothing else; `server.rs` logs `analyzed: <path>` and, deliberately, adds no
|
||||
clause to the progress bar's end message (see the work log).
|
||||
- `collect_sources` takes a `HeldAnalyses` argument, because it has two
|
||||
callers with different needs: an index rebuild wants the buffers' records,
|
||||
a refactoring reads the texts and nothing else and would be paying for
|
||||
records nothing looks at.
|
||||
- `collect_sources` no longer reads a file from disk when an open buffer speaks
|
||||
for it. The text was read and then thrown away; the size cap is still
|
||||
consulted first, so an oversized file still reports itself `Skipped` exactly
|
||||
as before.
|
||||
|
||||
### `lucisv_server::candidates` — words from a token stream
|
||||
|
||||
- `Candidates::build(index, sources, known: HashMap<PathBuf, Vec<String>>)`
|
||||
takes a third argument: the words of the files whose token stream the caller
|
||||
already has. A file listed there is not lexed again; a file absent from it is
|
||||
lexed exactly as every file used to be.
|
||||
- `Candidates::update_words(index, path, words)` is `update_file` with the lex
|
||||
already done, and `update_file` delegates to it.
|
||||
- `words_of_tokens(tokens)` is `pub(crate)`: the whole of `words_in` after the
|
||||
lex, so the two roads to a file's words are one function over one token
|
||||
stream.
|
||||
|
||||
### `lucisv_server::settings`
|
||||
|
||||
- Two new fields, `index_scope: IndexScope` (`Folder` | `Workspace`, default
|
||||
@@ -224,6 +283,34 @@ pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups,
|
||||
- [x] 19 new tests (12 state, 2 server, 1 e2e, 2 vlog_semantic, 2 settings),
|
||||
3 existing ones extended, 1 superseded test rewritten; every other test
|
||||
in the crate that wanted the whole workspace now says so
|
||||
### Round 19 — a rescan stops re-parsing what is already analyzed (2026-08-28)
|
||||
|
||||
- [x] Traced where a scope-widening `didOpen`'s 213 ms actually goes, per stage,
|
||||
and wrote it down (work log)
|
||||
- [x] An open buffer's **index facts** come from the analysis it already holds
|
||||
(`FileFacts::from_analysis`), on the whole-rebuild path and on
|
||||
`update_one`'s incremental one
|
||||
- [x] An open buffer's **completion words** come from the tokens it was analyzed
|
||||
from (`words_of_tokens`), on both paths
|
||||
- [x] The disk copy of a file an open buffer speaks for is no longer read
|
||||
- [x] `IndexEvent::Analyzed`, logged as `analyzed: <path>`, so "from cache"
|
||||
still means the persistent store
|
||||
- [x] Equivalence pinned six ways: encoded-record equality across 860 corpus
|
||||
files and 13 crafted shapes, index fingerprint equality at workspace
|
||||
scale, `update_facts` == `update_file`, and the server-level
|
||||
"same index and same completion tables as the same bytes on disk"
|
||||
- [x] **~228 ms → ~23 ms** on the same probe, with the closed-buffer floor
|
||||
unmoved at ~12 ms
|
||||
- [ ] **Not done, deliberately:** no incremental *widen* (index only the newly
|
||||
in-scope files and keep the rest). See the work log — it cannot hold the
|
||||
brief's own fingerprint-equivalence test while other buffers carry unsaved
|
||||
edits, and it would not have touched the 68 ms re-lex or any rescan that a
|
||||
`didOpen` did not trigger.
|
||||
- [ ] **Not done, deliberately:** the remaining ~11 ms an open 1.4 MB buffer
|
||||
adds to a rescan is the fact walk (1.7 ms), the word set (3.1 ms) and the
|
||||
workspace-wide word table taking 40 000 identifiers back in. It is real
|
||||
work over real content, not a repeat of work already done.
|
||||
|
||||
- [ ] **Not done, deliberately:** no `lucisv.toml` key for either setting. They
|
||||
are editor-session resource settings — how much of *this machine's* time
|
||||
to spend — not project style, the same reason `maxFileSize` has none.
|
||||
@@ -358,6 +445,184 @@ The 19 new tests, the 3 extended and the 1 rewritten, and what each is for:
|
||||
| `the_folder_scope_widens_when_a_file_in_another_folder_is_opened` (e2e) | the real binary: definition into a sibling folder empty, opening it resolves, and a `"workspace"` client resolves immediately |
|
||||
| `indexing_reports_its_progress_over_the_wire` (e2e, updated) | the model on the wire: three bars, `0 files indexed` then `1 file indexed` twice |
|
||||
|
||||
### 2026-08-28 — dev agent (a rescan stops re-parsing what is already analyzed)
|
||||
|
||||
**The symptom, reproduced first.** `nav.rs`'s
|
||||
`qa_didopen_latency_when_a_new_folder_widens_the_scope`, `--release`, three
|
||||
runs on `HEAD`: the widening `didOpen` **227.2 / 229.3 / 229.4 ms**, the rescan
|
||||
alone **224.5 / 224.7 / 225.4 ms**, and **12.5 / 13.1 / 12.6 ms** for the same
|
||||
rescan with the 1.4 MB `top.sv` closed. (The closed number is the floor for a
|
||||
reason worth naming: `top.sv` is 1.4 MB, over the 1 MiB default
|
||||
`lucisv.index.maxFileSize`, so with no buffer open it is not walked at all. The
|
||||
"13 ms" is the other 400 files, not 401.)
|
||||
|
||||
**Where the 210 ms actually goes.** `rebuild_index_with` timed stage by stage,
|
||||
with the buffer open, per rescan:
|
||||
|
||||
| stage | with the buffer open | with it closed |
|
||||
|---|---|---|
|
||||
| `collect_sources` (401 reads) | 9.5 ms | 8.4 ms |
|
||||
| the facts loop | **133.5 ms** | 1.5 ms |
|
||||
| `IndexBuilder::finish` | 0.4 ms | 0.12 ms |
|
||||
| `Candidates::build` | **68.5 ms** | 0.85 ms |
|
||||
| `IncludeGraph::build` | 0.84 ms | 0.14 ms |
|
||||
| overlay refresh | 0.12 ms | ~0 |
|
||||
|
||||
So the brief's "210 ms of re-lexing and re-parsing the open buffer" is right in
|
||||
total and **understates the shape**: the buffer was lexed *twice* per rescan.
|
||||
Once inside `FileFacts::of` (tokenize 62 ms, parse 66 ms, `analyze` 18 ms,
|
||||
the fact walk under 2 ms — 133 ms in all), and again inside
|
||||
`Candidates::build`, whose `words_in` re-lexes every file's text to harvest
|
||||
identifiers (62 ms of the 68 ms). A third, smaller waste sat in
|
||||
`collect_sources`, which read the 1.4 MB disk copy of `top.sv` and then threw
|
||||
it away because the buffer overrides it. Every one of those three is work this
|
||||
server had already done: the `Document` for that buffer holds the tokens, the
|
||||
tree, the define table and the `Semantics`, all built from the same text by the
|
||||
same functions, at the last keystroke.
|
||||
|
||||
**Shape taken: (b), extended to the completion words. (a) was investigated and
|
||||
rejected, on two grounds.**
|
||||
|
||||
- **(a) cannot hold its own mandatory test.** The brief's hard requirement for
|
||||
an incremental widen is that the widened index fingerprint byte-identically
|
||||
to a fresh full build. It does not, in a case that is easy to reach: the
|
||||
index is rebuilt on save, not on change, so between two rebuilds any open
|
||||
buffer may carry unsaved edits. A *full* rebuild at the widening `didOpen`
|
||||
indexes those edits (`collect_sources` overlays live buffer text); an
|
||||
incremental widen that indexed only the newly in-scope files would not. That
|
||||
is an answer change — type `package p;` into an open buffer, jump into a new
|
||||
folder, and the two shapes disagree about whether `p` exists — and the
|
||||
fingerprint test would catch it as a failure, correctly. Making (a) safe means
|
||||
re-indexing the changed buffers anyway, which is (b) with a diff bolted on
|
||||
in front.
|
||||
- **(a) would have fixed a third of it.** It touches only the facts loop, and
|
||||
only on the rescans a widen triggers. The 68 ms word re-lex is in
|
||||
`Candidates::build`, which a widen rebuilds whatever the file list did; and
|
||||
every *other* rescan with a big buffer open — a save that falls back to a
|
||||
whole rebuild, a settings change, a folder event, a watched file — keeps
|
||||
paying the full 200 ms. (b) is one rule that covers all of them: **an open
|
||||
buffer's finished analysis is what the buffer contributes, wherever it is
|
||||
asked.**
|
||||
|
||||
**The equivalence is by construction, then pinned anyway.** `facts_of` was
|
||||
split: everything after `tokenize`/`parse_tolerant`/`analyze` moved into
|
||||
`facts_from_analysis`, and `FileFacts::of` now calls it. So
|
||||
`FileFacts::from_analysis` is not a second way of computing a record — it is
|
||||
the same code entered one step later, which is the difference between an
|
||||
equivalence that has to be tested for and one that has to be *broken* to fail.
|
||||
The same split gives `words_of_tokens` (the whole of `words_in` after the lex)
|
||||
and `WorkspaceIndex::update_facts` (the whole of `update_file` after the
|
||||
parse). What is left to prove is the narrow claim that `Document::new`'s
|
||||
analysis is `facts_of`'s analysis — two separate call sites of the same three
|
||||
functions, including the all-or-nothing lex-failure branch — and that is what
|
||||
the corpus sweeps are for.
|
||||
|
||||
**The reuse is wired where the override already lives.** `collect_sources` is
|
||||
the one place that decides "this buffer's text beats the disk copy"; the facts
|
||||
and the words are now taken from the same `Document` in the same loop
|
||||
iteration, so a record and the text beside it can never describe different
|
||||
bytes. `rebuild_index_with` consults that map *before* the persistent cache,
|
||||
deliberately: an open buffer's own analysis is right even when the buffer has
|
||||
unsaved edits, which is exactly when a content-keyed store has nothing to
|
||||
offer. It still writes the record through to the store, so the next session
|
||||
starts from it.
|
||||
|
||||
**One argument rather than one wasted walk.** `collect_sources` has a second
|
||||
caller — `sources()`, which every refactoring reads the workspace through — and
|
||||
it wants the texts alone. Building a record and a word set off every open buffer
|
||||
for it would be ~5 ms of dead work per `prepareRename` with a 1.4 MB buffer
|
||||
open, so the function takes a `HeldAnalyses` argument saying which caller it is.
|
||||
A boolean would have read as `collect_sources(watch, true)` at the call site;
|
||||
the two-variant enum says what the `true` means.
|
||||
|
||||
**`update_one` takes the same shortcut**, through the new `analysis_of`, which
|
||||
finds the buffer the same way `current_text` does — so a `didSave` on a big
|
||||
buffer stops re-parsing it too. That is not the brief's headline case but it is
|
||||
the same waste on the path a user hits most often.
|
||||
|
||||
**A third event word rather than a fourth meaning for `cached`.**
|
||||
`IndexEvent::Analyzed` is its own variant so "N from cache" in the progress
|
||||
bar's end message keeps meaning the persistent store and nothing else — that
|
||||
sentence is `index-persistence`'s, and e2e transcripts assert it. The per-file
|
||||
log gains `analyzed: <path>`; the end message gains **nothing**, because one
|
||||
file out of a workspace is not why a scan finished fast, and a bar that grew a
|
||||
clause in every session with a file open would say less rather than more.
|
||||
`Analyzed` still ticks the bar, like the other two: it is a file of the work
|
||||
list.
|
||||
|
||||
**Two existing tests moved, both for the same honest reason.**
|
||||
`the_open_files_are_indexed_first_and_the_index_cannot_tell` counted `Parsing`
|
||||
events to check the *order* of the work list; it now counts all three routes,
|
||||
because the open buffer it is watching no longer parses.
|
||||
`the_cache_never_puts_back_a_file_the_scan_no_longer_visits` asserted its open
|
||||
buffer came from the store; it now asserts it came from its own analysis, and
|
||||
also that it appears on neither of the other two lists — the test's real point
|
||||
(`tb/b.sv` has a record and is still not an indexed file) is untouched.
|
||||
|
||||
**After, same probe, three runs:** the widening `didOpen` **22.7 / 23.2 /
|
||||
24.0 ms**, the rescan alone **22.6 / 23.1 / 24.7 ms**, the closed-buffer floor
|
||||
**11.5 / 12.8 / 12.4 ms** — unmoved, as it must be. **~228 ms → ~23 ms, 10×**,
|
||||
and the open 1.4 MB buffer's own share of a rescan went from ~212 ms to ~11 ms.
|
||||
The probe now prints that share directly and permanently, so the claim is
|
||||
re-measurable rather than remembered:
|
||||
|
||||
```
|
||||
That buffer's own share: facts 140.3ms parsed vs 1.67ms reused,
|
||||
words 62.9ms re-lexed vs 3.09ms reused
|
||||
```
|
||||
|
||||
`references-nav`'s own probe is unchanged and green on the same run
|
||||
(110 µs cross-file references either direction, 1.18 ms for the in-file
|
||||
fallback on a name used 10 001 times), which is what says this round did not
|
||||
pay for its rescan out of the request path.
|
||||
|
||||
**What is left, and why it is not waste.** The ~12 ms the open buffer still
|
||||
adds is the fact walk over its tree (1.7 ms), the identifier set over its
|
||||
tokens (3.1 ms), and `Candidates::build` taking 40 000 identifiers into the
|
||||
workspace-wide word table. All three are work over content that really is in
|
||||
the index; none of them repeats work already done.
|
||||
|
||||
**Tests added (6).** `vlog_semantic`:
|
||||
`facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text`
|
||||
(13 crafted shapes — empty, unlexable, tolerant-parse-with-errors, packages,
|
||||
classes, nested classes, `` `define``/`` `undef``, imports and `::` paths, a
|
||||
file-scope instantiation that is deliberately not an edge, a generate body),
|
||||
`the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus` (860 files,
|
||||
encoded records byte-identical),
|
||||
`an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text`
|
||||
(workspace scale, files added in reverse path order so the reuse cannot smuggle
|
||||
an ordering in, plus `update_facts` == `update_file`). `lucisv_server`:
|
||||
`an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would`
|
||||
(an **edited** buffer — bytes nowhere on disk — against the same bytes written
|
||||
to disk and parsed: same fingerprint, same words, same unit candidates, and the
|
||||
event lists prove the two really took different routes),
|
||||
`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`
|
||||
(the narrow claim, over real `Document::new`s — this is the one that catches
|
||||
`Document::new` drifting from `facts_of`),
|
||||
`a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse`.
|
||||
|
||||
**Attacked before believing.** Three deliberate mutations, each run and each
|
||||
caught: giving `Document::facts` an empty `DefineTable` fails both the crafted
|
||||
fingerprint test and the corpus record sweep; dropping every 97th token in
|
||||
`Document::new` fails the corpus words sweep. (A mutation to `words_of_tokens`
|
||||
itself is *not* caught, and correctly so — both roads go through that one
|
||||
function, which is the point of the split.)
|
||||
|
||||
**Files touched:** `crates/vlog_semantic/src/workspace.rs`,
|
||||
`crates/vlog_semantic/tests/workspace.rs`,
|
||||
`crates/lucisv_server/src/state.rs`, `crates/lucisv_server/src/candidates.rs`,
|
||||
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/nav.rs`
|
||||
(the probe's own numbers), this README,
|
||||
`docs/features/references-nav/README.md` (the Handshake, delivered),
|
||||
`docs/features/indexing-ux/README.md` (the new log word), `TODO.md`. No new
|
||||
dependency, no `FACTS_FORMAT` change, no scope-semantics change, no version
|
||||
bump, no commits.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2413
|
||||
passed, 0 failed** (2407 on `HEAD`, measured — 6 new). `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent (gates, attack surfaces, mechanical-sweep audit)
|
||||
@@ -576,8 +841,220 @@ and the stale-comment LOW items are follow-up hygiene, not blockers — every
|
||||
behavior they probe was independently verified correct by hand in this
|
||||
session.
|
||||
|
||||
### 2026-08-28 — QA agent (round 19: drift, staleness, threshold and log-semantics attacks)
|
||||
|
||||
**Charter.** The round under review (dev work log "a rescan stops re-parsing
|
||||
what is already analyzed", same date) claims an open buffer's index facts and
|
||||
completion words can be read off its already-held analysis instead of
|
||||
re-parsed, and that this is safe because `FileFacts::of` and
|
||||
`Document::new`/`FileFacts::from_analysis` are now one code path entered at
|
||||
different points. The charter was to attack exactly the seam where the two
|
||||
routes could still disagree — a masked-corruption seed in CLAUDE.md's terms —
|
||||
plus staleness, the large-file threshold boundary, the cap interaction, and
|
||||
the new log word. **No drift, no staleness bug, and no cap regression were
|
||||
found.** One real, pre-existing (round-independent) robustness gap was found
|
||||
and is filed separately, not against this round.
|
||||
|
||||
**1. Drift attack — crafted non-corpus shapes, both facts and words.**
|
||||
Traced `Document::new` (`crates/lucisv_server/src/state.rs:64-92`) against
|
||||
`parse_and_collect`/`facts_of` (`crates/vlog_semantic/src/workspace.rs:773-793,
|
||||
1023-1034`) line by line: same `tokenize` → `collect_defines`/`parse_tolerant`
|
||||
on the `Ok` branch (same token vector, so `collect_defines` reads the same
|
||||
bytes in both places), same `parse_source_tolerant` on the `Err` branch. The
|
||||
one asymmetry — `Document::new` computes `collect_defines(&tokens)`
|
||||
unconditionally, including when `tokens` is the empty `Vec` from a lex
|
||||
failure, while `facts_of`'s `Err` arm substitutes `DefineTable::default()`
|
||||
directly — cannot drift: `DefineTable` derives `Default` as `entries:
|
||||
Vec::new()`, and `collect_defines(&[])` produces exactly that (confirmed by
|
||||
reading `collect_defines`, `crates/vlog_parser/src/defines.rs:91-104`: the
|
||||
loop never runs on an empty slice). Also confirmed `analyze(tree, text)`
|
||||
(`crates/vlog_semantic/src/lib.rs:65`) takes only the tree and the text — no
|
||||
workspace-index dependency — so nothing about the *workspace* state at the
|
||||
moment a buffer was analyzed can make its `semantics` differ from a fresh
|
||||
parse's.
|
||||
|
||||
Verified by construction is not verified by attack, so 16 crafted non-corpus
|
||||
shapes were run through the real `Document`+`FileFacts::of` pair (encoded
|
||||
facts equality and sorted-word equality), added as a permanent test:
|
||||
`qa_attack_crafted_non_corpus_shapes_drift_check`
|
||||
(`crates/lucisv_server/src/state.rs:3361-3441`) — a UTF-8 BOM, CRLF, BOM+CRLF,
|
||||
an unterminated block comment, an unterminated attribute, an unterminated
|
||||
macro call, an unterminated string, an embedded control character, deep
|
||||
`begin`/`end` nesting, deep paren nesting, 500 `` `define``s, `` `include``
|
||||
directives, a tree with parse-error recovery, mixed line endings, an embedded
|
||||
NUL, and tabs/form-feeds. **All 16 passed — no drift.** (The BOM cases lex
|
||||
clean, confirmed separately: `tokenize` silently absorbs a leading BOM rather
|
||||
than erroring, so they exercise the `Ok` branch like ordinary source, not the
|
||||
lex-failure one — noted so the case list isn't mistaken for dead weight.)
|
||||
|
||||
**One robustness finding, filed as out-of-scope, not blocking this round —
|
||||
LOW/INFORMATIONAL, pre-existing.** Deep `begin`/`end` nesting
|
||||
(500 levels) overflows the stack under `cargo test`'s default per-test-thread
|
||||
stack (2 MiB) — and it does so calling **`FileFacts::of` alone**, no
|
||||
`Document`, no reuse, nothing this round touched. Reproduced identically on
|
||||
`git stash`-ed pristine `master` with the same crafted input run through a
|
||||
temporary `vlog_semantic` test (`cargo test -p vlog_semantic` on unmodified
|
||||
`HEAD`: same abort). Because both routes being compared fail *identically*,
|
||||
this is the opposite of the drift this charter hunts for, and it is not a
|
||||
regression — the recursive-descent parser/analyzer has always had this
|
||||
ceiling; a real server thread's default OS stack is larger (8 MiB main-thread
|
||||
default on macOS, confirmed by running the same input outside the test
|
||||
harness) so this is unlikely to bite in the shipped binary at 500 levels, but
|
||||
the underlying unbounded-recursion-depth issue is real and worth a filed
|
||||
follow-up (a recursion-depth guard in the parser/analyzer, or running the LSP
|
||||
request-handling thread with an explicit larger stack). The permanent test
|
||||
above works around it by running on a dedicated 64 MiB-stack thread, which is
|
||||
what let the drift comparison actually exercise 500-level nesting without
|
||||
tripping the unrelated ceiling. Spun off as a background task rather than
|
||||
fixed here — it is not in this round's files or in `verify.rs`, and touching
|
||||
the parser's recursion handling is a bigger, separate change.
|
||||
|
||||
**2. Staleness attacks.** `qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan`
|
||||
(`crates/lucisv_server/src/state.rs:3482-3517`, new): an open buffer edited
|
||||
away from disk content (never saved) rescans from the live edit — confirmed
|
||||
via the `Analyzed` route and the indexed member changing from `ON_DISK` to
|
||||
`IN_BUFFER` — and, after `close_document` with no save in between, the very
|
||||
next rescan reparses from disk (`Parsing` route) and the index reverts to
|
||||
`ON_DISK`, with no trace of the closed buffer's analysis anywhere. Also traced
|
||||
structurally: the persistent `IndexCache` is keyed by a content hash of the
|
||||
exact bytes (`crates/lucisv_server/src/index_cache.rs:135-157`,
|
||||
`content_hash(text.as_bytes())`), so even though `rebuild_index_with` writes
|
||||
an open buffer's unsaved-edit facts through to the cache
|
||||
(`state.rs`'s facts-loop, `self.cache.record(&facts, text)`), a later lookup
|
||||
against disk's differently-hashed bytes cannot accidentally hit that record —
|
||||
the two are different cache keys by construction, not by care. The
|
||||
"`didSave` where disk write happens after the rescan reads" race cannot occur
|
||||
either, traced rather than merely tested: `server.rs`'s `DidSaveTextDocument`
|
||||
handler (`crates/lucisv_server/src/server.rs:1319-1334`) calls
|
||||
`self.set_document` (updating the in-memory `Document` from the notification's
|
||||
own text, when present) *before* `reindex_one`/`reindex`, and the reused facts
|
||||
come from that in-memory `Document`, never from a disk read — so there is no
|
||||
window in which the index can read disk before the save's bytes land there.
|
||||
|
||||
**3. Large-file threshold crossing via unsaved edits, both directions** —
|
||||
the charter's explicit "break it differently" ask, since the dev's own test
|
||||
only checks `doc.large` flips, not that a rescan's *event routing* follows it
|
||||
mid-session. Two new tests:
|
||||
`qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session`
|
||||
and `qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse`
|
||||
(`state.rs:3520-3596`). Small-on-disk/huge-live: a real analysis is reused
|
||||
(`Analyzed`) until the buffer is edited past the threshold, at which point the
|
||||
very next rescan drops it from every list (`analyzed` empty, `parsed` empty —
|
||||
contributes nothing at all, matching the fast-path contract), and shrinking it
|
||||
back reinstates reuse on the next rescan. Huge-on-disk/small-live: `doc.large`
|
||||
is decided from the buffer's own live text length (`is_large`,
|
||||
`state.rs:1298-1301`) and never from what is on disk, so the on-disk size is
|
||||
provably irrelevant to the routing — the buffer is on the fast path the
|
||||
instant it is opened with huge text, whatever the disk copy says, and reuse
|
||||
resumes the instant it is edited back down. **No boundary bug in either
|
||||
direction.**
|
||||
|
||||
**4. Cap interaction, unchanged in both directions.** New test
|
||||
`qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before`
|
||||
(`state.rs:1780-1817`): an open buffer whose file exceeds `maxFileSize` is
|
||||
still reported `Skipped` once, from `collect_sources`'s disk-phase walk (the
|
||||
`spoken_for` short-circuit this round added only skips the wasted *read*, not
|
||||
the cap check that runs ahead of it — traced in
|
||||
`collect_sources`, `state.rs:930-937`) — and it is still indexed in full
|
||||
afterward, now via `Analyzed` rather than `Parsing`. Confirmed the file is
|
||||
never re-parsed (`parsed` empty) and the content is indexed exactly as before
|
||||
this round. The cap boundary moved in neither direction.
|
||||
|
||||
**5. Event/log semantics — a real gap found and closed.** No test anywhere
|
||||
in the repository — not `state.rs`'s unit tests (which only check the
|
||||
`IndexEvent::Analyzed` *variant*, via the `scan()` helper), not any e2e test —
|
||||
exercised the actual `"analyzed: <path>"` string a real client would receive
|
||||
over `window/logMessage`, despite `docs/features/indexing-ux/README.md`
|
||||
documenting the exact wording. Added
|
||||
`qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan`
|
||||
(`crates/lucisv_server/tests/e2e.rs`, after `the_size_cap_and_the_file_log_work_over_the_wire`):
|
||||
against the real binary, a scope-widening `didOpen` with one open buffer and
|
||||
one disk-only file logs `analyzed: .../m.sv` and `indexing: .../disk_only.sv`
|
||||
— never the other word for the other file — and the follow-up `didSave`
|
||||
(the incremental `reindex_one` path) emits **no** log line at all, confirmed
|
||||
by counting exactly two `analyzed:`/`indexing:` lines in the whole transcript.
|
||||
This also incidentally re-confirms the work log's claim that `reindex_one`
|
||||
sends no per-file log line, which was previously asserted only by a code
|
||||
comment.
|
||||
|
||||
**6. Reproducing the numbers, `--release`, three fresh runs of
|
||||
`qa_didopen_latency_when_a_new_folder_widens_the_scope`:** widening `didOpen`
|
||||
**23.95 / 24.20 / 24.31 ms** (claimed ~23 ms), rescan alone **23.91 / 24.09 /
|
||||
23.88 ms**, closed-buffer floor **12.96 / 12.83 / 12.70 ms** (claimed ~12 ms,
|
||||
unmoved — confirmed unmoved). The buffer's own share, printed by the probe:
|
||||
facts **144.3 ms parsed vs 1.7 ms reused**, words **65.8 ms re-lexed vs
|
||||
3.1 ms reused** — matches the work log's 140.3 ms/1.67 ms and 62.9 ms/3.09 ms
|
||||
within noise. `qa_references_latency_with_a_big_open_top`
|
||||
(references-nav's own probe): **113 µs**/**128 µs** cross-file either
|
||||
direction (claimed ~110 µs), **1.19 ms** for the in-file fallback on a name
|
||||
used 10 001× (claimed 1.18 ms) — unmoved, confirming this round did not move
|
||||
cost onto the request path.
|
||||
|
||||
**7. Gates.** `cargo fmt --all -- --check`: clean (after formatting the new
|
||||
tests). `cargo clippy --all-targets --workspace`: zero warnings (two clippy
|
||||
hits in QA's own new tests — `cloned_ref_to_slice_refs`,
|
||||
`useless_format` — fixed before the final run). `cargo test --workspace`: all
|
||||
green, 0 failed, across every crate (lucisv_server's own suite: 1204 passed,
|
||||
23 ignored — the ignored set is the manual latency probes, run separately
|
||||
above). `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: `smoke: OK`. `verify.rs`: no diff (confirmed via
|
||||
`git diff --name-only`). No new `unwrap()`/`expect()`/`panic!` outside
|
||||
`#[cfg(test)]` in the round's diff or in QA's additions (grepped both).
|
||||
|
||||
**One documentation nit, LOW, informational.** This README's Handshakes
|
||||
section (`docs/features/index-scope/README.md:219`) says
|
||||
`words_of_tokens(tokens)` "is `pub(crate)`"; the actual declaration
|
||||
(`crates/lucisv_server/src/candidates.rs:246`) is `pub fn`. Harmless in
|
||||
practice — `lucisv_server` is a `bin`-only crate with no `lib` target
|
||||
(confirmed: `cargo test -p lucisv_server --lib` errors "no library targets
|
||||
found"), and `candidates` is a private `mod` (`main.rs:9`), so there is no
|
||||
larger scope for `pub` to leak into within this crate — but the README's
|
||||
wording doesn't match the code. Worth a one-word fix (`pub` → `pub(crate)`,
|
||||
or the sentence corrected) whenever this file is next touched.
|
||||
|
||||
**Tests added (8), all permanent, all passing.** `crates/lucisv_server/src/state.rs`:
|
||||
`qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before`,
|
||||
`qa_attack_crafted_non_corpus_shapes_drift_check` (+ its `_body` helper, run on
|
||||
a dedicated large-stack thread),
|
||||
`qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan`,
|
||||
`qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session`,
|
||||
`qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse`.
|
||||
`crates/lucisv_server/tests/e2e.rs`:
|
||||
`qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan`.
|
||||
|
||||
**Verdict: SHIP.** The round's central claim — an open buffer's held analysis
|
||||
is byte-identical to a fresh parse's, so reusing it cannot corrupt the index —
|
||||
held against every attack this session could construct, including shapes the
|
||||
dev's own corpus sweep and crafted-shape list did not cover. Staleness, the
|
||||
large-file threshold's two crossing directions, the cap interaction, and the
|
||||
new log word all check out. The one real finding (stack depth) predates this
|
||||
round, affects both compared routes identically, and is filed as a follow-up
|
||||
rather than a blocker.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-28 — lead, rescan-reuse round
|
||||
|
||||
Reviewed the diff and both logs after QA's clean SHIP; gates re-run
|
||||
independently (fmt clean, clippy silent, 2419 workspace tests green).
|
||||
The dev's deviation from the brief's preferred incremental-widen shape
|
||||
is correct and well-argued: a widen that skipped already-indexed files
|
||||
would also skip unsaved buffer edits the full rebuild indexes, an
|
||||
answer change the mandatory fingerprint test would have caught — so
|
||||
shape (b) with the split constructors is the honest one, and the split
|
||||
is genuinely by construction (`facts_of` = parse + `facts_from_analysis`,
|
||||
`words_in` = lex + `words_of_tokens`; one implementation each). The
|
||||
drift attacks QA ran — 16 crafted non-corpus shapes plus both corpus
|
||||
sweeps — are the right coverage for the one risk this design carries,
|
||||
and the staleness/threshold/cap boundary tests close the state-machine
|
||||
edges. `IndexEvent::Analyzed` kept separate from `Cached` so the
|
||||
persistence transcripts keep their meaning: good instinct. ~228 ms →
|
||||
~23 ms reproduced by dev, QA and the probe's own printout. Lead fixed
|
||||
QA's doc nit directly (`words_of_tokens` tightened to `pub(crate)` to
|
||||
match the Handshakes prose; all callers in-crate). The pre-existing
|
||||
deep-nesting overflow QA found on pristine master is correctly out of
|
||||
scope and spun off. Accepted; committed by the lead.
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
|
||||
@@ -216,6 +216,15 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
|
||||
line reads `cached: <path>` where a parsed file's reads `indexing: <path>`,
|
||||
and whose bar tick is identical — a cached file is a file of the work list,
|
||||
and the bar flying through them is the point.
|
||||
**Amended again (index-scope, 2026-08-28):** a third arm,
|
||||
`IndexEvent::Analyzed`, for a file that went into the index from an **open
|
||||
buffer's own finished analysis** rather than from a parse or from the store.
|
||||
Its log line reads `analyzed: <path>`; its bar tick is identical again. It
|
||||
deliberately adds **no** clause to the end message — one file out of a
|
||||
workspace is not why a scan finished fast, and "N from cache" keeps meaning
|
||||
the persistent store and nothing else, which is the sentence
|
||||
`index-persistence`'s e2e transcripts assert. See
|
||||
`docs/features/index-scope/README.md`.
|
||||
- `begin` still carries **no** percentage: the first honest one is the first
|
||||
file's.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -21,15 +21,15 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` |
|
||||
| `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` |
|
||||
| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didSave` once per notification, and for a `didChange` once per **flush** (a typing burst publishes once, not once per keystroke — `docs/features/change-debounce/README.md`) — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, and the composed text is held **dirty** — one `set_document` + one `publish` per *flush*, which is the next request, the next other notification, or a 150 ms quiet period. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` and `docs/features/change-debounce/README.md` |
|
||||
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
|
||||
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` |
|
||||
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built |
|
||||
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md`. The `file:line` half of a cross-file heading costs **no file access**: the line is recorded when the file is indexed (`Def::lines`), so only the snippet still reads, once per file per generation of it through `Workspace::file_view`: `docs/features/hover-line-index/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
|
||||
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
|
||||
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
|
||||
@@ -233,17 +233,19 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`.
|
||||
|
||||
| layer | rebuilt when | cost |
|
||||
|---|---|---|
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`, and every **flush** of the buffers a `didChange` left dirty — once per flush, however many ranges *and* however many notifications it coalesced (`docs/features/change-debounce/README.md`) | one file, full recompute — 2.6 ms at 1 000 lines, 31 ms at 10 000 (`docs/perf/README.md`) |
|
||||
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) |
|
||||
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
|
||||
| the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) |
|
||||
|
||||
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
|
||||
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
|
||||
deferred there. Incremental *sync* did not change that: the wire now carries
|
||||
ranges, but a `didChange` still throws the whole `Document` away and builds a
|
||||
new one — one reparse per notification, which is also the one generation bump
|
||||
the pull-diagnostics `resultId` depends on.
|
||||
**Per-file recompute** is the strategy TODO.md §6 states ("per-file recompute
|
||||
is fine at Verilog file sizes"); salsa is explicitly deferred there.
|
||||
Incremental *sync* did not change that: the wire carries ranges, but a flush
|
||||
still throws the whole `Document` away and builds a new one. What changed on
|
||||
2026-08-28 is *how often*: a `didChange` no longer triggers that recompute
|
||||
itself, so a typing burst costs one reparse and one generation bump — still
|
||||
exactly one of each per flush, which is what the pull-diagnostics `resultId`
|
||||
depends on (`docs/features/change-debounce/README.md`).
|
||||
|
||||
**Which files exist: the folder scope, since 2026-08-27** (index-scope). The
|
||||
index no longer walks the whole workspace by default. The ladder, highest
|
||||
@@ -268,6 +270,19 @@ folder brings it into scope. `"lucisv.index.scope": "workspace"` restores the
|
||||
pre-2026-08-27 behaviour in full. Rules, the clamp, the close decision and the
|
||||
one `.gitignore` gap: `docs/features/index-scope/README.md`.
|
||||
|
||||
**And scope-relative in *time*, since 2026-08-28** (scan-interleave). A
|
||||
**startup** scan of more than 64 files no longer blocks the message loop: it
|
||||
indexes one file at a time and answers whatever the client has already sent
|
||||
between two of them, so the first request of a session comes back in
|
||||
milliseconds instead of waiting out the whole scan (780 ms → 15.5 ms cold over
|
||||
200 files). The price is that such an answer reflects the index **as of that
|
||||
moment** — a declaration in a file the scan has not reached yet does not exist
|
||||
yet, in exactly the sense a declaration outside the scope does not exist. Two
|
||||
narrowings keep that from reaching anywhere it is not worth it: a scan of 64
|
||||
files or fewer runs one shot as it always did, and a request queued *behind* a
|
||||
message that asked for a rescan waits for that rescan, so the loop's order
|
||||
contract is unchanged. `docs/features/scan-interleave/README.md`.
|
||||
|
||||
**Open buffers override disk** in every index rebuild: the scope is walked,
|
||||
each file read, and then every open document with a path replaces the disk
|
||||
copy (adding itself if it exists only in the editor). So the index never
|
||||
@@ -588,14 +603,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
|
||||
@@ -617,8 +647,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`.
|
||||
|
||||
@@ -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.**
|
||||
|
||||
|
||||
@@ -116,10 +116,55 @@ 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
|
||||
@@ -165,6 +210,147 @@ 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()` +
|
||||
@@ -270,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
|
||||
@@ -522,6 +860,24 @@ 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
|
||||
|
||||
@@ -0,0 +1,592 @@
|
||||
# scan-interleave
|
||||
|
||||
## Goal
|
||||
|
||||
`Server::new` ran the whole startup scan before `run()`'s message loop took its
|
||||
first message, so everything a client sent the instant the handshake was done
|
||||
sat in the OS pipe until the scan was over: **780 ms cold store / 287 ms warm**
|
||||
over a 200-file workspace, against 26–64 µs for the same hover once the scan
|
||||
had finished (filed as "suspect 2" in
|
||||
`docs/features/hover-line-index/README.md`, and the larger half of the owner's
|
||||
"hover is really slow on first try"). This round takes the scan apart into
|
||||
per-file steps and drains the message queue between them, so a scan long enough
|
||||
for a person to notice answers questions while it runs. The first hover of a
|
||||
session now comes back in **15.5 ms cold / 12.8 ms warm** on the same fixture —
|
||||
a 50× and 22× improvement — and the scan's own total is unchanged inside
|
||||
run-to-run noise.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **An answer given mid-scan reads the index as of that moment.** It is
|
||||
scope-relative in *time* exactly the way every answer is already
|
||||
scope-relative in *space* (`crates/lucisv_server/README.md`): a declaration in
|
||||
a file the scan has not reached yet is a declaration this server does not know
|
||||
about yet, and it says so by answering nothing rather than by making the
|
||||
client wait. Which files that means depends on how far the scan got, so a
|
||||
mid-scan answer is genuinely **not reproducible** — which is why the rule
|
||||
below narrows the cases it can happen in to the one where it is worth it.
|
||||
- **Only a scan nobody asked for answers mid-way.** The message loop has always
|
||||
promised that everything queued *ahead* of a request is applied before that
|
||||
request is answered. A `didOpen` that widened the scope, a `didSave`, a
|
||||
changed setting or an added workspace folder ask for a rescan, and "applied"
|
||||
for those means the rescan has **run** — one message at a time, the server
|
||||
would have finished it before ever taking the request. So requests that arrive
|
||||
during a rescan wait for it, and only the *startup* scan — which nothing was
|
||||
queued ahead of — answers from a half-built index. See `Server::must_wait`.
|
||||
- **And only a scan long enough to be worth it.** A scan of at most
|
||||
`INTERLEAVE_ABOVE` (64) files is over in a few milliseconds and runs exactly as
|
||||
it always did, one shot, no drains: trading a complete answer for those
|
||||
milliseconds would be a bad bargain. A count rather than a clock, because a
|
||||
rule about elapsed time makes what a server answers depend on how loaded the
|
||||
machine is — which is a property neither a test suite nor a bug report can
|
||||
work with.
|
||||
- **The scan indexes the text each file had when its work list was taken.** A
|
||||
`didOpen` or a `didChange` answered mid-scan changes the *buffer* and not the
|
||||
index — exactly as it does when it lands a millisecond after the scan
|
||||
finished, because neither notification touches the index (a save is what
|
||||
does). So a message answered in the middle of a scan cannot move that scan's
|
||||
result.
|
||||
- **A record written through is a record kept.** A scan a `shutdown` interrupts
|
||||
leaves every file it had already parsed in the persistent store, because the
|
||||
store is appended to per file (`docs/features/index-persistence/README.md`).
|
||||
That was already true of a scan a `kill` interrupted; it is now reachable
|
||||
through the protocol as well.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `vlog_semantic` — `WorkspaceIndex::absorb`
|
||||
|
||||
```rust
|
||||
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
|
||||
/// many files at once — and for **one** merge rather than one each.
|
||||
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]);
|
||||
|
||||
// generic in what rides beside the path, so an owning caller gets the same order
|
||||
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)>;
|
||||
```
|
||||
|
||||
`absorb` keeps the same promise `update_facts` does — what comes out is the
|
||||
index a full `build` over the records it now holds would have produced — and for
|
||||
the same structural reason: the records stay path-sorted and one file to a path,
|
||||
and `merge` is then the loop `IndexBuilder::finish` runs over the same list. It
|
||||
exists because **a merge is a pass over every record the index holds**, which is
|
||||
measured below and is the difference between a linear scan and a quadratic one.
|
||||
|
||||
`index_order`'s lifetime parameter became a type parameter. Every existing
|
||||
caller passes `&str` and is unchanged; the scan passes `String`, because it owns
|
||||
its work list.
|
||||
|
||||
### `lucisv_server::state` — the scan as a value
|
||||
|
||||
```rust
|
||||
pub struct Scan { /* work list, how far through it, what is staged */ }
|
||||
|
||||
impl Scan {
|
||||
pub fn skipped(&self) -> usize;
|
||||
pub fn cached(&self) -> usize;
|
||||
pub fn total(&self) -> usize;
|
||||
pub fn index_next(&mut self, path: &Path) -> bool;
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub fn adopt_roots(&mut self, roots: Vec<PathBuf>);
|
||||
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Scan;
|
||||
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool;
|
||||
pub fn publish_scan(&mut self, scan: &mut Scan);
|
||||
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String>;
|
||||
}
|
||||
```
|
||||
|
||||
**A value rather than a loop, because a callback cannot be handed the workspace
|
||||
it is called from.** `rebuild_index_with` held `&mut self` for the whole scan,
|
||||
so its watcher callback could reach the connection (a disjoint field) but never
|
||||
the workspace — and answering a message needs exactly that. Splitting the loop
|
||||
puts the scan's state somewhere the server can own it, and `rebuild_index_with`
|
||||
is now literally
|
||||
|
||||
```rust
|
||||
let mut scan = self.begin_scan(watch);
|
||||
while self.scan_step(&mut scan, watch) {}
|
||||
self.finish_scan(scan)
|
||||
```
|
||||
|
||||
so "one shot" and "interleaved" are not two scans that have to be kept in step:
|
||||
they are this loop with and without a drain in it. That is what makes the
|
||||
fingerprint equivalence structural rather than tested-and-hoped.
|
||||
|
||||
`skipped`/`cached` moved from `IndexWatch` to `Scan`: they are facts about the
|
||||
scan, and `IndexWatch` is now purely the thing that speaks protocol.
|
||||
`open_roots_with` and `rebuild_index_with` are `#[cfg(test)]` now — the server
|
||||
drives the three calls itself, and every test that just wants an index still
|
||||
calls the one-shot form.
|
||||
|
||||
### `lucisv_server::candidates`, `::includes` — the batch forms
|
||||
|
||||
```rust
|
||||
impl Candidates {
|
||||
pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec<String>)>);
|
||||
}
|
||||
impl IncludeGraph {
|
||||
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]);
|
||||
}
|
||||
```
|
||||
|
||||
Both are the batch form of the incremental update each already had
|
||||
(`update_words`, `update_file`), doing the whole-table half once for the batch
|
||||
instead of once per file. **All three tables are published together, never one
|
||||
of them**: an index that had seen a scanned file while a completion or an
|
||||
include link could not would make "the workspace as far as it has been scanned"
|
||||
three different things at once.
|
||||
|
||||
`candidates::words_in` became `pub(crate)`, because a scan lexes each file's
|
||||
completion words as it reaches it rather than in one pass at the end. That moves
|
||||
work rather than adding it — `Candidates::build` at the end of the scan now
|
||||
finds every file's words already in hand and lexes nothing — and it is what
|
||||
keeps the *tail* of a scan from being an unbroken block longer than one file.
|
||||
|
||||
### `docs/features/hover-line-index` — suspect 2, **DELIVERED**
|
||||
|
||||
That round measured the wait, filed it as a request to "whoever owns the message
|
||||
loop next" and named the probe. This is that round; the probe is flipped and
|
||||
renamed (`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`)
|
||||
and its before-numbers are the ones in the table below.
|
||||
|
||||
## Measured
|
||||
|
||||
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
|
||||
`--release`, `#[ignore]`d probes, `--test-threads=1`. Taken 2026-08-28, before
|
||||
and after, in the same session.
|
||||
|
||||
### The merge cost, measured before the design was chosen
|
||||
|
||||
`perf::publishing_a_half_built_index_mid_scan`, files of 1 000 lines:
|
||||
|
||||
| workspace | one file's parse | one whole merge | one `update_facts` | per-file feeding would cost | against parsing |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| 50 files | 2.35 ms | 0.73 ms | 0.66 ms | 32.8 ms | 117.6 ms |
|
||||
| 200 files | 2.32 ms | 3.35 ms | 3.15 ms | **630.7 ms** | 464.4 ms |
|
||||
| 800 files | 2.23 ms | 15.90 ms | 14.66 ms | **11.73 s** | 1.78 s |
|
||||
|
||||
**So: not per file.** A merge is linear in the whole workspace, so feeding the
|
||||
live index one file at a time is quadratic — at 200 files it would have *more
|
||||
than doubled* the scan, and at 800 files multiplied it by seven. The decision
|
||||
the numbers make is **deferred**: records are staged as they are taken and
|
||||
folded in with one `absorb` per *drain*, and a drain only happens when the queue
|
||||
is not empty. A scan nobody is waiting on therefore pays nothing beyond one
|
||||
`try_recv` per file, and a scan somebody is waiting on pays 3.35 ms per burst at
|
||||
200 files — one and a half files' worth of parse.
|
||||
|
||||
### The latency the round is about
|
||||
|
||||
`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`, 200 files
|
||||
of 1 000 lines with a filelist, over the wire against the real binary:
|
||||
|
||||
| the first hover of a session | before | after |
|
||||
|---|---:|---:|
|
||||
| issued the moment `initialized` was sent, cold store | 780 ms | **15.5 ms** |
|
||||
| — warm store | 287 ms | **12.8 ms** |
|
||||
| the same hover once the scan is done | 64 / 61 µs | 191 / 151 µs |
|
||||
|
||||
Two honest caveats on that table. The "after" figures move with how busy the
|
||||
machine is — a second run minutes later, with the corpus suite running beside
|
||||
it, reported 19.8 ms and 14.0 ms — so read them as *tens of milliseconds
|
||||
against hundreds*, which is the claim, and not as three significant figures.
|
||||
And the last row is the same answer either way, measured differently now: the
|
||||
"after" run waits for the progress bar to come down before asking, which is
|
||||
what makes it a *post*-scan measurement rather than a race with the scan. Both
|
||||
are microseconds and neither is what the round moved.
|
||||
|
||||
### What the scan's total cost
|
||||
|
||||
`state::tests::qa_perf_cold_warm_and_half_warm_scans`, the 860-file corpus,
|
||||
before and after on the same machine minutes apart:
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| no cache | 321.5 ms | 322.0 ms |
|
||||
| cold, filling the store | 351.3 ms | 353.4 ms |
|
||||
| warm, every file from the store | 187.0 ms | 188.6 ms |
|
||||
| the store | 2 380 790 B | 2 380 790 B |
|
||||
|
||||
**+0.2 % / +0.6 % / +0.9 %**, which is well under the "a few percent" this
|
||||
round was allowed — and inside the run-to-run band, which is worth stating with
|
||||
a number of its own: the same "after" measurement taken again on a busier
|
||||
machine reported 357 / 375 / 201 ms, so the pair above is only meaningful
|
||||
*because* it was taken minutes apart in one session on one tree. Nothing was added to the
|
||||
per-file path; the completion word lex moved into it from the tail, and the
|
||||
index is folded in with the same number of merges a one-shot scan always did
|
||||
(one) when nothing is waiting.
|
||||
|
||||
### The floor under a mid-scan answer
|
||||
|
||||
`perf::what_a_scan_does_before_its_first_file`, 200 files of 1 000 lines:
|
||||
|
||||
| | quiet machine | busy machine |
|
||||
|---|---:|---:|
|
||||
| before the first file (resolve the scope, read every file, open the store) | 6.9 ms | 9.8 ms |
|
||||
| one file | 4.0 ms | 5.7 ms |
|
||||
| the other 199 | 682 ms | 723 ms |
|
||||
| finishing (last merge, completion tables, include graph, overlays) | 10.7 ms | 10.9 ms |
|
||||
|
||||
So the 15.5 ms above is the first two rows plus the handshake and the message's
|
||||
own travel, and it is **not** the "single digit ms" the brief hoped for. The
|
||||
first row is one block no drain can break up, and reading the files lazily is
|
||||
what would break it up — filed as a deliberate not-done below with this number
|
||||
attached.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Measure the merge cost before choosing a rhythm; per-file feeding
|
||||
rejected on the numbers above, deferred-and-batched chosen.
|
||||
- [x] `WorkspaceIndex::absorb`, with the fresh-build equivalence tested three
|
||||
ways (a batch of every shape, one batch against the same records in
|
||||
pieces, and an empty batch).
|
||||
- [x] `Scan` + `begin_scan`/`scan_step`/`publish_scan`/`finish_scan`, with
|
||||
`rebuild_index_with` rewritten as the loop over them.
|
||||
- [x] The server drives the scan and drains the queue between files; the
|
||||
queue moved onto `Server` so a scan and `run` share it.
|
||||
- [x] Order preserved: `Server::must_wait` holds a request (and everything
|
||||
behind it) that is queued behind a rescan, and `run` answers what was
|
||||
held before it takes anything newer — keeping its place among messages
|
||||
the rescan itself held, and carrying its `$/cancelRequest` with it.
|
||||
- [x] Coalescing: a rescan asked for mid-scan is a flag, and
|
||||
`scan_until_settled` is a loop — never a scan inside a scan.
|
||||
- [x] Shutdown mid-scan stops the scan where it stands and `run` returns
|
||||
without taking another message.
|
||||
- [x] The completion tables and the include graph are published with the
|
||||
index, so a mid-scan answer is one generation and not three.
|
||||
- [x] A file opened mid-scan is indexed next (`Scan::index_next`).
|
||||
- [x] The startup scan republishes and refreshes lenses when a buffer was
|
||||
opened during it — a debt that did not exist before this round.
|
||||
- [x] The e2e probe flipped and renamed; the before-numbers kept above.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets --workspace` / `cargo test
|
||||
--workspace` / `node editors/vscode/smoke.js`.
|
||||
- [ ] **Not done, deliberately: the files are still read eagerly.** The 6.9 ms
|
||||
before the first file is mostly 200 `read_to_string`s. Reading each file
|
||||
in `scan_step` instead would take the mid-scan floor to single digits,
|
||||
and it costs a work list of `Option<String>` and a decision about what a
|
||||
file that turns out to be unreadable does to the progress bar's `total`
|
||||
(today such a file never joins the work list at all, because the read
|
||||
that fails happens before the list is taken). Worth doing; not worth
|
||||
guessing at inside a round that is already changing when answers happen.
|
||||
- [ ] **Not done, deliberately: a scan of a few very large files still
|
||||
blocks.** `INTERLEAVE_ABOVE` counts files, and 20 netlist-shaped files
|
||||
can take a second. A second rule on elapsed time would catch it and would
|
||||
make what the server answers depend on machine load; the honest fix is a
|
||||
cost estimate from the sizes the cap already reads (`oversize` does a
|
||||
`metadata` call per walked file), which is a design, not a patch.
|
||||
- [ ] **Not done, deliberately: a rescan still makes requests wait.** The
|
||||
brief named later rescans as blocking the loop the same way, and they
|
||||
still block *requests* — notifications, cancels and responses are
|
||||
processed throughout. Answering a request from a half-updated index would
|
||||
break the order contract the loop has always kept, and no measurement
|
||||
says a rescan is where the pain is: the owner's report is about the first
|
||||
request of a session.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-28 — dev
|
||||
|
||||
**Measured the merge first, and the number chose the design.** The brief left
|
||||
per-file / chunked / deferred open and asked for numbers. `update_facts` on an
|
||||
already-held file is 3.15 ms at 200 files and 14.7 ms at 800, because
|
||||
`merge_references` re-resolves every reference in the workspace; one per file is
|
||||
630 ms and 11.7 s of pure merging. The rhythm that survives is **stage per
|
||||
file, fold in per drain, and drain only when something is waiting** — which
|
||||
makes the cost of interleaving zero for a scan nobody is waiting on and one
|
||||
merge per burst for a scan somebody is. There is no chunk size to tune, which
|
||||
is the nicest property of it: the client's own traffic sets the rhythm.
|
||||
|
||||
**The scan had to become a value before it could be interrupted.** The
|
||||
blocker was borrowing, not design: `rebuild_index_with(&mut self)` holds the
|
||||
workspace for the whole scan, and a message answered from inside it needs that
|
||||
same workspace. `Scan` owns the work list and the staged records, so
|
||||
`scan_step(&mut self, scan: &mut Scan)` borrows two separate things and the
|
||||
server can put whatever it likes between two calls. `rebuild_index_with` is now
|
||||
three lines over the same three methods, which is what makes "the interleaved
|
||||
scan is the one-shot scan with a drain in it" a fact about the code rather than
|
||||
a claim in a document.
|
||||
|
||||
**The hard part was not latency, it was the order contract.** The first
|
||||
working version answered requests mid-scan unconditionally, and sixteen e2e
|
||||
tests began failing *intermittently* — which is the real finding, not the
|
||||
failures. Those sessions pipeline a whole conversation into the pipe
|
||||
(`initialize`, `initialized`, a `didOpen` that widens the scope, three
|
||||
requests, `shutdown`), so whether a request saw a finished index depended on
|
||||
whether the forwarder thread got scheduled before the scan ended. Three
|
||||
decisions came out of that:
|
||||
|
||||
1. **`must_wait`.** A request queued behind a message that asked for a rescan
|
||||
waits for that rescan, because that is what one message at a time would have
|
||||
done, and once one request is waiting every later one waits too. Held
|
||||
messages keep their arrival order and are answered by `run` before it takes
|
||||
anything newer. `shutdown` waits with them: a request sent before a shutdown
|
||||
is a request the client is still owed an answer to.
|
||||
2. **Only the startup scan answers mid-way.** A scan a *message* asked for has
|
||||
that message queued ahead of everything else, so nothing arriving during it
|
||||
may be answered from a half-updated index. The startup scan has nothing
|
||||
queued ahead of it, and it is the one the owner's report is about.
|
||||
3. **`INTERLEAVE_ABOVE`.** Even the startup scan should not trade a complete
|
||||
answer for milliseconds. Sixty-four files is the line: below it the scan runs
|
||||
exactly as it always did, which is also why the whole existing suite passes
|
||||
unmodified — every fixture in it is a handful of files. A count and not a
|
||||
clock, so that what the server answers never depends on how busy the machine
|
||||
was.
|
||||
|
||||
**All three tables, or none.** After `must_wait` there were still failures
|
||||
where a macro hover and an include link came back empty mid-scan: the index was
|
||||
being published but `Candidates` and `IncludeGraph` were still built whole at
|
||||
the end. Publishing one of three tables makes "as far as the scan has got" mean
|
||||
three different things at once, so both grew a batch `absorb` and all three are
|
||||
folded in together. The include graph's known-file table is relearned from the
|
||||
scan's **whole work list** rather than the files it has reached, because which
|
||||
files *exist* is settled the moment the scope is resolved and only the edges are
|
||||
discovered file by file.
|
||||
|
||||
**Coalescing: finish, then rescan again — not abort and restart.** A message
|
||||
answered mid-scan sets `rescan_wanted`; `scan_until_settled` is a loop that
|
||||
scans again while the flag is set, and `reindex`/`reindex_one` set the flag
|
||||
instead of running when `scanning`. Finishing was chosen over aborting because
|
||||
it needs no way to unwind a half-published index and cannot loop forever: the
|
||||
follow-up scan reads the persistent store for every file the abandoned one had
|
||||
already parsed. Each scan keeps its own progress token, which is what a client
|
||||
showing a bar expects of two scans. `reindex_one` returns `true` when it defers,
|
||||
because its caller's fallback is "rebuild the whole thing right now", which is
|
||||
precisely what must not happen.
|
||||
|
||||
**Two debts this round created and paid.** A buffer can now be *opened* during
|
||||
the startup scan, so `Server::started` owes what `reindex` has always owed at
|
||||
the end of a scan — a code-lens refresh, a generation bump and a republish —
|
||||
and pays it when any buffer is open (which is nothing at all for a session
|
||||
whose client did not get a `didOpen` in edgeways). And `reindex_one` can no
|
||||
longer patch one file mid-scan without the scan overwriting it with older bytes
|
||||
a moment later, so it defers too.
|
||||
|
||||
**A test seam, named as one.** `Server::started` grew a `queued: Vec<Message>`
|
||||
parameter — what the client had already sent when the server was built, put
|
||||
straight onto the queue the startup scan drains. `Server::new` passes an empty
|
||||
one. The alternative was for the test to send on the client end and race the
|
||||
forwarder thread for it, which made the first version of
|
||||
`a_request_the_client_had_already_sent_is_answered_during_the_startup_scan`
|
||||
pass alone and fail under a loaded suite. A coin-toss test is worse than no
|
||||
test.
|
||||
|
||||
**Files touched.** `crates/vlog_semantic/src/workspace.rs`,
|
||||
`crates/vlog_semantic/tests/workspace.rs`,
|
||||
`crates/lucisv_server/src/{server.rs,state.rs,candidates.rs,includes.rs,perf.rs}`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, this README,
|
||||
`docs/features/hover-line-index/README.md`, `docs/perf/README.md`, `TODO.md`.
|
||||
No new dependency, no `unsafe`, no `#[allow]`, no version bump, no commits.
|
||||
Single-threaded throughout: the only thread this round touches is the message
|
||||
forwarder, which existed already and still only moves messages.
|
||||
|
||||
**Tests added** (14).
|
||||
|
||||
| test | where | pins |
|
||||
|---|---|---|
|
||||
| `absorbing_a_batch_gives_the_index_a_whole_build_would_have` | `vlog_semantic/tests/workspace.rs` | the house witness for the new entry point: a file replaced, two added (one sorting first, so every id moves), one dropped |
|
||||
| `absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index` | same | what makes a publish free of consequence — how records are grouped into batches cannot reach the result |
|
||||
| `absorbing_nothing_changes_nothing` | same | the empty publish and the empty finish |
|
||||
| `publishing_between_every_file_leaves_what_a_one_shot_scan_leaves` | `lucisv_server/src/state.rs` | the round's central invariant, over index **and** completion tables **and** include graph, publishing after every single file |
|
||||
| `a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope` | same | a publish only folds records *in*, so the removal a rescan owes has to survive every publish before it |
|
||||
| `a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes` | same | fingerprint equality with a `didChange` injected mid-scan |
|
||||
| `a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell` | same | `Scan::index_next` moves it, does not move it twice, refuses a file not waiting — and the finished index is byte-identical |
|
||||
| `a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven` | same | progress and log continuity: interleaving adds drains between events, never events |
|
||||
| `a_request_the_client_had_already_sent_is_answered_during_the_startup_scan` | `lucisv_server/src/server.rs` | the point of the round, over the real dispatch: the response goes out before the bar comes down |
|
||||
| `a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself` | same | the other side of `INTERLEAVE_ABOVE` |
|
||||
| `a_request_queued_behind_a_rescan_waits_for_that_rescan` | same | the order contract: the request sees the index the push asked for, not the one it was sent into |
|
||||
| `a_held_request_keeps_its_place_and_takes_its_cancel_with_it` | same | the two corners holding creates: a burst's own request stays in front of one the scan it started held later, and a cancel consumed on the way in goes back with what it cancels |
|
||||
| `a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan` | same | three settings pushes inside one scan cost one more scan, two bars, two tokens, no nesting |
|
||||
| `a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands` | same | the bar never comes down, the index is short, `run` returns at once |
|
||||
|
||||
Two `#[ignore]`d probes added
|
||||
(`perf::publishing_a_half_built_index_mid_scan`,
|
||||
`perf::what_a_scan_does_before_its_first_file`); one existing probe flipped and
|
||||
renamed (`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` →
|
||||
`..._is_answered_during_it`), which is the before/after pair this README's
|
||||
latency table is read from.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` silent. `cargo test --workspace` green, 0 failed:
|
||||
`lucisv_server`'s unit tests **1 225 passed / 26 ignored** (+11 tests, +2
|
||||
`#[ignore]`d probes), its `e2e` suite **56 passed / 2 ignored** (unmodified
|
||||
except the flipped probe), `vlog_semantic`'s `workspace` suite **70 passed**
|
||||
(+3). `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-28 — QA
|
||||
|
||||
Read `CLAUDE.md`, the dev brief, and this README's Handshakes/Work log before
|
||||
attacking. Traced `process_batch`'s held-message splice, `must_wait`,
|
||||
`scan_until_settled`/`scan_once`/`answer_what_is_waiting`, `Scan`, and
|
||||
`WorkspaceIndex::absorb` line by line against the charter's five attack
|
||||
classes, then exercised the parts a trace alone couldn't settle. Two real
|
||||
findings, both narrow; one confirmed-correct-but-untested behavior now pinned;
|
||||
gates and numbers reproduced.
|
||||
|
||||
**Finding 1 (low, doc-contract) — `WorkspaceIndex::absorb` does not dedupe a
|
||||
duplicate path in one batch the way `WorkspaceIndex::build` does.**
|
||||
`crates/vlog_semantic/src/workspace.rs:472-489` (`absorb`). `build` goes
|
||||
through `index_order`, which keeps the *first* of a duplicate path
|
||||
(`Vec::dedup_by`'s contract, `crates/vlog_semantic/src/workspace.rs:1034`).
|
||||
`absorb`'s own loop walks `records` left to right and overwrites on a
|
||||
`binary_search` hit, keeping the *last*. `absorb`'s doc comment claims "what
|
||||
comes out is the index a full build over the records it now holds would have
|
||||
produced" — that equivalence does not hold for a batch with a duplicate path.
|
||||
Not reachable through the scan that actually feeds `absorb` today: `Scan::work`
|
||||
is built from `index_order` before the scan starts, so it can never contain two
|
||||
entries for the same path, and `scan_step` therefore never stages a duplicate.
|
||||
But `absorb` is `pub` on `WorkspaceIndex`, its doc comment states the
|
||||
equivalence unconditionally, and a future caller (or a future change to how
|
||||
`Scan::work` is assembled) could reintroduce the gap silently. Repro and
|
||||
permanent regression test added and passing:
|
||||
`crates/vlog_semantic/tests/workspace.rs`,
|
||||
`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`
|
||||
— builds `[("a.sv", module first_shape), ("a.sv", package second_shape)]` both
|
||||
ways and asserts the fingerprints differ, then pins which one `absorb` actually
|
||||
keeps (the last). Not fixed here — whether `absorb` should match `build`'s
|
||||
first-wins or the doc comment should be narrowed to describe last-wins is a
|
||||
design call, not a QA fix. Verified harmless in production as things stand
|
||||
today, precisely because the scan can't construct the input that trips it.
|
||||
|
||||
**Finding 2 (very low, stale doc comment) — `refresh_code_lenses`'s doc comment
|
||||
contradicts what this round now does.**
|
||||
`crates/lucisv_server/src/server.rs:1979-1984`: "Nothing is sent at startup
|
||||
either: no buffer is open there, so there are no lenses to invalidate." That
|
||||
was true before this round; `Server::started` now calls exactly this method at
|
||||
the end of construction whenever a `didOpen` answered mid-scan left a buffer
|
||||
open (`crates/lucisv_server/src/server.rs:347-354`), and the new test below
|
||||
confirms it fires. The comment should say client-refresh-capable + a buffer
|
||||
open, no longer "never at startup." Not fixed here per QA's remit not to edit
|
||||
outside the change's own tests, but it is a one-line fix the dev should make in
|
||||
the same file the round already touched.
|
||||
|
||||
**Verified correct, previously untested — the two-publish behavior for a file
|
||||
opened mid-startup-scan.** Traced through `Server::started`'s new "pay the
|
||||
`reindex` debt" block and found it produces *two* `publishDiagnostics` for the
|
||||
file a mid-scan `didOpen` opens: one from `didOpen`'s own always-existing
|
||||
handler (against the half-built index, mid-scan — correct, not new), and one
|
||||
from the debt-payment block after the bar comes down (against the finished
|
||||
index — the new behavior). That is correct, not a duplicate-publish bug, but
|
||||
it was unverified by any test in the round's own "Tests added" table. Added
|
||||
`crates/lucisv_server/src/server.rs`,
|
||||
`a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once`:
|
||||
asserts exactly two publishes for the opened file, the first before the `end`
|
||||
progress event and the second after it, and exactly one `workspace/codeLens/refresh`
|
||||
(also after `end`, implicitly, since it can only fire once open_uris is
|
||||
non-empty at the end of construction). Passes.
|
||||
|
||||
**Also added, no bug found — `INTERLEAVE_ABOVE` exact-boundary test.** The
|
||||
charter asked for the 64/65 edge explicitly; the round's own tests exercise
|
||||
`INTERLEAVE_ABOVE + 6` and `4`, neither of which pins the `>` vs `>=` choice in
|
||||
`scan_once`. Added
|
||||
`crates/lucisv_server/src/server.rs`,
|
||||
`interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after`: a
|
||||
scan of exactly 64 files answers nothing mid-construction (one-shot), a scan of
|
||||
65 answers before the bar comes down (interleaved). Passes as written — no
|
||||
off-by-one found, now locked in.
|
||||
|
||||
**Attacks traced and found sound, not turned into new tests (existing coverage
|
||||
or structurally excluded):**
|
||||
- *Order-contract, cancel-through-a-wait*: traced `process_batch`'s
|
||||
`consumed_cancels` splice by hand against
|
||||
`a_held_request_keeps_its_place_and_takes_its_cancel_with_it`
|
||||
(`crates/lucisv_server/src/server.rs:2985`-ish) with a constructed batch
|
||||
where a cancel's target is answered *before* the wait point is reached — the
|
||||
stale cancel does get re-queued into `held`, but `cancelled_in` re-filters by
|
||||
the ids actually present in the replayed batch, so it is inert on replay,
|
||||
never mis-cancels an unrelated request. Not a bug; not worth a dedicated
|
||||
test since it changes nothing observable.
|
||||
- *Gone-file races during a scan that also answers mid-way*: `finish_scan`
|
||||
defers the `gone` computation to one `absorb` call at the very end, so a
|
||||
file leaving scope is not removed from the live index until the scan
|
||||
finishes. This only matters if a mid-scan answer could see a file that
|
||||
should already be gone — and every scan capable of having `gone` files
|
||||
non-empty is a *rescan* (`answering_a_rescan = true`), which `must_wait`
|
||||
already blocks from answering anything mid-way. The startup scan (the only
|
||||
one that answers mid-way) always starts from an empty index, so it can never
|
||||
have a `gone` file. Structural, not incidental — traced through
|
||||
`scan_until_settled`'s `asked_for` threading, not tested further.
|
||||
- *Include graph's `known` set includes not-yet-scanned files mid-scan*:
|
||||
intentional per the Handshakes section ("which files exist is settled the
|
||||
moment the scope is resolved"); this can make an `` `include `` targeting an
|
||||
unscanned file resolve to a path with no edges of its own yet, which is the
|
||||
same "not there yet" story the index already tells for symbols. Not a
|
||||
divergence from the round's own stated contract.
|
||||
- *Shutdown delivered twice (queue-injection copy + forwarder-relayed copy) in
|
||||
`a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands`*: the test
|
||||
deliberately sends the same logical `shutdown` through two paths and says so
|
||||
in its own comment ("whichever of the two ... the scan stops here"). Traced
|
||||
the `forward`/`handle_shutdown` interaction and confirmed the real `exit`
|
||||
notification can never be stolen by the forwarder (it stops at the first
|
||||
shutdown it relays and never reads again), so the raciness is a test-harness
|
||||
artifact for reaching the scenario at all, not a client-facing bug. Ran the
|
||||
test 20x in a loop (`cargo test ... -- --test-threads=1`, repeated) with no
|
||||
flake.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean (after formatting the one test I
|
||||
added that needed it). `cargo clippy --all-targets --workspace` silent.
|
||||
`cargo test --workspace` run 3x after all QA additions: **0 failures each run,
|
||||
2457 total passed each run**, identical every time. One transient failure seen
|
||||
*before* the final 3-run check
|
||||
(`large::tests::references_on_one_giant_line_locate_their_hits_in_linear_time`,
|
||||
a pre-existing wall-clock perf gate unrelated to any file this round touches)
|
||||
under self-inflicted contention (I had a background `cargo test` and a 3-run
|
||||
loop racing on the same machine at once); reproduced clean on both master
|
||||
(pre-round, 3/3) and this round's tree (3/3) once run without that
|
||||
contention — not a regression, not flagged further.
|
||||
`node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**Numbers reproduced**, same machine, `--release`, `--test-threads=1`:
|
||||
- `e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`: 16.1 ms
|
||||
cold / 14.0 ms warm (README claims 15.5 / 12.8, and says a rerun elsewhere
|
||||
saw 19.8 / 14.0 — this sits inside that band).
|
||||
- `perf::publishing_a_half_built_index_mid_scan`, all three sizes including
|
||||
800 (not skipped — it ran in 5.4s, not slow): 200-file whole merge 3.85 ms
|
||||
(claimed 3.35 ms), 800-file per-file-feeding-would-cost 12.9 s (claimed
|
||||
11.7 s) against 2.06 s of parsing (claimed 1.78 s) — same shape, same
|
||||
conclusion (deferred-batched, not per-file), numbers within normal
|
||||
machine-to-machine variance.
|
||||
- `state::tests::qa_perf_cold_warm_and_half_warm_scans`: no-cache 347 ms /
|
||||
cold 387 ms / warm 203 ms (claimed 322/353/189) — store size **exactly**
|
||||
2 380 790 bytes, matching the README bit for bit, which is the number that
|
||||
actually matters (deterministic index size, unaffected by machine noise).
|
||||
|
||||
**Verdict: SHIP.** No masked-corruption, no order-contract violation, no
|
||||
non-settling loop found across five attack classes and direct code tracing.
|
||||
Two findings filed above are both low severity, both narrow (one is
|
||||
structurally unreachable through the round's own code paths today, the other
|
||||
is a one-line stale comment), and neither touches the hard invariants
|
||||
(never-corrupt, idempotent, comments-preserved) or the round's own claimed
|
||||
equivalences in the paths actually exercised. Three regression tests added,
|
||||
all passing, all documenting real (if narrow) findings or previously-untested
|
||||
correct behavior — none required a design change.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
|
||||
independently (fmt clean, clippy silent, 2457 workspace tests green,
|
||||
QA ran the suite ×3 with identical results). This was the riskiest
|
||||
round of the wave — interleaving is where order contracts go to die —
|
||||
and the two rules that survived the dev's own 16-test intermittent
|
||||
failure (`must_wait`, so only the startup scan answers mid-way; and
|
||||
`INTERLEAVE_ABOVE` as a count, not a clock) are the reason the whole
|
||||
existing suite passes unmodified and deterministic. The measure-first
|
||||
discipline paid again: per-file merging looked obvious and would have
|
||||
been quadratic (11.7 s over 800 files); one absorb per non-empty-queue
|
||||
drain costs the idle scan a `try_recv` per file and nothing else. The
|
||||
structural fingerprint argument — one-shot and interleaved are
|
||||
literally the same three-line loop over `Scan` — is the strongest
|
||||
equivalence guarantee of the wave. First hover of a session:
|
||||
780 → 15.5 ms cold, 287 → 12.8 ms warm, scan totals inside noise; the
|
||||
remaining 6.9 ms of eager pre-scan reads is measured and filed, not
|
||||
hidden. QA's two low findings were the lead's to settle and are fixed
|
||||
in this commit: `absorb`'s doc now states the distinct-paths
|
||||
precondition and why last-wins is the right update semantic (behavior
|
||||
unchanged — the one production caller feeds deduped work, and QA's
|
||||
divergence test pins the edge), and `refresh_code_lenses`' comment
|
||||
caught up with `started`. The double-publish for a buffer opened
|
||||
mid-scan (half-built answer, then finished answer) is correct by the
|
||||
scope-relative-in-time doctrine and now pinned. Accepted; committed by
|
||||
the lead.
|
||||
@@ -44,7 +44,10 @@ impl WorkspaceIndex {
|
||||
fn counts(&self) -> IndexCounts;
|
||||
}
|
||||
|
||||
struct Def { file: FileId, name_span: TextRange, kind: SymbolKind }
|
||||
struct Def { file: FileId, name_span: TextRange, kind: SymbolKind,
|
||||
detail_span: Option<TextRange>, // 2026-08-28, port-detail-spans
|
||||
lines: DeclLines } // 2026-08-28, hover-line-index
|
||||
struct DeclLines { name: u32, detail: Option<u32> } // 1-based source lines
|
||||
struct WorkspaceSymbol<'a> { name: &'a str, container: Option<&'a str>, def: &'a Def }
|
||||
struct IndexCounts { files, modules, packages, typedefs, members, defines }
|
||||
|
||||
@@ -275,6 +278,15 @@ unchanged by where the span comes from. Nothing here needs revisiting when
|
||||
order in every returned slice, regardless of iteration order.
|
||||
- `Def.name_span` is a non-empty byte range in `Def.file` that slices back to
|
||||
exactly the name that was looked up (asserted over the whole corpus).
|
||||
- `Def.lines` (2026-08-28, `docs/features/hover-line-index/README.md`) is the
|
||||
1-based line each of those spans falls on, read off the same text the span
|
||||
was read from, in the same pass. It is what lets a consumer print
|
||||
`file:line` for an indexed declaration with no file access at all. **A line
|
||||
is not text**: the index still keeps no file contents, exactly as it keeps
|
||||
no contents for the spans it has always held. The field is a struct rather
|
||||
than a bare number so richer per-declaration position data extends it by
|
||||
gaining a field — members are `Decl`s like units are, so a module's ports
|
||||
already carry their own lines here.
|
||||
- `resolve_external` does not mutate `Semantics` and holds no borrow of the
|
||||
index in its result.
|
||||
|
||||
@@ -424,6 +436,19 @@ and more than half of all external candidates answered on clean files.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — declaration lines** (`docs/features/hover-line-index/README.md`).
|
||||
`Def` and the per-file `Decl` gained `lines: DeclLines { name, detail }`, the
|
||||
1-based source lines of `name_span` and of `detail_span`, computed in
|
||||
`facts_from_analysis` from a `LineIndex` over the file being indexed.
|
||||
`FileFacts::from_analysis` takes that index as a parameter (its one real caller
|
||||
already holds one); `FileFacts::of` builds its own. The record format grew two
|
||||
fields per declaration and `FACTS_FORMAT` went **3 → 4**.
|
||||
`WorkspaceIndex::fingerprint`'s `sym` line carries the lines, so the
|
||||
incremental-equals-fresh witness covers them — every existing equivalence test
|
||||
stayed green unmodified. Cost, measured over the corpus: the whole scan is
|
||||
unchanged inside its noise (one `LineIndex::new` per parsed file, under 1 % of
|
||||
that file's parse) and the persistent store grows 68 KB over 860 files, 2.9 %.
|
||||
|
||||
**2026-08-27 — indexed navigation.** `FileFacts` gained compact local and
|
||||
external reference records and its persisted format moved to version 2.
|
||||
`WorkspaceIndex` resolves them into reverse postings after declaration tables
|
||||
|
||||
@@ -0,0 +1,599 @@
|
||||
# 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.
|
||||
|
||||
## Before / after — round 3 (2026-08-28)
|
||||
|
||||
`docs/features/hover-line-index/README.md` — the owner's report that hovering
|
||||
an instantiation, and a port on that instantiation, is slow on the first try.
|
||||
Two suspects were measured before anything was changed; the numbers said which
|
||||
one this round could fix and which it could only file.
|
||||
|
||||
**D1 — the heading stopped reading the file, and the snippet's read is
|
||||
shared.** Each indexed declaration now carries its line (`Def::lines`,
|
||||
`FACTS_FORMAT` 3 → 4), so `file:line` costs nothing; the snippet still wants
|
||||
that file's text, and takes it from a four-entry / 8 MiB LRU of closed files'
|
||||
text in `Workspace`. So the *first* touch of a file still pays one read and
|
||||
every touch after it pays nothing.
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| hover on an instantiation into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms |
|
||||
| — the same hover again | 5.75 ms | **0.95 µs** |
|
||||
| hover on a port into the same file, first touch | 5.85 ms | 5.92 ms |
|
||||
| — the same hover again | 5.71 ms | **0.99 µs** |
|
||||
| the 31.7 MB probe above, first touch | 17.0 ms | 16.8 ms |
|
||||
| — the same hover again | 17.0 ms | **4.4 µs** |
|
||||
| `perf::hovering_across_files_into_a_closed_file`, 1k / 10k (mean of 20) | 39.8 / 157 µs | **4.7 / 12.9 µs** |
|
||||
|
||||
The cost, over the 860-file corpus: one `LineIndex::new` per parsed file, which
|
||||
leaves every scan figure inside its own noise (no cache 338 → 343 ms, cold
|
||||
372 → 374 ms, warm 197 → 200 ms), and 68 KB more store — 2.9 %.
|
||||
|
||||
**D2 — the first request of a session waits out the startup scan.
|
||||
Measured, filed, not fixed.** `Server::new` runs the whole scan before the
|
||||
message loop takes its first message, so anything a client sends the instant
|
||||
the handshake finishes sits in the OS pipe until the scan ends. Over 200 files
|
||||
of 1 000 lines, through the shipped binary
|
||||
(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_waits_for_it`):
|
||||
|
||||
| the first hover of a session | cold store | warm store |
|
||||
|---|---:|---:|
|
||||
| issued the moment `initialized` was sent | **780 ms** | **287 ms** |
|
||||
| the same hover once the scan is done | 64 µs | 61 µs |
|
||||
|
||||
This is four orders of magnitude larger than D1 and is where "the first hover
|
||||
is slow" mostly lives. Fixing it is a change to request scheduling — answering
|
||||
while the index is half-built, or scanning off the message-loop thread — and
|
||||
was explicitly out of this round's scope.
|
||||
|
||||
## Before / after — round 4 (2026-08-28)
|
||||
|
||||
`docs/features/scan-interleave/README.md`: D2, answered. The scan is per-file
|
||||
steps with the message queue drained between them, so a startup scan of more
|
||||
than 64 files answers requests while it runs — single-threaded, interleaved,
|
||||
not scanned off-thread. Same fixture, same probe, flipped and renamed
|
||||
(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_is_answered_during_it`):
|
||||
|
||||
| the first hover of a session | before | after |
|
||||
|---|---:|---:|
|
||||
| issued the moment `initialized` was sent, cold store | **780 ms** | **15.5 ms** |
|
||||
| — warm store | **287 ms** | **12.8 ms** |
|
||||
| the same hover once the scan is done | 64 / 61 µs | 191 / 151 µs |
|
||||
|
||||
The "after" figures are tens of milliseconds, not three significant figures: a
|
||||
second run on a busier machine reported 19.8 / 14.0 ms. The claim is the order
|
||||
of magnitude, and the post-scan row is measured after waiting for the progress
|
||||
bar rather than racing the scan.
|
||||
|
||||
**What it cost the scan: under a percent.** The merge was measured before the
|
||||
design was chosen, and the numbers ruled out the obvious shape — a merge is a
|
||||
pass over the whole index, so folding each file in as it is taken would be
|
||||
quadratic (`perf::publishing_a_half_built_index_mid_scan`, 200 files of 1k
|
||||
lines: 630 ms of merging against 464 ms of parsing; 800 files: 11.7 s against
|
||||
1.78 s). Records are staged and folded in once per *drain* instead, and a drain
|
||||
only happens when a message is waiting:
|
||||
|
||||
| 860-file corpus | before | after |
|
||||
|---|---:|---:|
|
||||
| no cache | 321.5 ms | 322.0 ms |
|
||||
| cold, filling the store | 351.3 ms | 353.4 ms |
|
||||
| warm, every file from the store | 187.0 ms | 188.6 ms |
|
||||
|
||||
The floor under the 15.5 ms is one block no drain can break up:
|
||||
`perf::what_a_scan_does_before_its_first_file` puts **6.9 ms** before the first
|
||||
file (resolve the scope, read all 200 files, open the store) against 4.0 ms for
|
||||
one file — so reading the files lazily is what a single-digit number would take,
|
||||
and it is filed as a deliberate not-done in that feature's README.
|
||||
|
||||
## 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.
|
||||
|
||||
0. **Answer requests during the startup scan — 780 ms cold, 287 ms warm, on
|
||||
the first request of a session.** New in round 3's measurements (D2 above)
|
||||
and the largest single number on this page. It is not a code-speed problem:
|
||||
the work is already as fast as the persistent cache can make it, and what
|
||||
costs the user is that the message loop has not started yet. Any fix is a
|
||||
change to what an answer *means* while the index is half-built, so it needs
|
||||
a design round, not an optimisation.
|
||||
→ **Done in round 4**, 780 → 15.5 ms cold and 287 → 12.8 ms warm; the
|
||||
design round it needed is `docs/features/scan-interleave/README.md`, and
|
||||
what an answer means mid-scan is written down there. What is left of this
|
||||
item is 6.9 ms of eager file reading before the scan's first file.
|
||||
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.
|
||||
- [x] **Added in round 3 (2026-08-28):** a hover into a big closed file with
|
||||
the **first touch and the repeat reported separately**
|
||||
(`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`) — every
|
||||
earlier hover probe reported a mean, which hides exactly the split the
|
||||
owner's report was about — and the first request of a session against
|
||||
the shipped binary, with a cold store and a warm one
|
||||
(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_waits_for_it`).
|
||||
`perf::breaking_down_one_flushed_keystroke`.
|
||||
- [x] **Added in round 4 (2026-08-28):** what one mid-scan publish costs
|
||||
against the per-file parse it is interleaved with
|
||||
(`perf::publishing_a_half_built_index_mid_scan`, at 50 / 200 / 800
|
||||
files), and what a scan does *before* its first file — the block no
|
||||
drain can break up (`perf::what_a_scan_does_before_its_first_file`).
|
||||
The e2e probe above was flipped to
|
||||
`a_hover_issued_during_the_initial_scan_is_answered_during_it`.
|
||||
- [ ] **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.
|
||||
|
||||
@@ -5,6 +5,65 @@ 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.14.0 — 2026-08-28
|
||||
|
||||
The first-hover release.
|
||||
|
||||
- **The first hover of a session answers in ~15 ms**, not hundreds —
|
||||
the server now answers requests while the workspace scan is still
|
||||
running, with your open file indexed first.
|
||||
- **Repeat hovers into closed files are ~1 µs.** Declaration line
|
||||
numbers live in the index (a few KB even for tens of thousands of
|
||||
modules, ports included), and a closed file's text is read once and
|
||||
cached, not re-read per hover.
|
||||
- **One-time index rebuild** on first open after updating — the index
|
||||
format gained the line numbers.
|
||||
|
||||
## 0.13.1 — 2026-08-28
|
||||
|
||||
The F12-latency release.
|
||||
|
||||
- **Find References with a huge file open is ~30× faster** (3.2 ms →
|
||||
0.11 ms on a 70 000-reference buffer), and in-file references and
|
||||
occurrence highlighting on heavily used signals are ~40 % faster.
|
||||
- **Jumping into a new folder is ~10× faster.** The index rescan that a
|
||||
scope-widening jump triggers now reuses what your open buffers already
|
||||
analyzed instead of re-parsing them: ~228 ms → ~23 ms with a 1.4 MB
|
||||
file open.
|
||||
- **Pathologically nested files can no longer crash the tools.** ~500
|
||||
nested `begin`/`end` (or `case`, `fork`, generate…) blocks now produce
|
||||
an ordinary "nesting too deep" diagnostic on every platform, including
|
||||
Windows, instead of risking an abort.
|
||||
|
||||
## 0.13.0 — 2026-08-28
|
||||
|
||||
- **Typing no longer reanalyzes on every keystroke.** The buffer's analysis is
|
||||
deferred to the first moment anything needs it, so a burst of typing costs
|
||||
one reanalysis instead of one per key. Half-typed lines stop flashing
|
||||
squiggles that vanish a keystroke later. In a 10 000-line file a keystroke
|
||||
now round-trips in 37.6 ms.
|
||||
- **Old-style ports hover properly.** A port named in the module header and
|
||||
completed in the body (`input signed [31:0] data_in;`) now shows both
|
||||
places on one card — the header line and the declaration carrying its
|
||||
direction, type and width — with the comments that document each of them.
|
||||
Go-to-definition offers both, body declaration first. Works across files,
|
||||
and for old-style task and function arguments too.
|
||||
- **Faster hover and cursor answers.** Hovering into a closed file reads it
|
||||
once instead of twice, and expand-selection, on-type formatting, completion
|
||||
and inline templates find the token at your cursor by binary search rather
|
||||
than by scanning the file. No answer changed.
|
||||
- The index cache's format changed, so the first session after upgrading
|
||||
rebuilds it.
|
||||
|
||||
## 0.12.1 — 2026-08-27
|
||||
|
||||
- **Hover shows the declaration itself.** Hovering a name declared in another
|
||||
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.
|
||||
|
||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||
setup.
|
||||
|
||||
The current release is **0.12.0**. Its platform packages include both
|
||||
The current release is **0.14.0**. Its platform packages include both
|
||||
`lucisv-server` and the `lucisv` command-line tool:
|
||||
|
||||
| Package target | Machines |
|
||||
@@ -320,6 +320,48 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.14.0 highlights
|
||||
|
||||
Version 0.14.0 is the first-hover release:
|
||||
|
||||
- Hover on instantiations and ports is now fast on the *first* try: the
|
||||
server answers during the startup scan (~15 ms instead of waiting
|
||||
hundreds), declaration lines live in the index, and closed files are
|
||||
read once, then cached.
|
||||
- The index cache format changed: the first open after updating
|
||||
re-scans once, then persistent caching resumes.
|
||||
|
||||
## Release 0.13.1 highlights
|
||||
|
||||
Version 0.13.1 is the F12-latency release:
|
||||
|
||||
- Find References with a big file open answers in ~0.1 ms where it took
|
||||
milliseconds, and jumping into a not-yet-indexed folder costs ~23 ms
|
||||
where it took ~228 ms — the rescan reuses what open buffers already
|
||||
analyzed.
|
||||
- Deeply nested files produce a "nesting too deep" diagnostic instead of
|
||||
ever crashing the server or CLI, on every platform.
|
||||
|
||||
## Release 0.13.0 highlights
|
||||
|
||||
Version 0.13.0 is the responsiveness release. Typing no longer reanalyzes the
|
||||
buffer on every keystroke — the analysis is deferred to the first moment
|
||||
anything needs it, so a burst of typing costs one reanalysis instead of one
|
||||
per key, and half-typed lines stop flashing squiggles that vanish a moment
|
||||
later. Cursor-position answers — expand selection, on-type formatting,
|
||||
completion, inline templates — binary-search for the token under your cursor
|
||||
instead of scanning the file.
|
||||
|
||||
Hover also learned old-style ports: a port named in the module header and
|
||||
completed in the body (`input signed [31:0] data_in;`) shows both places on
|
||||
one card, with the comments that document each of them.
|
||||
|
||||
## Release 0.12.1 highlights
|
||||
|
||||
Version 0.12.1 makes hover answer the question directly: a cross-file name
|
||||
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:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||
"version": "0.12.0",
|
||||
"version": "0.14.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -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