Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f7b4a9f91 | ||
|
|
574ab833e3 | ||
|
|
12d0bbad51 | ||
|
|
de8a7e129c | ||
|
|
611dd23069 | ||
|
|
a4f23db2c7 | ||
|
|
d94f9e3de0 | ||
|
|
94b130aca1 | ||
|
|
efe67bde65 |
No files matched your search
@@ -4,6 +4,80 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.13.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.13.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -573,6 +573,18 @@ 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.
|
||||
- [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
|
||||
@@ -721,6 +733,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).
|
||||
|
||||
@@ -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,
|
||||
|
||||
+1089
-18
File diff suppressed because it is too large.
Load diff
@@ -568,6 +568,40 @@ mod tests {
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_from_the_previous_facts_format_is_dropped_not_misread() {
|
||||
// Simulates a store written by the released 0.12.1 (FACTS_FORMAT 2,
|
||||
// before detail_span). Same CACHE_FORMAT and VERSION as today — only
|
||||
// FACTS_FORMAT differs — so the only thing that can catch it is the
|
||||
// FACTS_FORMAT field in the header line. QA finding for
|
||||
// docs/features/port-detail-spans/README.md: the format bump 2 → 3
|
||||
// had no regression test of its own; this is that test.
|
||||
let dir = TempDir::new("factsformat2");
|
||||
let file = dir.file("m.sv", M);
|
||||
let encoded = facts(&file, M).encode().expect("encodes");
|
||||
let old_format_store = format!(
|
||||
"lucisv-index-cache\t{CACHE_FORMAT}\t2\t{VERSION}\n{}\n",
|
||||
line(content_hash(M.as_bytes()), &encoded)
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), old_format_store).expect("write");
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(
|
||||
cache.facts_for(&file, M).is_none(),
|
||||
"a format-2 record must not be read as a format-3 one"
|
||||
);
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
#[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)
|
||||
|
||||
@@ -25,7 +25,15 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
/// An open buffer answers from the line index it already carries; a closed
|
||||
/// file is read and indexed here — which is why a hover that names one file
|
||||
/// twice reads it through the per-request memo in `hover::symbol_hover`, not
|
||||
/// through two calls here.
|
||||
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(doc.line_index.line_col(offset).0);
|
||||
}
|
||||
let text = ws.text_of(path)?;
|
||||
Some(LineIndex::new(&text).line_col(offset).0)
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ mod locate;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
#[cfg(test)]
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod selection;
|
||||
|
||||
@@ -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,7 +169,11 @@ 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,
|
||||
@@ -223,11 +239,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));
|
||||
|
||||
@@ -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,338 @@
|
||||
//! 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.
|
||||
fn mean(runs: u32, mut body: impl FnMut()) -> Duration {
|
||||
let start = Instant::now();
|
||||
for _ in 0..runs {
|
||||
body();
|
||||
}
|
||||
start.elapsed() / runs
|
||||
}
|
||||
|
||||
/// A scratch directory holding the generated files a measurement needs,
|
||||
/// removed when the measurement is done.
|
||||
fn scratch(tag: &str, files: &[(&str, &str)]) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_{tag}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
for (name, text) in files {
|
||||
std::fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::analyzing -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn analyzing_a_generated_module() {
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let (tree, _) = parse_source_tolerant(&src);
|
||||
let took = mean(10, || {
|
||||
black_box(analyze(black_box(&tree), black_box(&src)));
|
||||
});
|
||||
let symbols = analyze(&tree, &src).symbols().len();
|
||||
eprintln!(
|
||||
"analyze: {lines} lines ({} KB, {symbols} symbols) took {took:?}",
|
||||
src.len() / 1000
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::opening -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn opening_a_buffer_end_to_end() {
|
||||
// What one flushed keystroke costs: lex, parse, analyze, resolve against
|
||||
// the index. The index holds the same file, so `resolve_external` has
|
||||
// something real to answer from rather than an empty table.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let path = PathBuf::from("gen.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), src.as_str())]);
|
||||
let took = mean(10, || {
|
||||
black_box(Document::new(Some(path.clone()), src.clone(), &index));
|
||||
});
|
||||
eprintln!("Document::new: {lines} lines ({} KB) took {took:?}", src.len() / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::breaking_down -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn breaking_down_one_flushed_keystroke() {
|
||||
// `opening_a_buffer_end_to_end` says what a flush costs; this says where
|
||||
// that cost is, stage by stage, in the order `Document::new` runs them —
|
||||
// plus the diagnostics pass, which is *not* inside `Document::new` but
|
||||
// runs on every publish, so a flush is the sum of the two.
|
||||
//
|
||||
// `parse_tolerant` consumes its token vector, so each run of the parse
|
||||
// needs a fresh clone; the clone is measured on its own line and the parse
|
||||
// line is reported with the clone still in it. Subtracting one from the
|
||||
// other is the honest reading, and it is what `Document::new` really pays.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let path = PathBuf::from("gen.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), src.as_str())]);
|
||||
let tokens = tokenize(&src).expect("the generated module lexes");
|
||||
let (tree, _) = parse_tolerant(tokens.clone(), &src);
|
||||
let semantics = analyze(&tree, &src);
|
||||
let doc = Document::new(Some(path.clone()), src.clone(), &index);
|
||||
|
||||
let lex = mean(20, || {
|
||||
black_box(tokenize(black_box(&src)).is_ok());
|
||||
});
|
||||
let clone = mean(20, || {
|
||||
black_box(tokens.clone());
|
||||
});
|
||||
let parse = mean(20, || {
|
||||
black_box(parse_tolerant(black_box(tokens.clone()), black_box(&src)));
|
||||
});
|
||||
let defines = mean(200, || {
|
||||
black_box(collect_defines(black_box(&tokens)));
|
||||
});
|
||||
let analyzing = mean(20, || {
|
||||
black_box(analyze(black_box(&tree), black_box(&src)));
|
||||
});
|
||||
let external = mean(200, || {
|
||||
black_box(resolve_external(black_box(&semantics), black_box(&index)));
|
||||
});
|
||||
let line_index = mean(200, || {
|
||||
black_box(LineIndex::new(black_box(&src)));
|
||||
});
|
||||
let lint = mean(20, || {
|
||||
black_box(crate::diagnostics::all(black_box(&doc)));
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"flush breakdown, {lines} lines ({} tokens): tokenize {lex:?}, \
|
||||
tokens.clone() {clone:?}, parse_tolerant (clone included) {parse:?}, \
|
||||
collect_defines {defines:?}, analyze {analyzing:?}, \
|
||||
resolve_external {external:?}, LineIndex::new {line_index:?}, \
|
||||
diagnostics::all {lint:?}",
|
||||
tokens.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::finding_one_token -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn finding_one_token_against_sweeping_the_stream() {
|
||||
// The before/after of the interactive handlers' token lookups, on the
|
||||
// lookup alone. Both halves run in the same measurement, against the same
|
||||
// stream, so neither number depends on remembering an earlier run.
|
||||
//
|
||||
// The cursor sits three quarters of the way down the file. A sweep costs
|
||||
// the distance from token zero, so measuring at the top would flatter it
|
||||
// and measuring at the very end would flatter it in the other direction;
|
||||
// three quarters is an ordinary place for a cursor to be.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let tokens = tokenize(&src).expect("the generated module lexes");
|
||||
let at = tokens[tokens.len() * 3 / 4].span.start;
|
||||
|
||||
// `selection.rs`: the innermost step of an expand-selection chain.
|
||||
let covers = |span: vlog_parser::TextRange| span.start <= at && at <= span.end;
|
||||
let sweep = mean(1_000, || {
|
||||
black_box(tokens.iter().find(|t| covers(t.span)).map(|t| t.span));
|
||||
});
|
||||
let search = mean(1_000, || {
|
||||
black_box(
|
||||
tokens.get(first_token_reaching(&tokens, black_box(at))).filter(|t| covers(t.span)),
|
||||
);
|
||||
});
|
||||
|
||||
// `completion.rs`: the balanced-parenthesis window between an opener
|
||||
// and the cursor. This one swept the *whole* stream — the filter has
|
||||
// no upper bound to break on — to reach a window two offsets name.
|
||||
let from = tokens[tokens.len() / 2].span.end;
|
||||
let window_sweep = mean(1_000, || {
|
||||
black_box(tokens.iter().filter(|t| t.span.start >= from && t.span.start < at).count());
|
||||
});
|
||||
let window_search = mean(1_000, || {
|
||||
let window = first_token_from(&tokens, black_box(from))..first_token_from(&tokens, at);
|
||||
black_box(tokens[window].len());
|
||||
});
|
||||
|
||||
eprintln!(
|
||||
"one token among {}: sweeping {sweep:?}, binary search {search:?}; \
|
||||
the balanced-paren window: sweeping {window_sweep:?}, \
|
||||
binary search {window_search:?}",
|
||||
tokens.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::hovering_a_local -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn hovering_a_local_declaration() {
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let dir = scratch(&format!("local{lines}"), &[("gen.sv", src.as_str())]);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&dir.join("gen.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), src.clone());
|
||||
// The last block's `w_n` use, so the answer is as far into the file as
|
||||
// this file goes.
|
||||
let offset = src.rfind("<= w_").expect("a use") as u32 + 4;
|
||||
let took = mean(20, || {
|
||||
black_box(hover(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
assert!(hover(&ws, &uri, offset).is_some(), "the offset must be a name");
|
||||
eprintln!("hover, local target: {lines} lines took {took:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::hovering_across -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn hovering_across_files_into_a_closed_file() {
|
||||
// The disk path: the target file is closed, so the card's heading line and
|
||||
// its snippet both come out of one read (`hover::disk_view`). The second
|
||||
// read that memo removed is measured beside it — it is the whole file
|
||||
// again, plus a whole `LineIndex` again.
|
||||
for lines in SIZES {
|
||||
let sub = generated_module("sub", lines);
|
||||
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
|
||||
let dir = scratch(&format!("cross{lines}"), &[("sub.sv", sub.as_str()), ("top.sv", top)]);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = top.find("data_in(").expect("a port connection") as u32;
|
||||
let took = mean(20, || {
|
||||
black_box(hover(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
let path = dir.join("sub.sv");
|
||||
let one_read = mean(20, || {
|
||||
let text = ws.text_of(black_box(&path)).expect("readable");
|
||||
black_box(LineIndex::new(&text));
|
||||
});
|
||||
// The card really is the cross-file one, read off that file's disk
|
||||
// text — a measurement of a hover that answered nothing is worthless.
|
||||
let card = hover(&ws, &uri, offset).expect("a cross-file card");
|
||||
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
|
||||
eprintln!(
|
||||
"hover, closed cross-file target: {lines} lines took {took:?} \
|
||||
(one read + LineIndex of that file: {one_read:?}, which is what the memo saves)"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::reindexing -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn reindexing_one_changed_file() {
|
||||
// What a save costs the index: one file re-parsed and merged, against a
|
||||
// workspace of twenty files of the same size.
|
||||
for lines in SIZES {
|
||||
let sources: Vec<(PathBuf, String)> = (0..20)
|
||||
.map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), lines)))
|
||||
.collect();
|
||||
let index = WorkspaceIndex::build(
|
||||
sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::<Vec<_>>(),
|
||||
);
|
||||
let (path, src) = &sources[7];
|
||||
let took = mean(10, || {
|
||||
let mut index = index.clone();
|
||||
index.update_file(black_box(path.clone()), black_box(src));
|
||||
black_box(index);
|
||||
});
|
||||
let clone = mean(10, || {
|
||||
black_box(index.clone());
|
||||
});
|
||||
eprintln!(
|
||||
"WorkspaceIndex::update_file: 20 files of {lines} lines took {took:?} \
|
||||
(of which {clone:?} is the clone this measurement needs to repeat itself)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::looking_up -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn looking_up_one_name_against_scanning_every_symbol() {
|
||||
// The before/after of the name-keyed lookup, on the lookup alone. What
|
||||
// `hover::live_symbol` actually saves is larger: every symbol the scan
|
||||
// used to reach and reject by name is also an `indexed_def_for_symbol`
|
||||
// call it no longer makes — two index lookups apiece.
|
||||
for lines in SIZES {
|
||||
let src = generated_module("gen", lines);
|
||||
let (tree, _) = parse_source_tolerant(&src);
|
||||
let semantics = analyze(&tree, &src);
|
||||
let name = format!("w_{}", lines / 8);
|
||||
let scan = mean(1_000, || {
|
||||
let name = black_box(name.as_str());
|
||||
black_box(semantics.symbols().iter().filter(|s| s.name == name).count());
|
||||
});
|
||||
let keyed = mean(1_000, || {
|
||||
black_box(semantics.symbols_named(black_box(&name)).count());
|
||||
});
|
||||
eprintln!(
|
||||
"one name among {} symbols: scanning {scan:?}, keyed lookup {keyed:?}",
|
||||
semantics.symbols().len()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -155,8 +155,21 @@ pub struct Server {
|
||||
/// one token, and a token is never reused: a client keys the bar it is
|
||||
/// showing off it.
|
||||
indexings: u32,
|
||||
/// Buffers that are text-current but analysis-stale: the newest applied
|
||||
/// text for each, in first-dirtied order. A `didChange` lands here instead
|
||||
/// of running a reparse, and every one of them is flushed — analyzed,
|
||||
/// republished — by the first thing that needs the analysis: the next
|
||||
/// request, the next non-`didChange` notification, or the quiet-period
|
||||
/// timer in `run`. See `docs/features/change-debounce/README.md`.
|
||||
dirty: Vec<(Uri, String)>,
|
||||
}
|
||||
|
||||
/// How long a burst of `didChange` notifications may sit unanalyzed once the
|
||||
/// typing has stopped, before the quiet-period timer flushes them anyway. The
|
||||
/// coalescing this buys — one reparse per burst instead of one per keystroke —
|
||||
/// is worth nothing if diagnostics never arrive until the next request does.
|
||||
const CHANGE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150);
|
||||
|
||||
/// What the workspace-rescan progress bar calls itself. One title for every
|
||||
/// rescan — startup, save, watched file, changed scope — because they are the
|
||||
/// same work and a user reading the status bar wants to know that.
|
||||
@@ -224,6 +237,7 @@ impl Server {
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
};
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
@@ -270,14 +284,33 @@ impl Server {
|
||||
/// `$/cancelRequest` mean anything: while a handler runs, the client's
|
||||
/// later requests and its cancels for them pile up together, and a cancel
|
||||
/// found next to its request answers that request for free.
|
||||
///
|
||||
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
|
||||
/// flushed here rather than left waiting for a request that may never
|
||||
/// come — diagnostics are the one answer the client never asks for.
|
||||
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
let queue = self.queue();
|
||||
while let Ok(message) = queue.recv() {
|
||||
loop {
|
||||
let message = if self.dirty.is_empty() {
|
||||
match queue.recv() {
|
||||
Ok(message) => message,
|
||||
Err(_) => return Ok(()),
|
||||
}
|
||||
} else {
|
||||
match queue.recv_timeout(CHANGE_DEBOUNCE) {
|
||||
Ok(message) => message,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
self.flush_dirty();
|
||||
continue;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
||||
}
|
||||
};
|
||||
if self.process_batch(burst(&queue, message))? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move the incoming messages onto a queue of our own, and report it.
|
||||
@@ -355,6 +388,12 @@ impl Server {
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn request(&mut self, request: Request) -> Response {
|
||||
// A request answers from a buffer's analysis, so any change the client
|
||||
// has already sent is in effect before it is answered — the order
|
||||
// contract the loop has always promised. Here is also where a typing
|
||||
// burst is coalesced: the changes before this request all become one
|
||||
// `set_document` in `flush_dirty`.
|
||||
self.flush_dirty();
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
// The large-file fast path answers first, and for most methods it
|
||||
@@ -1207,6 +1246,24 @@ impl Server {
|
||||
|
||||
fn notification(&mut self, notification: Notification) {
|
||||
let method = notification.method.clone();
|
||||
// A closing buffer's pending text is dropped *before* the flush, not
|
||||
// in the `didClose` arm below it: the flush would otherwise analyze
|
||||
// and publish diagnostics for a file the client has stopped looking
|
||||
// at, only for the close handler to clear them again a line later.
|
||||
// Every other dirty buffer still flushes, as it must — closing one
|
||||
// file says nothing about the rest (QA, change-debounce CD-1).
|
||||
if method == DidCloseTextDocument::METHOD {
|
||||
if let Some(uri) = closing_uri(¬ification) {
|
||||
self.dirty.retain(|(pending, _)| *pending != uri);
|
||||
}
|
||||
}
|
||||
// Everything but a `didChange` needs the buffers' analyses current —
|
||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||
// request gets happens here, with the one exception that *is* the
|
||||
// thing being deferred.
|
||||
if method != DidChangeTextDocument::METHOD {
|
||||
self.flush_dirty();
|
||||
}
|
||||
match method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
||||
@@ -1235,19 +1292,28 @@ impl Server {
|
||||
DidChangeTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
||||
// Incremental sync: the changes are ranges into the buffer
|
||||
// we hold, applied in order. A full-sync client's
|
||||
// rangeless change still replaces the whole buffer, so
|
||||
// "the last one wins" stays true for it. One notification
|
||||
// is one `set_document` — one reparse, one generation
|
||||
// bump — however many ranges it carried.
|
||||
// we hold — the newest applied text, which while dirty is
|
||||
// the pending one, not the last analyzed one — applied in
|
||||
// order. A full-sync client's rangeless change still
|
||||
// replaces the whole buffer, so "the last one wins" stays
|
||||
// true for it. A burst of changes is coalesced into one
|
||||
// `set_document` — one reparse, one generation bump — when
|
||||
// the buffer is flushed; see `mark_dirty`.
|
||||
if p.content_changes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let uri = p.text_document.uri;
|
||||
let base = self.workspace.document(&uri).map_or("", |doc| doc.text.as_str());
|
||||
let text = sync::apply_changes(base, &p.content_changes);
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
let text = {
|
||||
let base = self
|
||||
.dirty
|
||||
.iter()
|
||||
.find(|(pending, _)| *pending == uri)
|
||||
.map(|(_, text)| text.as_str())
|
||||
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
|
||||
.unwrap_or("");
|
||||
sync::apply_changes(base, &p.content_changes)
|
||||
};
|
||||
self.mark_dirty(uri, text);
|
||||
}
|
||||
}
|
||||
DidSaveTextDocument::METHOD => {
|
||||
@@ -1353,6 +1419,10 @@ impl Server {
|
||||
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
self.config_warnings.remove(&uri);
|
||||
// The buffer's unanalyzed change is already gone — it was
|
||||
// dropped at the top of this function, ahead of the flush
|
||||
// that would otherwise have analyzed it.
|
||||
//
|
||||
// The remembered token answer goes with the buffer: the
|
||||
// client drops what it was holding too, and nothing may
|
||||
// grow with the number of files ever opened.
|
||||
@@ -1711,6 +1781,29 @@ impl Server {
|
||||
self.announce_fast_path(&uri, was_large);
|
||||
}
|
||||
|
||||
/// Hold a buffer's newest text for later analysis. A change already held
|
||||
/// is replaced in place, so the entry's position in the flush order — the
|
||||
/// order the buffers were first dirtied in — survives a burst.
|
||||
fn mark_dirty(&mut self, uri: Uri, text: String) {
|
||||
match self.dirty.iter_mut().find(|(pending, _)| *pending == uri) {
|
||||
Some(entry) => entry.1 = text,
|
||||
None => self.dirty.push((uri, text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyze and republish every dirty buffer, oldest first. One flush is
|
||||
/// one `set_document` per buffer, so a whole typing burst costs one
|
||||
/// reparse per buffer it touched instead of one per keystroke.
|
||||
fn flush_dirty(&mut self) {
|
||||
if self.dirty.is_empty() {
|
||||
return;
|
||||
}
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// Say once, in the output channel, that a buffer is on the large-file
|
||||
/// fast path.
|
||||
///
|
||||
@@ -2114,6 +2207,16 @@ fn extract<P: DeserializeOwned>(
|
||||
notification.extract(&method)
|
||||
}
|
||||
|
||||
/// The buffer a `didClose` names, read without consuming the notification —
|
||||
/// the close handler runs after the flush, and dropping a pending change has
|
||||
/// to happen before it. `None` for params that do not parse, which the
|
||||
/// handler below ignores in exactly the same way.
|
||||
fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
serde_json::from_value::<DidCloseTextDocumentParams>(notification.params.clone())
|
||||
.ok()
|
||||
.map(|p| p.text_document.uri)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -4434,7 +4537,10 @@ mod tests {
|
||||
// incremental text sync
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `didChange`, carrying whatever changes were given.
|
||||
/// One `didChange`, carrying whatever changes were given. The flush at the
|
||||
/// end is the quiet-period timer firing: a test drives notifications one
|
||||
/// at a time, so the burst the loop would have coalesced never forms, and
|
||||
/// without this the buffer would sit dirty forever.
|
||||
fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
@@ -4443,10 +4549,15 @@ mod tests {
|
||||
"contentChanges": changes,
|
||||
}),
|
||||
);
|
||||
session.server.flush_dirty();
|
||||
}
|
||||
|
||||
/// The text the server currently holds for a buffer.
|
||||
/// The text the server currently holds for a buffer — the newest applied
|
||||
/// text, which while a change sits dirty is the pending one.
|
||||
fn buffer(session: &Session, uri: &Uri) -> String {
|
||||
if let Some((_, text)) = session.server.dirty.iter().find(|(pending, _)| pending == uri) {
|
||||
return text.clone();
|
||||
}
|
||||
session.server.workspace.document(uri).expect("an open buffer").text.clone()
|
||||
}
|
||||
|
||||
@@ -4498,6 +4609,87 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_changes_coalesces_into_one_reparse() {
|
||||
// The change debounce's whole payoff: a burst of `didChange`
|
||||
// notifications costs one reparse when the next thing that needs the
|
||||
// analysis flushes them, not one per keystroke.
|
||||
let tree = Tree::new("debounce");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
let before = session.server.generation;
|
||||
session.batch(vec![
|
||||
changed(&uri, 2, "module m;\n wire a;\nendmodule\n"),
|
||||
changed(&uri, 3, "module m;\n wire a;\n wire b;\nendmodule\n"),
|
||||
]);
|
||||
// Text-current, analysis-stale: nothing has reparsed yet, and the
|
||||
// newest text is already what the server holds.
|
||||
assert_eq!(session.server.generation, before, "no keystroke reparses on its own");
|
||||
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
|
||||
// The first request after the burst is answered from one flush.
|
||||
session.result(
|
||||
DocumentSymbolRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(session.server.generation, before + 1, "one reparse for the whole burst");
|
||||
assert!(session.server.dirty.is_empty(), "and nothing is left pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone() {
|
||||
// The debounce's other half: a buffer closed mid-edit is never
|
||||
// analyzed. Its pending text is dropped ahead of the flush at the top
|
||||
// of `notification`, so the client gets the one clearing publish and
|
||||
// nothing else — while every *other* dirty buffer still flushes,
|
||||
// because closing one file says nothing about the rest (QA, CD-1).
|
||||
let tree = Tree::new("closedirty");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let closing = session.open(&tree.path.join("closing.sv"), "module a;\nendmodule\n");
|
||||
let staying = session.open(&tree.path.join("staying.sv"), "module b;\nendmodule\n");
|
||||
let _ = session.published();
|
||||
|
||||
// Both buffers go dirty with text that would diagnose if analyzed.
|
||||
let before = session.server.generation;
|
||||
for (uri, text) in [
|
||||
(&closing, "module a;\n wire ;\nendmodule\n"),
|
||||
(&staying, "module b;\n wire ;\nendmodule\n"),
|
||||
] {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": text }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
assert_eq!(session.server.generation, before, "a keystroke reparses nothing on its own");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": closing } }),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
before + 1,
|
||||
"one reparse — the buffer still open; the closing one's text went with it"
|
||||
);
|
||||
assert!(session.server.dirty.is_empty(), "nothing left pending");
|
||||
|
||||
let published = session.published();
|
||||
let closed: Vec<_> = published.iter().filter(|p| p.uri == closing).collect();
|
||||
assert_eq!(closed.len(), 1, "exactly one publish for the closed buffer: {published:?}");
|
||||
assert!(closed[0].diagnostics.is_empty(), "and it is the clearing one: {published:?}");
|
||||
let open: Vec<_> = published.iter().filter(|p| p.uri == staying).collect();
|
||||
assert_eq!(open.len(), 1, "the other buffer publishes once: {published:?}");
|
||||
assert!(
|
||||
!open[0].diagnostics.is_empty(),
|
||||
"the other buffer's pending edit was flushed as usual: {published:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_notification_is_one_generation_bump_however_many_ranges() {
|
||||
// The pull-diagnostics `resultId` is this counter. One reparse and one
|
||||
@@ -6308,12 +6500,11 @@ mod tests {
|
||||
// The rebuild republished it, and an edit to it is still diagnosed.
|
||||
let published = session.published();
|
||||
assert!(published.iter().any(|p| p.uri == uri), "{published:#?}");
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }],
|
||||
}),
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "{published:#?}");
|
||||
@@ -6986,13 +7177,7 @@ mod tests {
|
||||
assert!(lines[0].contains("bytes"), "{}", lines[0]);
|
||||
|
||||
// A keystroke in it does not say it again.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": big_source() }],
|
||||
}),
|
||||
);
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
!session.logged().iter().any(|(_, m)| m.contains("large-file fast path")),
|
||||
"the line is per entry, not per notification"
|
||||
@@ -7016,12 +7201,11 @@ mod tests {
|
||||
|
||||
// The same buffer, edited past the threshold: one publish, empty, so
|
||||
// the squiggles go away rather than being left frozen on screen.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }],
|
||||
}),
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }]),
|
||||
);
|
||||
let cleared = session.published();
|
||||
assert_eq!(cleared.len(), 1, "one publish, as every change makes");
|
||||
@@ -7280,13 +7464,7 @@ mod tests {
|
||||
!session.server.workspace.document(&uri).expect("open").large,
|
||||
"the open buffer keeps the mode it was built in"
|
||||
);
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": big_source() }],
|
||||
}),
|
||||
);
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
session.server.workspace.document(&uri).expect("open").large,
|
||||
"and takes the fast path at its next change"
|
||||
|
||||
@@ -137,6 +137,60 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Finding a token by offset without sweeping the buffer
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// The lexer emits tokens in source order and they never overlap, so
|
||||
// `span.start` and `span.end` both rise across the vector: `end[i] <=
|
||||
// start[i+1] <= end[i+1]`. That makes both predicates below monotone, which
|
||||
// is the whole precondition `partition_point` needs. Every handler that used
|
||||
// to sweep the vector looking for a token at the cursor is one comparison
|
||||
// away from one of these two indices — see
|
||||
// `docs/features/interactive-latency/README.md` for the per-call-site
|
||||
// argument that each swap returns exactly what the sweep returned.
|
||||
|
||||
/// The index of the first token that **reaches** `offset` — the first with
|
||||
/// `span.end >= offset`. `tokens.len()` when none does.
|
||||
///
|
||||
/// Every token before it ends strictly before `offset`, so it cannot cover,
|
||||
/// end at, or contain `offset`. The token *at* this index is therefore the
|
||||
/// first candidate any such question has.
|
||||
pub fn first_token_reaching(tokens: &[Token], offset: u32) -> usize {
|
||||
tokens.partition_point(|token| token.span.end < offset)
|
||||
}
|
||||
|
||||
/// The index of the first token that **begins** at or after `offset` — the
|
||||
/// first with `span.start >= offset`. `tokens.len()` when none does.
|
||||
pub fn first_token_from(tokens: &[Token], offset: u32) -> usize {
|
||||
tokens.partition_point(|token| token.span.start < offset)
|
||||
}
|
||||
|
||||
/// A buffer of `blocks` repeated blocks, for the tests that check a binary
|
||||
/// search against the sweep it replaced.
|
||||
///
|
||||
/// Deliberately awkward: tokens written with no space between them (`a=b;`),
|
||||
/// line and block comments, a string, nested `begin`/`end` and several depths
|
||||
/// of parentheses. The offsets those tests walk are *every byte*, and the ones
|
||||
/// that could tell a binary search from a sweep are exactly the bytes two
|
||||
/// tokens share — which only adjacent punctuation produces.
|
||||
#[cfg(test)]
|
||||
pub fn mixed_buffer(blocks: usize) -> String {
|
||||
let mut src = String::from("module mixed (input logic clk, output logic [7:0] q);\n");
|
||||
for n in 0..blocks {
|
||||
src.push_str(&format!(
|
||||
" // block {n}\n \
|
||||
wire [7:0] w{n};assign w{n}=(q[0]?8'd1:8'd2)+{{4'h0,4'hF}};\n \
|
||||
/* {n} */ always @(posedge clk) begin\n \
|
||||
if (w{n}[0]) begin q<=w{n}; end else begin q<=8'd0; end\n \
|
||||
end\n \
|
||||
initial $display(\"block {n}\", w{n});\n"
|
||||
));
|
||||
}
|
||||
src.push_str("endmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// What the scope ladder decided: the files to index, the directories an
|
||||
/// `` `include`` in them is looked for in, and what to tell the user.
|
||||
#[derive(Default)]
|
||||
@@ -931,6 +985,45 @@ mod tests {
|
||||
Uri::from_str(s).expect("test uri parses")
|
||||
}
|
||||
|
||||
/// The precondition both binary searches rest on. If the lexer ever emits
|
||||
/// a token out of order, or two tokens that overlap, `partition_point`'s
|
||||
/// predicates stop being monotone and every handler that calls
|
||||
/// [`first_token_reaching`] or [`first_token_from`] starts answering
|
||||
/// something else. This is the test that would fail first.
|
||||
#[test]
|
||||
fn the_token_stream_rises_and_never_overlaps() {
|
||||
let text = mixed_buffer(20);
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
assert!(doc.tokens.len() > 500, "premise: a stream worth searching");
|
||||
for pair in doc.tokens.windows(2) {
|
||||
assert!(pair[0].span.start <= pair[1].span.start, "{pair:?}");
|
||||
assert!(pair[0].span.end <= pair[1].span.start, "overlapping tokens: {pair:?}");
|
||||
assert!(pair[0].span.start <= pair[0].span.end, "an inverted span: {pair:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Both searches, against the sweep they stand in for, at every byte of a
|
||||
/// buffer full of tokens that touch.
|
||||
#[test]
|
||||
fn every_offset_finds_the_token_a_sweep_would_have_found() {
|
||||
let text = mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &WorkspaceIndex::default());
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc.tokens.iter().position(|t| t.span.end >= offset);
|
||||
assert_eq!(
|
||||
first_token_reaching(&doc.tokens, offset),
|
||||
swept.unwrap_or(doc.tokens.len()),
|
||||
"first token reaching {offset}"
|
||||
);
|
||||
let swept = doc.tokens.iter().position(|t| t.span.start >= offset);
|
||||
assert_eq!(
|
||||
first_token_from(&doc.tokens, offset),
|
||||
swept.unwrap_or(doc.tokens.len()),
|
||||
"first token from {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_analyzes_a_clean_file() {
|
||||
let mut ws = Workspace::default();
|
||||
|
||||
@@ -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
|
||||
@@ -4592,3 +4606,139 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact};
|
||||
/// 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 = 3;
|
||||
|
||||
impl FileFacts {
|
||||
/// These facts as one line's worth of fields, tab-separated.
|
||||
@@ -185,6 +185,18 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn site(&mut self, site: &DeclSite) {
|
||||
@@ -298,7 +310,14 @@ 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));
|
||||
Some(Decl { name, name_span, kind, detail_span })
|
||||
}
|
||||
|
||||
fn site(&mut self) -> Option<DeclSite> {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -37,6 +37,10 @@ pub struct Def {
|
||||
pub name_span: TextRange,
|
||||
/// What kind of declaration it is, for an icon and for hover text.
|
||||
pub kind: SymbolKind,
|
||||
/// Where the declaration is *completed* when not at `name_span` — a
|
||||
/// non-ANSI port's body `input wire clk;`. A cross-file hover shows these
|
||||
/// lines; `None` for every declaration complete where it is named.
|
||||
pub detail_span: Option<TextRange>,
|
||||
}
|
||||
|
||||
/// Stable identity of one indexed declaration inside the current index.
|
||||
@@ -644,15 +648,21 @@ pub(crate) struct Decl {
|
||||
pub(crate) name: String,
|
||||
pub(crate) name_span: TextRange,
|
||||
pub(crate) kind: SymbolKind,
|
||||
pub(crate) detail_span: Option<TextRange>,
|
||||
}
|
||||
|
||||
impl Decl {
|
||||
fn of(symbol: &Symbol) -> Decl {
|
||||
Decl { name: symbol.name.clone(), name_span: symbol.name_span, kind: symbol.kind }
|
||||
Decl {
|
||||
name: symbol.name.clone(),
|
||||
name_span: symbol.name_span,
|
||||
kind: symbol.kind,
|
||||
detail_span: symbol.detail_span,
|
||||
}
|
||||
}
|
||||
|
||||
fn def(&self, file: FileId) -> Def {
|
||||
Def { file, name_span: self.name_span, kind: self.kind }
|
||||
Def { file, name_span: self.name_span, kind: self.kind, detail_span: self.detail_span }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 = "\
|
||||
|
||||
@@ -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,418 @@
|
||||
# hover-declarations
|
||||
|
||||
## Goal
|
||||
|
||||
Hovering a name declared in **this** file has always shown the declaration
|
||||
itself — `local_text` prints the kind, the name and the source lines
|
||||
`decl_span` covers. Hovering a name declared in *another* file showed only
|
||||
`**port** — declared in `sub.sv:3``: enough to navigate to, not enough to read.
|
||||
The owner's ask (2026-08-27) is that the cross-file card carry the declaration
|
||||
too — for a port its direction, type and width, `input logic [7:0] addr` — so
|
||||
that reading a connection list does not require jumping out of the file. This
|
||||
round adds a fenced `systemverilog` snippet of the declaration's source line(s)
|
||||
under each candidate's existing heading, fetched at hover time and omitted
|
||||
entirely whenever it could be the wrong line.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The index stays text-free.** `Def` is `{file, name_span, kind}` and the
|
||||
persisted facts and `FACTS_FORMAT` are untouched
|
||||
(`docs/features/workspace-index/README.md`,
|
||||
`docs/features/index-persistence/README.md`). A hover is a rare, one-name,
|
||||
human-speed request; reading one file to answer it is the same trade
|
||||
`locate::line_number` has always made for the `file:line` half of the card.
|
||||
- **`reference.name` is the declared name.** Every `Definition::External`
|
||||
answer comes from a reference (`ExternalResolutions::definition_of` looks the
|
||||
target up by `ReferenceId`), and `resolve_external` finds the `Def` by
|
||||
passing exactly that `name` to `WorkspaceIndex::units` / `member`. So the
|
||||
name is the bare declared spelling — `WIDTH` for a `p::WIDTH` use, `clk` for
|
||||
a `.clk(...)` connection — never a qualified path. That is what makes it
|
||||
usable as the guard's expected text.
|
||||
- **Disk text is what the index was built from.** `Workspace::text_of` prefers
|
||||
an open buffer, which is right for a location and wrong for a snippet, so the
|
||||
open case is handled separately and never reaches `text_of`.
|
||||
- **A `decl_span` may be enormous.** A module's `decl_span` is its whole body
|
||||
(`bind_module` passes the item span), and one netlist line has no bound at
|
||||
all — hence the two caps below.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed**
|
||||
|
||||
- `crate::nav::indexed_def_for_symbol` — raised from private to `pub(crate)`,
|
||||
behaviour byte-for-byte unchanged. `nav.rs` walks it live-symbol → indexed
|
||||
`Def`; this feature walks the same relation the other way (scan the open
|
||||
buffer's symbols for the one that maps to this `Def`), which is precisely
|
||||
what `nav.rs`'s own `include_declaration` block already does for the
|
||||
declaration location. One matcher, so a hover snippet and a
|
||||
go-to-definition can never disagree about which declaration is which.
|
||||
- `Workspace::document_for_path`, `Workspace::text_of`, `WorkspaceIndex::path`.
|
||||
- `crate::convert::Positions::whole_lines`, `vlog_parser::LineIndex`.
|
||||
- `vlog_semantic::{Def, Symbol}` — read only; nothing added to either.
|
||||
|
||||
**Promised**
|
||||
|
||||
- `nav.rs` keeps its behaviour: the visibility change is the only edit to it,
|
||||
and its whole test module stays green unmodified.
|
||||
- The `` ```systemverilog `` fence tag is used for the new block, as the
|
||||
fence-tag contract in `docs/features/lucisv-server/README.md` requires — it
|
||||
is the only thing that colours a hover card.
|
||||
- Nothing is added to `Def`, to the facts file, or to `FACTS_FORMAT`; a cache
|
||||
written before this round is still current after it.
|
||||
**Superseded 2026-08-28 by `docs/features/port-detail-spans/README.md`**,
|
||||
which adds `Def::detail_span`, writes it in every declaration record and
|
||||
bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is
|
||||
discarded. This round's own promise held while it was this round's to
|
||||
make; the index is text-free either way (a span is not text).
|
||||
- The heading line `**label** — declared in `file:line`` is unchanged, so a
|
||||
client (or a test) reading only that half sees exactly what it saw before.
|
||||
|
||||
## How the snippet is fetched
|
||||
|
||||
`declaration_snippet(ws, def, name)` in `hover.rs`, once per candidate:
|
||||
|
||||
1. **The target file is open** (`ws.document_for_path`). The index's span is
|
||||
against that file's *last saved* text, so an unsaved edit above the
|
||||
declaration has already moved it and reading the buffer at `def.name_span`
|
||||
would print whatever those offsets now cover. Match the `Def` to a live
|
||||
symbol **logically** instead — same name, and `indexed_def_for_symbol` maps
|
||||
it back to this same `Def` — and widen that symbol's live `decl_span` to
|
||||
whole lines.
|
||||
2. **Not open**: `ws.text_of(path)` (disk, since no buffer backs it), a fresh
|
||||
`LineIndex`, and `def.name_span` widened to whole lines.
|
||||
3. **Guard, both paths.** Slice the chosen text at the chosen name span and
|
||||
require it to equal the hovered name. `str::get` returns `None` for a span
|
||||
that runs past the text or lands mid-character, so a stale or shifted span
|
||||
fails the check rather than panicking. Any failure — unreadable file, no
|
||||
live symbol, text that does not spell the name — drops the snippet and
|
||||
leaves today's card exactly as it was. **A hover must never lie; less
|
||||
information beats wrong information.**
|
||||
|
||||
Note the asymmetry, and that it is deliberate: the open path widens
|
||||
`decl_span` (mirroring `local_text`, which is the only span a live symbol
|
||||
offers that covers a whole multi-line declaration), the disk path widens
|
||||
`def.name_span` (the only span the index holds). For the declarations the ask
|
||||
is about — ports, parameters, typedefs, a module header — both are one line
|
||||
and the two paths print the same thing.
|
||||
|
||||
## Cutting it down
|
||||
|
||||
`cut_to_size` trims trailing blank space (as `local_text` does; leading
|
||||
indentation stays, so the line reads as written) and then applies two caps,
|
||||
each with its own note under the fence:
|
||||
|
||||
| Cap | Value | Why |
|
||||
|---|---|---|
|
||||
| lines | `SNIPPET_LINES` = 5 | a module's `decl_span` is its whole body |
|
||||
| characters | `SNIPPET_CHARS` = 400 | one netlist line can be megabytes |
|
||||
|
||||
A cut appends ` …` inside the fence and `*shown to N lines*` /
|
||||
`*shown to N characters*` after it — the same shape as the macro card's
|
||||
`*truncated at N characters*`, so the two footnotes read as one convention.
|
||||
The character cap counts `char`s and cuts on a boundary.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `declaration_snippet` with the open-buffer and disk paths.
|
||||
- [x] Guard on both paths; snippet omitted on any mismatch.
|
||||
- [x] Line and character caps with a note.
|
||||
- [x] One snippet per candidate for an ambiguous name.
|
||||
- [x] `indexed_def_for_symbol` shared with `nav.rs`, behaviour unchanged.
|
||||
- [x] Tests (9 new, in `hover.rs`'s own test module).
|
||||
- [x] Hover row + hover section in `docs/features/lucisv-server/README.md`.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- Not done, deliberately: no facts/cache change, nothing in `vlog_semantic`,
|
||||
no TODO.md edit (no existing checklist item covers this; §8's hover items
|
||||
are all already checked, and inventing one is out of scope).
|
||||
- [x] **2026-08-28**: one disk read per file per hover (`disk_view` memo);
|
||||
QA finding 4 closed.
|
||||
- [x] **2026-08-28**: `live_symbol` (and `nav::indexed_references`) look a
|
||||
name up instead of scanning every symbol, with the first-match
|
||||
tie-break pinned by test.
|
||||
- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior
|
||||
`\r` into the fence; QA finding 2 closed.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev
|
||||
|
||||
- Read the brief, `hover.rs`, `nav.rs`, `state.rs` and `convert.rs`. Confirmed
|
||||
the two facts the design rests on: `set_document` does **not** rebuild the
|
||||
index (so an open buffer really can hold a span the index does not know
|
||||
about — the case step 1 exists for), and `follow_one` looks a `Def` up by
|
||||
`reference.name`, which is what licenses using that name as the guard's
|
||||
expected text rather than trying to recover a name from `Def`.
|
||||
- Added `declaration_snippet`, `live_symbol`, `span_text`, `fenced` and
|
||||
`cut_to_size` to `hover.rs`, plus the two caps as consts. `symbol_hover`'s
|
||||
`External` arm now appends the snippet to each candidate's part; the heading
|
||||
it appends to is untouched.
|
||||
- Raised `nav::indexed_def_for_symbol` to `pub(crate)` with a doc line naming
|
||||
the second caller. No other change to `nav.rs`.
|
||||
- Decision: the open path uses `decl_span` and the disk path `name_span`,
|
||||
per the brief. Considered using `name_span` on both for symmetry — it would
|
||||
make a big module's card one header line rather than five — but that would
|
||||
drop the live-buffer case's only handle on a multi-line declaration, and the
|
||||
line cap already bounds the damage. Recorded in *How the snippet is fetched*
|
||||
so the asymmetry is a decision and not an accident.
|
||||
- Decision: no fallback from the open path to disk text. If a file is open and
|
||||
no live symbol matches, the buffer has been edited past the index and the
|
||||
indexed span is exactly the thing that cannot be trusted; falling back would
|
||||
re-introduce the wrong-line risk the guard exists to remove.
|
||||
- Nine tests added (listed below). Ran the gates: fmt
|
||||
clean, clippy `--all-targets` clean, `cargo test --workspace` green at 2372
|
||||
passed / 0 failed / 12 ignored.
|
||||
|
||||
**Tests added** (all in `crates/lucisv_server/src/hover.rs`, `mod tests`):
|
||||
|
||||
| Test | Pins |
|
||||
|---|---|
|
||||
| `a_cross_file_port_connection_shows_the_ports_own_declaration_line` | the ask: direction + type + width, and only that port's line |
|
||||
| `a_cross_file_module_instance_shows_its_header_line` | the module header, disk path |
|
||||
| `a_package_member_shows_its_declaration_line` | a `localparam` and a `typedef` through `import p::*` |
|
||||
| `an_unsaved_edit_that_moved_the_declaration_is_read_at_its_live_span` | live line, not the stale-span line (asserts the *new* width and the absence of the old) |
|
||||
| `a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line` | guard, disk half: file rewritten under a live index → no fence at all, heading intact |
|
||||
| `an_open_buffer_that_no_longer_declares_the_name_drops_the_snippet` | guard, live half: the port renamed away in the buffer |
|
||||
| `a_very_long_declaration_line_is_cut_with_a_note` | the character cap and its note |
|
||||
| `a_declaration_spanning_many_lines_is_cut_at_the_line_limit` | the line cap, via an open module whose `decl_span` is its body |
|
||||
| `two_files_declaring_one_name_each_get_their_own_snippet` | ambiguous name: both headings, both snippets |
|
||||
|
||||
### 2026-08-28 — dev (performance: one disk read, one name lookup)
|
||||
|
||||
Parts A2 and A3 of the "Improve LSP performance + hover accuracy" round.
|
||||
Behavior of every card is unchanged; both items are the same answer, reached
|
||||
with less work. Numbers in `docs/perf/README.md`.
|
||||
|
||||
- **A2 — one read per file per hover.** A hover into a *closed* file used to
|
||||
read that file and build a `LineIndex` over it twice: once in
|
||||
`locate::line_number` for the `file:line` heading, once in
|
||||
`declaration_snippet` for the fenced lines. This is QA's finding 4 below,
|
||||
and it is now closed. `symbol_hover` holds a per-request memo — one
|
||||
`(path, text, LineIndex)` in `disk_view` — that the heading and the snippet
|
||||
both read, and `declaration_snippet` no longer touches the disk at all: it
|
||||
is now the *open-buffer* path only, with the closed-file path inlined in
|
||||
`symbol_hover` beside the heading it shares a read with. The
|
||||
`spells_exactly` guard applies on both paths exactly as before. A card
|
||||
naming one file twice (two declarations in one file) now pays for one read,
|
||||
not two, which is why the memo is keyed by path rather than being a single
|
||||
`Option` per candidate.
|
||||
- Measured: 34 ms → 16.3 ms on QA's own 31.7 MB measurement, and 141 µs of
|
||||
a 148 µs hover at 10 000 lines is that one read. See `docs/perf`.
|
||||
- QA's measurement test was renamed
|
||||
`hovering_into_a_large_closed_file_reads_it_twice` →
|
||||
`..._reads_it_once`, since the doubling it was named for is gone. The QA
|
||||
log below still names the old spelling; that section is QA's to amend.
|
||||
- **A3 — `live_symbol` stops scanning every symbol.** Walking the whole
|
||||
buffer's symbol table and calling `nav::indexed_def_for_symbol` (two index
|
||||
lookups) on every symbol whose name happened to match — and reaching every
|
||||
symbol whose name did not — became a name-keyed lookup:
|
||||
`vlog_semantic::Semantics::symbols_named(name)`, two binary searches over a
|
||||
side table of symbol ids sorted by name, built once during `analyze`. Only
|
||||
same-named declarations are probed. A side table rather than a
|
||||
`HashMap<String, Vec<SymbolId>>` so that `Semantics` — which is cloned per
|
||||
document — does not carry a second copy of every name it already holds;
|
||||
four bytes per symbol against a `String` per symbol.
|
||||
- **The tie-break is preserved.** The map's lists are built by walking the
|
||||
symbols in order, so `symbols_named` yields declaration order — the same
|
||||
order, and the same first match, the old `symbols().iter().find(..)`
|
||||
made. Pinned by `looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
|
||||
in `crates/vlog_semantic/tests/semantics.rs`, which compares the two
|
||||
answers directly and asserts the earlier declaration comes first. QA's
|
||||
`duplicate_live_declarations_of_one_name_pick_the_first_one_silently`
|
||||
(finding 3 below) still passes, unchanged.
|
||||
- `nav.rs`'s `indexed_references` had the same scan-by-name for the
|
||||
declaration's live span; it is the same swap and was made in the same
|
||||
change, for the same reason.
|
||||
- `vlog_refactor::ports.rs:1154` has a third one (`symbols().iter()
|
||||
.position(|s| s.name == port && …)`). It is not a trivial swap — the
|
||||
predicate carries a kind and a span test and the code wants the
|
||||
*position* as a `SymbolId` — and it is in another crate, so it is left
|
||||
alone and recorded here rather than done.
|
||||
- Cost: four bytes per symbol. Measured saving on the lookup alone:
|
||||
8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`).
|
||||
|
||||
### 2026-08-28 — dev (CRLF, closing QA finding 2)
|
||||
|
||||
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
|
||||
`\r` inside the fence — is **fixed**, as part of `port-detail-spans`' PDS-4.
|
||||
Every line a card shows now goes through `attached_lines`, which strips a
|
||||
trailing `\r` as it composes each line; that covers both this feature's
|
||||
snippet path and `local_text`'s in-file path, which QA named as having the
|
||||
same property, because both reach it through `fenced_sections`. Display
|
||||
text only: no buffer is written.
|
||||
- QA's pinned regression test was named for the old behaviour
|
||||
(`a_crlf_multiline_snippet_keeps_interior_carriage_returns`) and asserted
|
||||
it; it is now `a_crlf_multiline_snippet_carries_no_carriage_returns` and
|
||||
asserts the opposite, plus that the lines read as written. The QA log below
|
||||
still names the old spelling; that section is QA's to amend.
|
||||
- No other change to this feature. `spells_exactly`, the caps and the
|
||||
disk/live split are untouched.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA
|
||||
|
||||
Read the brief, the dev's Work log, and `crates/lucisv_server/src/hover.rs` /
|
||||
`nav.rs` in full. Ran the gates first (all green before any probing): `cargo
|
||||
fmt --check` clean, `cargo clippy --all-targets --workspace -- -D warnings`
|
||||
clean, `cargo test --workspace` green — 1173 passed / 0 failed / 12 ignored
|
||||
(pre-existing) before this round's own probes were added.
|
||||
|
||||
Then attacked `declaration_snippet`, `live_symbol`, `span_text` and
|
||||
`cut_to_size` along the seven angles in the charter. Eight probe tests added
|
||||
to a new `mod qa_hover_declarations` in `hover.rs` (one `#[ignore]`d perf
|
||||
measurement); one real defect found and fixed with a ninth test pinning it.
|
||||
|
||||
**Finding 1 — MEDIUM, fixed.** *The guard was a fixed-length substring check,
|
||||
not a whole-identifier check, so an edit that only **extends** a name defeats
|
||||
it.* `declaration_snippet`'s guard (`hover.rs:243` and `:252`, before the fix)
|
||||
compared `span_text(text, span)` — a slice of exactly `name.len()` bytes at
|
||||
the *old, recorded* offset — against `name`. `def.name_span`'s length is
|
||||
whatever the name was when the index was last built; it does not grow if the
|
||||
file is edited without a reindex. So: index built on `input logic [7:0]
|
||||
addr;`, then the file is rewritten on disk to `input logic [7:0] addr2;`
|
||||
*without* triggering a reindex (an ordinary edit-then-hover-before-save-event
|
||||
race, exactly the staleness window this feature's guard exists for). The old
|
||||
span still covers exactly the four bytes `"addr"` — a *prefix* of the new
|
||||
`"addr2"` — so `span_text` returns `Some("addr")`, equals the hovered name,
|
||||
and the guard passed. The card for `.addr(...)` then showed
|
||||
`` input logic [7:0] addr2 `` under a heading that says `addr`'s declaration,
|
||||
one line pretending to be a name it is not — exactly the masked-corruption
|
||||
shape CLAUDE.md's invariant 4 is about, applied to this round's new safety
|
||||
net rather than `verify.rs`.
|
||||
- Repro (was a failing/panicking assertion, now a passing regression test):
|
||||
`a_disk_edit_that_only_appends_to_the_name_defeats_the_guard`,
|
||||
`hover.rs:1060`.
|
||||
- Fix: added `spells_exactly` (`hover.rs:293`) and `continues_a_name`
|
||||
(`hover.rs:306`), and switched both guard call sites
|
||||
(`declaration_snippet`'s live and disk branches) to it. It keeps the
|
||||
existing text-equality check and additionally requires that the
|
||||
character immediately outside the span on either side (if any) is not an
|
||||
identifier-continuation character (`[A-Za-z0-9_$]`) — turning a
|
||||
prefix/suffix match back into a miss. Applied to *both* branches for one
|
||||
guard, one guarantee, even though the live branch's `symbol.name_span`
|
||||
(a token span from a fresh parse) could not actually suffer this —
|
||||
`symbol.name == name` was already checked before the span comparison, so
|
||||
the length always matched there. No behavior change for any span that is
|
||||
a genuine whole identifier, which is every case the dev's 9 tests and the
|
||||
existing corpus tests exercise — full `cargo test --workspace` stayed
|
||||
green (1173 passed / 0 failed / 13 ignored, the 13th being this round's
|
||||
own perf probe) after the fix.
|
||||
- This does **not** close every staleness gap by design — a same-length
|
||||
edit that changes an identifier into a different same-length identifier,
|
||||
or that changes what a name's *kind* means without renaming it, is still
|
||||
the accepted risk window the Assumptions section already names ("a hover
|
||||
is a rare, one-name, human-speed request"). What the fix removes is
|
||||
specifically the case where the *shown text visibly disagrees with the
|
||||
name in the heading* — the one the guard's stated promise ("never show a
|
||||
wrong line") is about.
|
||||
|
||||
**Finding 2 — LOW, filed, not fixed.** *A CRLF file's multi-line snippet
|
||||
keeps the embedded `\r` on every interior line, only the last one is
|
||||
trimmed.* `cut_to_size` (`hover.rs`, unchanged by QA) calls `trim_end()` once
|
||||
on the whole cut string, which strips a *trailing* `\r` (and `\n`) but not an
|
||||
interior one before a kept newline. `local_text` (the in-file branch,
|
||||
pre-existing, not part of this round) has the identical property via the same
|
||||
`whole_lines`/`trim_end` shape, so this is not new behavior introduced by
|
||||
this feature, just newly reachable from a second call site. Cosmetic, not a
|
||||
correctness break: the bytes shown are exactly the file's own bytes, and a
|
||||
fenced code block renders them close to verbatim either way. Pinned as a
|
||||
permanent regression test rather than fixed, since a real fix (stripping
|
||||
`\r` before every kept `\n`, in both `local_text` and here) is a
|
||||
cross-cutting change to shared rendering, out of this round's stated scope
|
||||
(`hover.rs`'s `External` arm and its shared helper with `nav.rs`).
|
||||
- Repro: `a_crlf_multiline_snippet_keeps_interior_carriage_returns`,
|
||||
`hover.rs:1156`.
|
||||
|
||||
**Finding 3 — LOW/accepted, pinned as a regression test, not a defect of this
|
||||
round.** *Two live declarations of the same name+kind in one open buffer (a
|
||||
transient mid-edit state, e.g. a duplicate line not yet deleted) make
|
||||
`live_symbol`'s `.find()` pick whichever comes first in `Semantics::symbols()`
|
||||
order, silently.* `indexed_def_for_symbol` (`nav.rs:164`, visibility-only
|
||||
change this round) maps *any* live symbol with a matching name/kind/owner
|
||||
back to the single persisted `Def` for that name when the index itself has
|
||||
only one — it does not know or care that the *live* buffer momentarily has
|
||||
two. This is inherited, unchanged behavior from `nav.rs`'s existing
|
||||
go-to-definition matcher (the Handshakes section calls this out on purpose:
|
||||
"one matcher, so a hover snippet and a go-to-definition can never disagree").
|
||||
Not a lie in the sense the guard is about — the guard still requires the
|
||||
*chosen* symbol's own span to spell the name exactly, which it always does
|
||||
here by construction — but it is a silent, unsignaled choice between two
|
||||
candidates. Filed rather than fixed: fixing it means changing
|
||||
`indexed_def_for_symbol`'s matching rule, which is nav.rs's and explicitly
|
||||
out of this round's scope ("nav tests must stay green," brief line 27).
|
||||
- Repro: `duplicate_live_declarations_of_one_name_pick_the_first_one_silently`,
|
||||
`hover.rs:1126`.
|
||||
|
||||
**Finding 4 — perf note, not a defect, no action taken.** *A hover resolving
|
||||
into a large closed file reads the file and builds a `LineIndex` over it
|
||||
twice*: once inside `locate::line_number` (for the `file:line` heading — this
|
||||
predates this round) and again inside `declaration_snippet` (for the
|
||||
snippet — new this round), independently, from the same disk path. Measured
|
||||
in release mode: a 31.7 MB synthetic file (600k filler lines behind a small
|
||||
port declaration, `maxFileSize` raised so it indexes at all) took 34 ms for
|
||||
one hover — acceptable for a rare, single-shot request, but a real, avoidable
|
||||
doubling of I/O and linear scan work per disk-path candidate. A fix would
|
||||
mean threading one read/`LineIndex` through both `line_number` and
|
||||
`declaration_snippet`, which touches `locate.rs` (also used by `macro_hover`)
|
||||
and is a small refactor rather than a one-line change — noted per the
|
||||
charter's "note it, don't redesign" rather than attempted.
|
||||
- Measurement, `#[ignore]`d (writes ~30 MB, not a correctness assertion):
|
||||
`hovering_into_a_large_closed_file_reads_it_twice`, `hover.rs:1325`. Run
|
||||
with `cargo test --release -p lucisv_server large_closed -- --ignored
|
||||
--nocapture`.
|
||||
- **Amended 2026-08-28 — QA.** Closed by A2 (`docs/perf/README.md`):
|
||||
`symbol_hover`'s `disk_view` memo now shares one read + one `LineIndex`
|
||||
between the heading and the snippet. Re-ran the same measurement (now
|
||||
named `..._reads_it_once`): **17.0 ms**, against the documented
|
||||
"34 ms → 16.3 ms" — matches within the run-to-run noise `docs/perf/
|
||||
README.md` itself calls out. No longer an open finding.
|
||||
|
||||
**Verified, no finding** (angles from the charter that turned up nothing):
|
||||
UTF-8 multi-byte content before a declaration, on the same file, does not
|
||||
panic `span_text`/`whole_lines` (`multibyte_utf8_before_the_declaration_does_not_panic`,
|
||||
`hover.rs`) — both are `.get()`-based and this stayed a belt-and-braces pin.
|
||||
A declaration at byte offset 0 and a declaration on the file's last line with
|
||||
no trailing newline both render correctly, no underflow
|
||||
(`a_declaration_at_the_very_start_of_the_file_is_shown`,
|
||||
`a_declaration_on_the_last_line_with_no_trailing_newline_is_shown`). The line
|
||||
cap (`SNIPPET_LINES` = 5) and character cap (`SNIPPET_CHARS` = 400) are both
|
||||
exact-boundary-safe — 5 lines / 400 chars is not cut, 6 lines / 401 chars is,
|
||||
and a 400-char boundary landing mid multi-byte character is not split because
|
||||
`cut_to_size` counts with `char_indices`, never raw bytes
|
||||
(`exactly_the_line_cap_is_not_cut_one_more_is`,
|
||||
`exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe`). A
|
||||
case-mismatched open buffer (same file, different-case path on a
|
||||
case-insensitive filesystem) is not recognized as "the target file open" by
|
||||
`document_for_path`'s exact `PathBuf` equality, so it falls back to the disk
|
||||
path rather than mixing the two identities — the safe direction, confirmed
|
||||
with unsaved edits in the mismatched buffer never leaking into the card
|
||||
(`a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk`,
|
||||
macOS/Windows-gated). Multiple ambiguous candidates each render from their
|
||||
own file with no cross-contamination — the dev's own
|
||||
`two_files_declaring_one_name_each_get_their_own_snippet` already covers
|
||||
this and reads fine without a divider between candidates (each fenced block
|
||||
is its own visual unit).
|
||||
|
||||
**Gates, final.** `cargo fmt --check` clean. `cargo clippy --all-targets
|
||||
--workspace -- -D warnings` clean. `cargo test --workspace`: 1173 passed / 0
|
||||
failed / 13 ignored (12 pre-existing + this round's one perf probe).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-27 — lead.** Reviewed the full diff after QA's SHIP verdict;
|
||||
gates re-run independently (fmt clean, clippy silent, 1173 server tests
|
||||
green). The shape is right: no widening of persisted facts, snippets
|
||||
fetched at hover time from whichever text the span is valid against
|
||||
(live logical match through `nav.rs`'s one matcher, disk otherwise),
|
||||
and a guard that prefers no snippet to a wrong one. QA's MEDIUM find —
|
||||
the fixed-length substring guard passing on a name that had merely been
|
||||
*extended* in place — is precisely the masked-corruption shape
|
||||
invariant 4 exists for, applied correctly to a new forgiveness path
|
||||
outside `verify.rs`; the `spells_exactly` boundary check closes it on
|
||||
both the live and disk paths and the attack test pins it. The
|
||||
deliberate asymmetry (live path shows `decl_span`, disk path the name's
|
||||
line) is documented and bounded by the caps; the duplicate-live-symbol
|
||||
tie-break is inherited from the shared matcher and correctly pinned
|
||||
rather than re-designed. The CRLF interior-`\r` cosmetic and the
|
||||
double-read of large closed files are accepted as filed. Accepted;
|
||||
committed by the lead.
|
||||
@@ -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
|
||||
|
||||
@@ -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` |
|
||||
| `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
|
||||
@@ -588,14 +590,29 @@ overlap trap and the round-trip property:
|
||||
(`docs/features/include-nav/README.md`).
|
||||
2. **A reference** resolved in-file: the symbol's kind, its name, and the
|
||||
source lines its `decl_span` covers.
|
||||
3. **A reference** answered only by the workspace overlay: the kind and name,
|
||||
plus each target's file and line.
|
||||
3. **A reference** answered only by the workspace overlay: the kind, each
|
||||
target's file and line, and — since 2026-08-27 — **that declaration's own
|
||||
source line(s)** beneath each heading.
|
||||
4. **A declaration** the cursor is sitting on: its own kind, name and
|
||||
snippet.
|
||||
|
||||
The snippet is `decl_span` widened to whole lines, so a declaration reads as
|
||||
it was written rather than starting mid-line.
|
||||
|
||||
**The cross-file snippet (case 3).** The index holds no file contents, so the
|
||||
line is fetched per hover: from the **live buffer** when the target file is
|
||||
open — matched to the indexed `Def` logically through
|
||||
`nav::indexed_def_for_symbol`, because an unsaved edit above a declaration has
|
||||
already moved the span the index recorded — and from disk otherwise, where the
|
||||
recorded span is the one the index was built from. Either way the chosen text
|
||||
is sliced at the chosen name span and required to spell the hovered name; on
|
||||
any mismatch, unreadable file or unmatched buffer the snippet is dropped and
|
||||
the card is exactly what it was before this feature. It is capped at 5 lines
|
||||
and 400 characters (a module's `decl_span` is its whole body; a netlist line
|
||||
has no bound), with a footnote naming whichever cap cut it. Rules, the
|
||||
deliberate span asymmetry between the two paths, and the guard's attack tests:
|
||||
`docs/features/hover-declarations/README.md`.
|
||||
|
||||
**A macro card has a second half since M14 (0.5.0).** Under the definition it
|
||||
shows what the hovered *use* expands to in one step — the body with this call's
|
||||
arguments substituted for the parameters — fenced identically, with a footnote
|
||||
@@ -617,8 +634,10 @@ registered for exactly that language id, and that grammar is the *only* thing
|
||||
that colours a hover card: semantic tokens cannot reach markdown, and VS Code
|
||||
resolves a fence's info string against the language registry rather than
|
||||
against the hovered document. Changing the tag, or fencing a new surface with a
|
||||
different one, silently returns every card to flat grey. The three call sites
|
||||
pin the exact fenced string in their own tests; the registration is pinned by
|
||||
different one, silently returns every card to flat grey. Every call site —
|
||||
`define_text`, `expansion_text`, `local_text`, the cross-file `fenced` and the
|
||||
completion templates' documentation panel — pins the exact fenced string in its
|
||||
own tests; the registration is pinned by
|
||||
`crates/lucisv_server/tests/grammar.rs`, which also holds the extension's keyword
|
||||
list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
`docs/features/editor-packaging/README.md`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
# perf — measured numbers for the paths a keystroke and a hover run through
|
||||
|
||||
## Goal
|
||||
|
||||
Give the server's hot paths — `analyze`, opening a buffer, answering a hover,
|
||||
reindexing one saved file, and (since round 2) one flush stage by stage and
|
||||
one keystroke's round trip over the wire — a number that is *measured* rather
|
||||
than guessed, taken the same way every time, so a later round can say whether
|
||||
it made something faster or only different. This is the record; the
|
||||
measurements themselves are `#[ignore]`d tests in
|
||||
`crates/lucisv_server/src/perf.rs` and in
|
||||
`crates/lucisv_server/tests/e2e.rs`, run on demand and asserting nothing about
|
||||
duration. Nothing here is a performance *budget*: a test that fails when a
|
||||
machine is busy is a test that gets deleted.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **No benchmark dependency.** `criterion` and friends are out: `CLAUDE.md`
|
||||
requires a written justification for any new dependency, and the workspace
|
||||
has six direct ones (`rayon`, `lsp-server`, `lsp-types`, `serde`,
|
||||
`serde_json`, plus their pins). `std::time::Instant` + `eprintln!` is the
|
||||
shape this repo already uses for perf notes (`hover.rs`'s QA measurement,
|
||||
`includes.rs`, `inlay.rs`, `file_ops.rs`) and it is what is used here.
|
||||
- **`--test-threads=1` or the numbers are noise.** The harness otherwise runs
|
||||
these concurrently with each other and with 1 200 other tests. The first run
|
||||
of these measurements was taken without it and reported a cross-file hover
|
||||
as *cheaper* than the single file read it performs; that is how obvious the
|
||||
contamination is.
|
||||
- **Means, not single runs.** Each measurement is the mean of 10–1 000 runs
|
||||
(`perf::mean`), with `std::hint::black_box` around the inputs and results so
|
||||
a release build cannot optimize the work away.
|
||||
- **Generated input, not the corpus.** `perf::generated_module` builds an
|
||||
ANSI-headed module of repeated four-line blocks (a wire, an assign, a
|
||||
register, an update) at 1 000 and 10 000 lines. It is uniform, which real
|
||||
RTL is not — the numbers are a scale, not a prediction for any given file.
|
||||
The corpus-scale numbers this repo already has live where they were taken
|
||||
(`docs/features/incremental-index`, `index-persistence`, `references-nav`).
|
||||
|
||||
## Reproducing
|
||||
|
||||
```text
|
||||
cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
Each test's own doc comment names the narrower filter for running it alone.
|
||||
The over-the-wire measurement lives with the other end-to-end tests, because
|
||||
it spawns the shipped binary, so it has its own command:
|
||||
|
||||
```text
|
||||
cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
The one older measurement quoted below has a third:
|
||||
|
||||
```text
|
||||
cargo test --release -p lucisv_server large_closed -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
## The machine
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| CPU | Apple M1 Max (`uname -m` = `arm64`) |
|
||||
| OS | macOS 27.0 (build 26A5421a) |
|
||||
| build | `--release`, workspace at 0.12.1 + rounds 1 and 2 uncommitted |
|
||||
| date | 2026-08-28 (every figure below re-measured this day, round 2) |
|
||||
|
||||
## Numbers
|
||||
|
||||
All figures are the mean of the runs named above. "1k" and "10k" are the
|
||||
generated module's line counts (29 KB / 501 symbols and 309 KB / 5 001
|
||||
symbols respectively).
|
||||
|
||||
| what | 1k lines | 10k lines |
|
||||
|---|---|---|
|
||||
| `vlog_semantic::analyze` (tree already parsed) | 252 µs | 3.76 ms |
|
||||
| `Document::new` — lex + parse + analyze + `resolve_external` | 2.54 ms | 31.1 ms |
|
||||
| `hover`, target declared in the same open buffer | 2.68 µs | 1.10 µs |
|
||||
| `hover`, target in a **closed** file (disk path) | 38.1 µs | 159 µs |
|
||||
| — of which one read + one `LineIndex` of that file | 27.4 µs | 140 µs |
|
||||
| `WorkspaceIndex::update_file`, 20 files of this size | 2.76 ms | 32.1 ms |
|
||||
| — of which the clone the measurement needs to repeat itself | 60 µs | 567 µs |
|
||||
| one name looked up among the file's symbols: **linear scan** | 767 ns | 8.14 µs |
|
||||
| one name looked up among the file's symbols: **name-sorted lookup** | 93 ns | 131 ns |
|
||||
| one token found at the cursor: **sweep** | 6.58 µs | 77.5 µs |
|
||||
| one token found at the cursor: **binary search** | 15 ns | 20 ns |
|
||||
| the balanced-paren window `completion.rs` needs: **sweep** | 8.63 µs | 130 µs |
|
||||
| the balanced-paren window `completion.rs` needs: **binary search** | 27 ns | 36 ns |
|
||||
|
||||
Every figure above comes from one run of the command in *Reproducing*, on the
|
||||
machine above. A local hover is a handful of pointer chases and comes out
|
||||
under 3 µs at both sizes; the 1k figure being the larger of the two is that
|
||||
measurement's noise floor, not a result.
|
||||
|
||||
Three things stand out:
|
||||
|
||||
- **A hover into a closed file is a file read.** 27 µs of the 1k hover's
|
||||
38 µs, and 140 µs of the 10k hover's 159 µs, is reading that file and
|
||||
building a `LineIndex` over it. Everything else — resolution, guards,
|
||||
rendering — is single-digit microseconds.
|
||||
- **`Document::new` is where a keystroke's cost lives**, and it is dominated
|
||||
by lexing and parsing, not by `analyze` (31 ms against 3.8 ms at 10k
|
||||
lines). The stage-by-stage table below says exactly how much.
|
||||
- **A sweep of the token vector costs about what the parse of one line
|
||||
costs**, and there are several per keystroke. That is round 2's Phase 2.
|
||||
|
||||
### One flush, stage by stage
|
||||
|
||||
`Document::new` runs the first seven of these in order; the eighth is not
|
||||
inside it at all — `diagnostics::all` is what a *publish* runs, on every
|
||||
flush, and round 1's table did not account for it.
|
||||
|
||||
`parse_tolerant` consumes its token vector, so each run of the parse needs a
|
||||
fresh clone. The clone has its own row and the parse row still contains it;
|
||||
subtracting one from the other is the honest reading, and it is what
|
||||
`Document::new` really pays.
|
||||
|
||||
| stage of one flush | 1k lines (9 461 tokens) | 10k lines (94 961 tokens) |
|
||||
|---|---|---|
|
||||
| `tokenize` | 1.14 ms | 12.5 ms |
|
||||
| `tokens.clone()` (the copy `Document` keeps) | 230 µs | 2.40 ms |
|
||||
| `parse_tolerant`, clone included | 1.16 ms | 14.3 ms |
|
||||
| — the parse alone, by subtraction | 0.93 ms | 11.9 ms |
|
||||
| `collect_defines` | 7.09 µs | 121 µs |
|
||||
| `analyze` | 278 µs | 5.55 ms |
|
||||
| `resolve_external` | 943 ns | 49.3 µs |
|
||||
| `LineIndex::new` | 10.5 µs | 115 µs |
|
||||
| `diagnostics::all` (parse errors + closers + lint) | 104 µs | 1.40 ms |
|
||||
|
||||
Read this table as *shares of a flush*, not as the last word on any one
|
||||
stage: it runs eight measurements back to back on one heap, and its `analyze`
|
||||
row came out 5.55 ms in the same run where the dedicated `analyze` test —
|
||||
which measures nothing else — came out 3.76 ms. The dedicated figure is the
|
||||
cleaner one. What the table is for is the proportion, and the proportion is
|
||||
unambiguous:
|
||||
|
||||
- **Lexing and parsing are 79 % of a flush** at 10 000 lines (12.5 + 11.9 of
|
||||
30.9 ms, taking the dedicated `analyze` figure for the rest). Everything
|
||||
else together is a fifth.
|
||||
- **`tokens.clone()` is 7.7 %**, and it is load-bearing rather than waste:
|
||||
`parse_tolerant` takes ownership of its tokens and *steals the comments out
|
||||
of them*, so the copy `Document` keeps is the only one that still has its
|
||||
trivia. It is also already the cheap option — before the one-lex change
|
||||
this was a second `tokenize`, which is 12.5 ms.
|
||||
- **`resolve_external` is 49 µs, one part in six hundred.** Making the
|
||||
workspace overlay skippable was on this round's list of candidates; the
|
||||
measurement says there is nothing there to save.
|
||||
- **The lint pass is 1.40 ms on top of the flush**, about 4 %. It walks the
|
||||
tree once per rule.
|
||||
|
||||
### Over the wire — what a keystroke actually costs a user
|
||||
|
||||
Round 1 listed this as its own open TODO, because it cannot be taken from
|
||||
inside the crate: the number includes two pipes, a JSON encoder and decoder,
|
||||
the change debounce's quiet-period timer and a whole flush. It is measured by
|
||||
spawning the shipped binary and speaking framed JSON-RPC at it
|
||||
(`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`, command above).
|
||||
|
||||
| `didChange` → `publishDiagnostics` | 1k lines | 10k lines |
|
||||
|---|---|---|
|
||||
| one keystroke, nothing following it | 164 ms | 202 ms |
|
||||
| a burst of ten keystrokes, no pause | 165 ms | 207 ms |
|
||||
| — publishes that burst produced | **1** | **1** |
|
||||
| one keystroke **a request follows** (mean of 10) | 4.35 ms | 37.6 ms |
|
||||
|
||||
The three rows say three different things.
|
||||
|
||||
- **The debounce is the felt latency when a client asks for nothing.**
|
||||
150 ms of the 164 ms is `CHANGE_DEBOUNCE`'s quiet period; the work is the
|
||||
rest. At 10 000 lines the same 150 ms sits on top of a 31 ms flush. This
|
||||
is the one row where round 1 made something *slower*: before the debounce
|
||||
a lone keystroke published in about one flush, and it now waits out the
|
||||
timer first. It is the bargain debouncing is, and the last row is why it
|
||||
is worth taking.
|
||||
- **A real editor never waits for that timer.** VS Code asks for semantic
|
||||
tokens, inlay hints and highlights the moment a buffer changes, and a
|
||||
request flushes the dirty buffer before it is answered. That is the last
|
||||
row, and it is the number a user actually feels: **4.35 ms at 1 000 lines,
|
||||
37.6 ms at 10 000**.
|
||||
- The first two rows are single round trips, not means, and each is bounded
|
||||
below by a 150 ms timer; treat their differences as noise. The last row is
|
||||
the mean of ten and is the one worth comparing across rounds.
|
||||
|
||||
## Before / after — round 1 (2026-08-28)
|
||||
|
||||
**A1 — didChange debounce.** Not measured directly *at the time*, and the
|
||||
arithmetic below is what round 1 recorded: every `didChange` used to run one
|
||||
`Document::new` plus lint and publish; a burst of *k* changes now runs one.
|
||||
At 10k lines that is 31 ms saved per keystroke after the first in a burst, at
|
||||
1k lines 2.6 ms. What the debounce cannot save is the first change in a burst
|
||||
and the last flush, so the floor is one `Document::new` per burst per buffer.
|
||||
|
||||
**Round 2 measured it.** A burst of ten keystrokes over the wire produces
|
||||
**one** `publishDiagnostics`, counted rather than reasoned about — the count
|
||||
comes from draining the session at `shutdown`, which every pending flush is
|
||||
guaranteed to have arrived before. The arithmetic above was right.
|
||||
|
||||
The burst is deliberately the **last** thing that measurement does, which is
|
||||
QA finding IL-1 closed: every `wait_for` in the test accepts *any* publish,
|
||||
so while the burst ran before the other rows, a second publish it had
|
||||
produced would have been absorbed by the next row's wait and never counted.
|
||||
With nothing between the burst and the drain, the count is the count.
|
||||
|
||||
**A2 — one disk read per hover.** Measured, two ways.
|
||||
|
||||
- The QA round that filed the finding measured a hover into a 31.7 MB closed
|
||||
file at **34 ms** (`docs/features/hover-declarations/README.md`, finding 4,
|
||||
2026-08-27, same machine, same test, release build). The same test after
|
||||
the `disk_view` memo: **16.3 ms**. That is the expected shape — two reads
|
||||
and two `LineIndex` builds became one — but the two numbers come from
|
||||
different runs on different days, so read it as "about half", not as
|
||||
2.08×.
|
||||
- The `perf::hovering_across_files_into_a_closed_file` measurement takes the
|
||||
after-number and the cost of one read + `LineIndex` side by side, in the
|
||||
same run: 142 µs of a 160 µs hover at 10k lines. Removing a second read of
|
||||
that same file is therefore removing roughly the whole remaining cost of
|
||||
the request, which is the before/after in the form that does not depend on
|
||||
an old number.
|
||||
|
||||
**A3 — name-keyed symbol lookup.** Measured directly, on the lookup alone:
|
||||
8.41 µs → 133 ns at 10k lines (5 001 symbols), 763 ns → 106 ns at 1k. The
|
||||
lookup is only part of what was saved: in `hover::live_symbol` every symbol
|
||||
the scan used to reach was also an `indexed_def_for_symbol` call — two index
|
||||
lookups apiece — which the name-sorted lookup never makes. That larger saving
|
||||
is **not measured here**; the 8.41 µs → 133 ns figure is a floor on it, not
|
||||
the whole of it.
|
||||
|
||||
**B — port detail spans, and comment attachment.** Not measured. The work
|
||||
added is a second `fenced_sections` call over lines already in memory, and
|
||||
two integers per declaration in the index and its facts records. No
|
||||
measurement was taken and none is claimed.
|
||||
|
||||
## Before / after — round 2 (2026-08-28)
|
||||
|
||||
**C1 — six token lookups stopped sweeping the buffer.** Measured directly,
|
||||
both halves in the same run against the same token stream
|
||||
(`perf::finding_one_token_against_sweeping_the_stream`), with the cursor
|
||||
three quarters of the way down the file — a sweep costs the distance from
|
||||
token zero, so measuring at either end would flatter it.
|
||||
|
||||
| | 1k lines | 10k lines |
|
||||
|---|---|---|
|
||||
| the token at the cursor: sweep → binary search | 6.58 µs → 15 ns | 77.5 µs → 20 ns |
|
||||
| `balanced`'s window: sweep → binary search | 8.63 µs → 27 ns | 130 µs → 36 ns |
|
||||
|
||||
Six call sites across `selection.rs`, `on_type.rs`, `completion.rs` and
|
||||
`inline.rs`; which ones, what each of them wanted, and the per-site argument
|
||||
that the search returns exactly what the sweep returned are in
|
||||
`docs/features/interactive-latency/README.md`. Every one is pinned by a test
|
||||
that walks **every byte** of a buffer full of touching tokens and compares
|
||||
the two. None of them changed an answer, and the tests are what says so
|
||||
rather than the claim.
|
||||
|
||||
Three sweeps were left alone with the reason written down: `signature.rs`'s
|
||||
two paren-depth walks (a depth is a function of every bracket before the
|
||||
cursor), `pairs.rs::analyze` (not a position query at all), and
|
||||
`completion.rs`'s comment gate (comments are trivia attached to whichever
|
||||
token happens to be next, so no search of the stream answers "is this byte
|
||||
inside a comment"). That last one is the remaining per-keystroke
|
||||
whole-buffer walk on the completion path.
|
||||
|
||||
**C2 — the round trip, and nothing else changed.** No stage of a flush was
|
||||
touched this round, so the flush table above is a baseline rather than an
|
||||
after. The reasons each candidate was refused, with its number, are in the
|
||||
next section.
|
||||
|
||||
## What it would take to go faster
|
||||
|
||||
Ranked by what the measurements above say is there, with what each would
|
||||
cost. None of these were attempted; each is a future round.
|
||||
|
||||
1. **Incremental lexing and parsing — 24.5 ms of a 31 ms flush at 10 000
|
||||
lines (79 %).** This is the only large lever left. It is also the one
|
||||
change that runs straight into `CLAUDE.md`'s hard invariants 1 and 2: the
|
||||
parser is what the "never corrupt code" and idempotency guarantees rest
|
||||
on, and an incremental parser that is right on 99 % of edits is worse than
|
||||
none. The change debounce already removed most of the *repetition* per
|
||||
keystroke, which is why this was not attempted here. The number that would
|
||||
justify it: **37.6 ms**, the felt latency of one keystroke in a
|
||||
10 000-line buffer, of which roughly 30 ms is lex + parse.
|
||||
2. **A cheaply-clonable `Token` — 2.40 ms, 7.7 % of a flush.**
|
||||
`Document.tokens` must be a separate copy because `parse_tolerant` takes
|
||||
ownership and steals `leading`/`trailing` out of the tokens it parses; the
|
||||
copy is 94 961 `String` allocations. Interning the text, or an `Rc<str>`,
|
||||
would remove most of it — but `Token` is `vlog_parser`'s public type and
|
||||
the formatter reads it everywhere, so this is a cross-crate change for
|
||||
under 8 %.
|
||||
3. **One tree walk for the whole lint pass — 1.40 ms, about 4 % on top of a
|
||||
flush.** `vlog_linter::lint` is `for rule in enabled { rule.check(ctx) }`,
|
||||
one walk per rule, and the same engine serves `lucisv check`. Fusing them
|
||||
is a `vlog_linter` refactor, and the editor and CI must not disagree about
|
||||
what a violation is.
|
||||
4. **`completion.rs`'s comment gate**, the last whole-buffer walk on a
|
||||
per-keystroke request path. Not measured on its own; it is one pass over
|
||||
the token vector plus its trivia, so the sweep figures above (77.5 µs at
|
||||
10 000 lines) are the right order of magnitude for it. Doing it properly
|
||||
means giving the lexer a way to answer "which comment covers this byte",
|
||||
which is a `vlog_parser` question and not a `completion.rs` one.
|
||||
5. **`CHANGE_DEBOUNCE` itself** is not a code problem: 150 ms of a lone
|
||||
keystroke's 164 ms round trip is the timer. It only bites clients that ask
|
||||
for nothing after a change, and it was set deliberately. Now that it is
|
||||
measured, a future round has the number to argue about.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/lucisv_server/src/perf.rs` — eight `#[ignore]`d measurements,
|
||||
std only, each with the command to run it.
|
||||
- [x] `analyze`, `Document::new`, hover (local + closed cross-file),
|
||||
`WorkspaceIndex::update_file`, at 1k and 10k lines.
|
||||
- [x] Before/after where it was cheap: A2 (two ways), A3 and C1.
|
||||
- [x] Machine, command and date recorded above.
|
||||
- [x] **Round 1's first open TODO, resolved (round 2, 2026-08-28):**
|
||||
end-to-end request latency over the wire, measured against the shipped
|
||||
binary — a single `didChange`, a burst of ten (with the publish count
|
||||
that turns A1's arithmetic into a measurement), and the
|
||||
change-then-request shape a real editor produces.
|
||||
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`.
|
||||
- [x] **Added in round 2:** one flush stage by stage, including the
|
||||
`diagnostics::all` pass that runs on every publish and that round 1's
|
||||
table did not account for.
|
||||
`perf::breaking_down_one_flushed_keystroke`.
|
||||
- [ ] **Round 1's second open TODO, restated and still open:** memory.
|
||||
Nothing in the repo measures resident size. Round 2 added no data
|
||||
structure — two free functions and no state — so the figure it would
|
||||
report has not moved, and round 1's name index is still four bytes per
|
||||
symbol. Worth doing before anything interns tokens, which is item 2 of
|
||||
*What it would take to go faster* and is a memory trade as much as a
|
||||
time one.
|
||||
- [ ] Not measured: the per-request handlers themselves (hover aside).
|
||||
Completion, signature help and semantic tokens each have a
|
||||
whole-buffer pass somewhere; only their token lookups were measured
|
||||
this round, not the requests end to end.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev.** Wrote `perf.rs` and took the numbers above (part A4 of
|
||||
the LSP performance round). Chose one module of six tests over a test per
|
||||
crate so that a single command produces the whole table. The generated-module
|
||||
generator lives beside the tests rather than in a shared helper — it has one
|
||||
user.
|
||||
|
||||
Renamed `hover.rs`'s QA measurement
|
||||
`hovering_into_a_large_closed_file_reads_it_twice` →
|
||||
`..._reads_it_once`, since the doubled read it was named for is what A2
|
||||
removed. The QA log in `docs/features/hover-declarations/README.md` still
|
||||
names the old spelling; that section belongs to QA and was left alone.
|
||||
|
||||
**2026-08-28 — dev (QA fixes).** No number above moved, and none was
|
||||
re-measured, because nothing on a measured path changed shape:
|
||||
|
||||
- The hover fixes (PDS-1, PDS-2, PDS-4) are all inside `attached_lines`,
|
||||
which part **B** already records as unmeasured. The added work is a
|
||||
`strip_suffix` per composed line and a below-comment walk that now also
|
||||
runs when a comment sits above — a handful of `line_range` lookups against
|
||||
the 142 µs *file read* that dominates the "hover closed" figure.
|
||||
- CD-1 only *removes* work (a closing buffer's `Document::new` and publish),
|
||||
and the debounce's own A1 numbers are arithmetic over `Document::new`,
|
||||
which is untouched.
|
||||
- PDS-3 widens one `bind_port_decl` branch from ports to task/function
|
||||
arguments: one hash lookup per declarator of a body port declaration
|
||||
inside a task or function. `perf.rs`'s generated modules contain no
|
||||
tasks, so the `analyze` / `Document::new` / `update_file` figures cannot
|
||||
have moved at all.
|
||||
|
||||
**2026-08-28 — dev (round 2).** Added
|
||||
`perf::breaking_down_one_flushed_keystroke`,
|
||||
`perf::finding_one_token_against_sweeping_the_stream` and
|
||||
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`, and **re-measured every
|
||||
figure in this document** on the same machine from the commands written
|
||||
beside them — the tables above are one run of each, not a mix of runs across
|
||||
days. The old figures are gone rather than kept alongside; every pair was
|
||||
within the noise this document already budgets for, and carrying two columns
|
||||
of the same measurement would invite reading a difference into scheduling.
|
||||
Round 1's figures are not lost — the QA log below quotes all of them in its
|
||||
own table, dated, and that section belongs to QA and was left alone.
|
||||
|
||||
The round's changes are in `docs/features/interactive-latency/README.md`.
|
||||
Only C1 touched shipped code, and it touched no stage of a flush, so the
|
||||
flush table is a baseline for the next round rather than an after.
|
||||
|
||||
Two things are recorded here that a future round should not have to
|
||||
rediscover. First, the e2e measurement reuses `e2e.rs`'s existing `Live`
|
||||
session helper; the only shared code that changed is that `Live::finish` now
|
||||
returns the publish count it saw on the way out, which is what makes the
|
||||
debounce's coalescing countable. Second, `perf::generated_module` now has a
|
||||
copy in `tests/e2e.rs` — a binary crate's modules are not reachable from an
|
||||
integration test — and the two must stay the same shape or the in-crate table
|
||||
and the over-the-wire table stop being readable against one another.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** No findings — every number reproduces within reason.
|
||||
|
||||
- **Machine match confirmed.** `sysctl -n machdep.cpu.brand_string` →
|
||||
`Apple M1 Max`; `sw_vers` → macOS 27.0, build `26A5421a` — exactly the
|
||||
machine named in the README's own table, on the same checkout.
|
||||
- **Re-ran the exact reproduce command**, `cargo test --release -p
|
||||
lucisv_server perf:: -- --ignored --nocapture --test-threads=1`, and
|
||||
compared every figure against the table:
|
||||
|
||||
| what | table | re-measured |
|
||||
|---|---|---|
|
||||
| `analyze`, 1k / 10k | 274 µs / 3.79 ms | 287.6 µs / 3.806 ms |
|
||||
| `Document::new`, 1k / 10k | 2.60 ms / 31.1 ms | 2.600 ms / 31.72 ms |
|
||||
| hover local, 1k / 10k | 1.79 µs / 0.97 µs | 3.35 µs / 1.01 µs |
|
||||
| hover closed, 1k / 10k | 35.2 µs / 160 µs | 34.4 µs / 172 µs |
|
||||
| — one read of it, 1k / 10k | 26.9 µs / 142 µs | 26.7 µs / 147.6 µs |
|
||||
| `update_file`, 1k / 10k | 2.73 ms / 31.4 ms | 2.695 ms / 32.45 ms |
|
||||
| — the clone, 1k / 10k | 60 µs / 528 µs | 60.7 µs / 516.7 µs |
|
||||
| linear scan, 1k / 10k | 763 ns / 8.41 µs | 793 ns / 8.21 µs |
|
||||
| name-sorted, 1k / 10k | 106 ns / 133 ns | 93 ns / 134 ns |
|
||||
|
||||
Every pair is within the noise the README itself budgets for — including
|
||||
the hover-local 1k figure, which the README already calls out by name as
|
||||
"that measurement's noise floor, not a result" (mine is higher still,
|
||||
3.35 µs vs. 1.79 µs, and still a handful of pointer chases either way).
|
||||
Nothing here is scaled, remembered, or overclaimed.
|
||||
- **Re-ran the older, separately-commanded measurement** too: `cargo test
|
||||
--release -p lucisv_server large_closed -- --ignored --nocapture
|
||||
--test-threads=1` → **17.0 ms** against the documented "34 ms → 16.3 ms."
|
||||
Matches the README's own honesty caveat exactly ("read it as 'about half',
|
||||
not as 2.08×" — different runs, different days).
|
||||
- **`perf.rs` measures what its name says** — spot-checked
|
||||
`hovering_across_files_into_a_closed_file` and
|
||||
`looking_up_one_name_against_scanning_every_symbol` against `hover.rs`'s
|
||||
and `lib.rs`'s actual entry points (`hover::hover`, `Semantics::
|
||||
symbols_named` vs. a hand-rolled linear scan over `symbols()`) — both call
|
||||
the real, shipped functions, not a stand-in.
|
||||
- **A1's "before/after" is correctly labeled "not measured directly"** — it
|
||||
is arithmetic over the already-verified `Document::new` figures, and the
|
||||
README says so; no separate claim to check.
|
||||
- **B's "not measured, none is claimed"** — confirmed true: no perf test
|
||||
exercises `fenced_sections`/`attached_lines`, and the README does not say
|
||||
one does.
|
||||
|
||||
**2026-08-28 — QA (round 2).** Findings and the full gate output are recorded
|
||||
in `docs/features/interactive-latency/README.md`'s QA log, which is this
|
||||
round's owning feature; summarized here since this document is where the
|
||||
numbers live.
|
||||
|
||||
- Every figure in *Over the wire* and *One flush, stage by stage* reproduced
|
||||
within the noise this document budgets for, from a fresh
|
||||
`cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1`
|
||||
and `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
|
||||
on this session's run of this machine.
|
||||
- **C1's identity claim** (six sweeps → binary searches, none changed an
|
||||
answer) held under a hand-traced check of all six call sites, including
|
||||
the empty-token and large-file-fast-path edges, and under an independent
|
||||
check of the `state.rs` monotonicity precondition against `vlog_parser`'s
|
||||
own much wider corpus/fuzz tests (`tests/spans.rs`, `tests/error_recovery.rs`)
|
||||
— no gap found.
|
||||
- **One methodology finding, IL-1 (medium)**, on the e2e round trip's burst
|
||||
measurement: the "1 publish(es)" figure for a burst of ten is not the
|
||||
order-independent count its own doc comment claims — a stray extra publish
|
||||
in the window between the burst and `Live::finish`'s drain could be
|
||||
silently absorbed by an unrelated `wait_for` later in the same test and
|
||||
never counted. Full detail and repro in
|
||||
`docs/features/interactive-latency/README.md`. Not a claim about a real
|
||||
double-publish (the debounce is understood to coalesce to one), and not
|
||||
fixed — closing it is a test-restructuring decision for the dev.
|
||||
- The two `generated_module` copies (this crate's `perf.rs` and `e2e.rs`'s)
|
||||
differ by one trivia line, not the byte-identical shape their own comment
|
||||
implies; verified harmless (comments are not tokens, and the tables stay
|
||||
readable against each other). Detail in the same QA log.
|
||||
- **Verdict: SHIP WITH FIXES noted, none applied.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted as the round's record.
|
||||
|
||||
The discipline here is what makes the numbers usable later: one command, one
|
||||
machine block, means rather than single runs, `--test-threads=1` justified by
|
||||
a contaminated first attempt that reported a cross-file hover as cheaper than
|
||||
the file read it performs. Refusing criterion was the right call against
|
||||
`CLAUDE.md`'s dependency rule, and the `#[ignore]`d-measurement pattern was
|
||||
already this repo's idiom rather than an invention for this round.
|
||||
|
||||
I re-ran every measurement independently and the figures reproduce. Two
|
||||
claims were softened at review rather than left as written: the wire-latency
|
||||
rows are re-measured after the IL-1 methodology fix (164/202 ms lone,
|
||||
4.35/37.6 ms with a request following), and the lone-keystroke row now says
|
||||
plainly that round 1 made that case *slower* — 150 ms of it is the debounce
|
||||
timer, and a client that asks for nothing after a change waits it out. A perf
|
||||
document that only records wins is not a perf document.
|
||||
|
||||
What I want the next round to inherit: the felt-latency number is **37.6 ms**
|
||||
for one keystroke in a 10 000-line buffer, roughly 30 ms of it lex and parse.
|
||||
That is the figure any incremental-parsing proposal has to be argued against,
|
||||
and it now exists.
|
||||
|
||||
@@ -5,6 +5,35 @@ for you. The extension and its bundled language server share one version
|
||||
number; the full engineering notes live in the
|
||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||
|
||||
## 0.13.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.13.0**. Its platform packages include both
|
||||
`lucisv-server` and the `lucisv` command-line tool:
|
||||
|
||||
| Package target | Machines |
|
||||
@@ -320,6 +320,26 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## 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.13.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