From 61f345aca716a2dc26c61a9e5bc52c3a350bdbae Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Fri, 28 Aug 2026 23:58:22 -0700 Subject: [PATCH] Performance wave Lane B: completion hot path, highlight fix, scope default Completion stops parsing whole declaring files per keystroke: tier 0 slices the module header at its terminating ';' via a whitelist walk over a bounded lex window, anchored on the index span and re-planning whole-file on anything unrecognized (non-ANSI included); the module table replaces a per-keystroke workspace_symbols(""). 53 -> 3.2 ms at the empty prefix (opentitan wire 63-66 -> 13-15 ms; typing an 11-char word 201 -> 64 ms), items pinned byte-identical. documentHighlight answered 0 on any name the file uses but does not declare (both cursor questions were single-file); nav gains external_occurrences over the overlay, grouping by the whole defs() slice, written failing-first and pinned at the two opentitan positions over the wire. lucisv.index.scopeDepth default 0 -> 2 (behavior change; CHANGELOG at release): a dv/tb file now indexes its IP block (21 files / 15 ms) instead of one file with every cross-file answer empty. Rootless sessions no longer climb (latent unnamed-tree walk removed). Dev Opus + QA Sonnet in a dedicated worktree; QA SHIP with one LOW (pre-existing attribute-instance indexing gap, pinned) and one recorded asymmetry. Lead-reviewed. Co-Authored-By: Claude Fable 5 --- TODO.md | 26 +- crates/lucisv_server/src/candidates.rs | 102 +++++- crates/lucisv_server/src/completion.rs | 449 +++++++++++++++++++++++- crates/lucisv_server/src/nav.rs | 221 +++++++++++- crates/lucisv_server/src/perf.rs | 294 ++++++++++++++++ crates/lucisv_server/src/server.rs | 22 +- crates/lucisv_server/src/settings.rs | 82 ++++- crates/lucisv_server/src/state.rs | 117 ++++-- crates/lucisv_server/tests/e2e.rs | 158 ++++++++- docs/features/completion-core/README.md | 249 ++++++++++++- docs/features/index-scope/README.md | 253 +++++++++++-- docs/features/references-nav/README.md | 168 +++++++++ docs/perf/README.md | 167 ++++++++- editors/vscode/package.json | 4 +- 14 files changed, 2199 insertions(+), 113 deletions(-) diff --git a/TODO.md b/TODO.md index 1d2a84d..e5ce671 100644 --- a/TODO.md +++ b/TODO.md @@ -1161,15 +1161,33 @@ settings.rs,perf.rs}, crates/lucisv_server/tests/e2e.rs, editors/vscode/package.json, docs/features/{completion-core, references-nav,index-scope}/README.md, docs/perf/README.md) -- [ ] `completion` 34–66 ms per keystroke (worst at 0–4 chars) → +- [x] `completion` 34–66 ms per keystroke (worst at 0–4 chars) → profile, then < 5 ms with item-identical answers pinned. -- [ ] `documentHighlight` answered 0 results at every opentitan + Profiled: the whole cost was tier 0, the module skeletons — every + other tier is 0.19 ms at every prefix. Tier 0 now parses the + declaring file's *header* instead of all of it, and reads the + module names off a table built with the index instead of sorting + the workspace's whole symbol table per keystroke. **3.17 ms** at + the empty prefix on a 4 000-file generated corpus (was 53.2 ms); + **13–15 ms** worst case on opentitan (was 34–66), and typing + `aes_reg_top` 201 ms → 64.5 ms. Items pinned identical by a + fifteen-shape plan-equality test and a module-table equality test. +- [x] `documentHighlight` answered 0 results at every opentitan position while references answered — root-cause and fix (or prove the benchmark request wrong and correct performance.md). -- [ ] Default `lucisv.index.scopeDepth` 0 → 2 (folder scope indexed + **A real bug, not a benchmark mistake**: the handler asked only + single-file `Semantics`, so a name this file uses but does not + declare — an instantiated module, a `.port` connection — had no + symbol to find, while `references` read the workspace overlay. + Fixed in `nav::external_occurrences`, with a unit regression test + and the two opentitan positions pinned over the wire. +- [x] Default `lucisv.index.scopeDepth` 0 → 2 (folder scope indexed exactly one file in opentitan's dv/tb layout; every cross-file answer empty until a jump widens) — behavior change, CHANGELOG - callout at release. + callout at release. Also removed the *rootless* climb, which had + no root to clamp against and would have walked an unnamed tree at + the new default. Cost measured rung by rung: 1 / 1 / 21 / 252 + files at depths 0 / 1 / 2 / 3. ### Deferred, filed diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index decc60f..2faf5d1 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -53,6 +53,15 @@ pub struct Macro { #[derive(Debug, Default)] pub struct Candidates { units: Vec, + /// Every module name the index declares, in the order + /// `WorkspaceIndex::workspace_symbols` puts them in. + /// + /// Its own table beside [`Candidates::units`] because tier 0 of a + /// completion asks a different question of it: a *substring* match, not a + /// prefix one, so it cannot ride the binary search the others do. What it + /// buys is that the whole symbol table is no longer built and sorted per + /// keystroke — see `docs/features/completion-core/README.md`, 2026-08-28. + modules: Vec, macros: Vec, words: Vec, /// How many in-scope files contain each word. What makes it possible to @@ -83,11 +92,9 @@ impl Candidates { sources: &[(PathBuf, String)], mut known: HashMap>, ) -> Candidates { - let mut out = Candidates { - units: units_of(index), - macros: macros_of(index), - ..Candidates::default() - }; + let (units, modules) = index_tables(index); + let mut out = + Candidates { units, modules, macros: macros_of(index), ..Candidates::default() }; for (path, text) in sources { let words = match known.remove(path) { Some(words) => words, @@ -121,7 +128,7 @@ impl Candidates { /// [`Candidates::update_file`] for a file whose words the caller already /// has — an open buffer's, read off the tokens it was analyzed from. pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec) { - self.units = units_of(index); + (self.units, self.modules) = index_tables(index); self.macros = macros_of(index); self.set_words(path, words); } @@ -137,13 +144,13 @@ impl Candidates { for (path, words) in batch { self.set_words(&path, words); } - self.units = units_of(index); + (self.units, self.modules) = index_tables(index); self.macros = macros_of(index); } /// Drop one file's contribution entirely. pub fn remove_file(&mut self, index: &WorkspaceIndex, path: &Path) { - self.units = units_of(index); + (self.units, self.modules) = index_tables(index); self.macros = macros_of(index); self.set_words(path, Vec::new()); } @@ -178,6 +185,18 @@ impl Candidates { matching(&self.units, prefix, |c| &c.name) } + /// Module names *containing* `query`, case-insensitively — what + /// `vlog_refactor::module_names` answers, off a table instead of off the + /// index. A substring match, so it is a scan; the table it scans holds one + /// entry per module rather than one per declaration in the workspace. + pub fn modules(&self, query: &str) -> Vec<&str> { + self.modules + .iter() + .filter(|name| contains_ignore_case(name, query)) + .map(String::as_str) + .collect() + } + /// `` `define`` names starting with `prefix`, case-insensitively. pub fn macros(&self, prefix: &str) -> &[Macro] { matching(&self.macros, prefix, |m| &m.name) @@ -189,12 +208,26 @@ impl Candidates { } } -/// Every name the index carries, as a lookup table. -fn units_of(index: &WorkspaceIndex) -> Vec { - // The empty query means "everything"; it is paid once per index build - // rather than once per keystroke, which is the whole point of this table. - let mut out: Vec = index - .workspace_symbols("") +/// Every name the index carries, and the module names among them, from one +/// pass over its symbol table. +/// +/// One pass because that pass is the expensive part: `workspace_symbols("")` +/// builds and sorts a record per declaration in the workspace, and the two +/// tables want the same records. It is paid once per index build rather than +/// once per keystroke, which is the whole point of both. +fn index_tables(index: &WorkspaceIndex) -> (Vec, Vec) { + let symbols = index.workspace_symbols(""); + // `workspace_symbols` sorts by name first, so same-named declarations are + // already adjacent and a plain `dedup` leaves one entry per module name — + // which is exactly what `vlog_refactor::module_names` does to the same + // list, minus the per-keystroke rebuild. + let mut modules: Vec = symbols + .iter() + .filter(|symbol| symbol.container.is_none() && symbol.def.kind == SymbolKind::Module) + .map(|symbol| symbol.name.to_string()) + .collect(); + modules.dedup(); + let mut out: Vec = symbols .into_iter() .map(|symbol| { let detail = match symbol.container { @@ -212,7 +245,7 @@ fn units_of(index: &WorkspaceIndex) -> Vec { sort_by_name(&mut out, |c| c.name.as_str()); // A name two files declare is one completion item, not two. out.dedup_by(|a, b| a.name == b.name && a.kind == b.kind); - out + (out, modules) } /// Every `` `define`` the workspace declares. `` `undef`` entries are skipped: @@ -322,6 +355,17 @@ fn lower_cmp(a: &str, b: &str) -> Ordering { a.bytes().map(|c| c.to_ascii_lowercase()).cmp(b.bytes().map(|c| c.to_ascii_lowercase())) } +/// Whether `word` holds `query` anywhere in it, ignoring ASCII case — the +/// match `WorkspaceIndex::workspace_symbols` makes, which +/// [`Candidates::modules`] has to make the same way to answer the same set. +fn contains_ignore_case(word: &str, query: &str) -> bool { + if query.is_empty() { + return true; + } + let query = query.as_bytes(); + word.as_bytes().windows(query.len()).any(|window| window.eq_ignore_ascii_case(query)) +} + /// Whether `word` starts with `prefix`, ignoring ASCII case. pub fn starts_with_ignore_case(word: &str, prefix: &str) -> bool { word.len() >= prefix.len() @@ -446,6 +490,34 @@ mod tests { assert!(!names.contains(&"never_seen"), "{names:?}"); } + /// The module table exists to answer what `vlog_refactor::module_names` + /// answers without the index rebuilding its whole symbol table per + /// keystroke, so the two must agree — set *and* order — at every query. + /// A substring match, not a prefix one: `module_names` asks the index for + /// `contains`, and `prim_aes_sbox` is an answer to `aes`. + #[test] + fn the_module_table_answers_exactly_what_module_names_answers() { + let files = [ + ("/rtl/aes.sv", "module aes;\nendmodule\npackage aes_pkg;\nendpackage\n"), + ("/rtl/aes_reg_top.sv", "module aes_reg_top;\nendmodule\n"), + ("/rtl/prim.sv", "module prim_aes_sbox;\nendmodule\nmodule PRIM_UPPER;\nendmodule\n"), + ("/rtl/other.sv", "interface i;\nendinterface\nclass c;\nendclass\n"), + // A module name two files declare — one entry, not two. + ("/rtl/twin_a.sv", "module twin;\nendmodule\n"), + ("/rtl/twin_b.sv", "module twin;\nendmodule\n"), + ]; + let srcs = sources(&files); + let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let candidates = Candidates::build(&index, &srcs, HashMap::new()); + for query in ["", "a", "ae", "aes", "AES", "prim", "PRIM", "_", "twin", "zzz", "aes_reg"] { + assert_eq!( + candidates.modules(query), + vlog_refactor::module_names(&index, query), + "query {query:?}" + ); + } + } + // ------------------------------------------------------------------ // QA (incremental-index, 2026-08-27): `word_files`'s exact bookkeeping // ------------------------------------------------------------------ diff --git a/crates/lucisv_server/src/completion.rs b/crates/lucisv_server/src/completion.rs index 207a2c0..1ad9efa 100644 --- a/crates/lucisv_server/src/completion.rs +++ b/crates/lucisv_server/src/completion.rs @@ -33,7 +33,7 @@ use lsp_types::{ use vlog_parser::token::{Comment, Token, TokenKind}; use vlog_parser::{TextRange, KEYWORDS}; use vlog_refactor::{InstantiationPlan, Layout, Site}; -use vlog_semantic::{Semantics, Symbol, SymbolKind}; +use vlog_semantic::{Semantics, Symbol, SymbolKind, WorkspaceIndex}; use crate::candidates::starts_with_ignore_case; use crate::pairs; @@ -59,6 +59,19 @@ const LIMIT: usize = 512; /// table built at index time. Unchanged from M4. const MODULE_LIMIT: usize = 64; +/// How far past a module's name [`module_header`] reads looking for the end of +/// its header, smallest first. +/// +/// A ladder rather than one bound because the lex is the whole cost of the +/// slice and it is linear in what it is handed, so every header would +/// otherwise pay for the widest one. The rungs come from measuring opentitan's +/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB, +/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB. +/// The top rung is well past that, because a rung that is too small is not a +/// wrong answer but a whole-file parse, and for those files that is 2–4 ms +/// against the 0.6 ms of lexing 16 KB. +const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024]; + /// `sortText` prefixes. The client sorts on these, so they *are* the tier /// order; the name follows so each tier is alphabetical within itself. const TIER_MODULE: char = '0'; @@ -211,7 +224,10 @@ fn module_tier( let layout = layout_at(ws, doc, word.start); let site = Site { semantics: &doc.semantics, offset: word.start }; - let names = vlog_refactor::module_names(ws.index(), &word.text); + // The same names `vlog_refactor::module_names` answers, off the table + // built with the index instead of off the index's whole symbol table — + // which the old call rebuilt and re-sorted on every keystroke. + let names = ws.candidates().modules(&word.text); if names.len() > MODULE_LIMIT { items.incomplete = true; } @@ -220,14 +236,145 @@ fn module_tier( // is silently skipped: a completion list is not the place to argue. let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue }; let Some(definition) = ws.text_of(path) else { continue }; - let Ok(plan) = vlog_refactor::instantiation_plan(name, &definition, Some(site)) else { - continue; - }; + let Ok(plan) = plan_for(ws.index(), name, &definition, site) else { continue }; let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string(); items.push(item(&plan, &layout, word.range(cursor), doc, &file, snippets)); } } +/// One module's instantiation plan, off its header alone where that is the +/// whole of what the plan reads, and off its whole file otherwise. +/// +/// The slice is an optimisation and never an answer of its own. Two things +/// send this back to the whole file, and both leave the answer exactly what it +/// was before the slice existed: +/// +/// * the slice does not plan at all — [`module_header`] cut a header this +/// parser does not read as one; +/// * the plan it produced has a port with neither a direction nor a type, +/// which is what a **non-ANSI** port list looks like once its body is gone: +/// `module m (a); input wire a;` writes the direction below the header, and +/// the body is the part the slice drops. +fn plan_for( + index: &WorkspaceIndex, + module: &str, + definition: &str, + site: Site<'_>, +) -> Result { + let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site)); + let Some(header) = module_header(index, module, definition) else { return whole() }; + match vlog_refactor::instantiation_plan(module, &header, Some(site)) { + Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan), + _ => whole(), + } +} + +/// The text one skeleton is planned from: the declaring file's header alone +/// where this function can find it, and the whole file where it cannot. +/// +/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed +/// the whole declaring file — three hundred lines of body to read a header a +/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads +/// nothing but the header, so nothing but the header needs to be parsed. +/// +/// The prefix is kept **byte for byte**: every span the plan reads is an offset +/// into the text it was parsed from, so cutting the front off would move them +/// all. Only the body is dropped, and an `endmodule` is written in its place so +/// the declaration is closed. +pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option { + let [def] = + index.units(module).iter().filter(|d| d.kind == SymbolKind::Module).collect::>()[..] + else { + return None; + }; + let name = def.name_span; + // The index's span is as of the last scan. A file edited on disk since + // then has moved it, and a slice taken at a stale offset would be a + // different module's header — so the name has to still be there. + if text.get(name.start as usize..name.end as usize) != Some(module) { + return None; + } + let from = name.end as usize; + for size in HEADER_WINDOWS { + // A window that cuts a block comment or a string in half does not lex, + // and one that cuts the port list in half runs out of tokens before + // the `;`. Both answer "not in this window" and are asked again at the + // next rung; both answer `None` at the last one. + let window = text.get(from..text.len().min(from + size))?; + if let Ok(tokens) = vlog_parser::tokenize(window) { + if let Some(end) = header_end(&tokens) { + let head = text.get(..from + end as usize)?; + return Some(format!("{head}\nendmodule\n")); + } + } + if from + size >= text.len() { + break; + } + } + None +} + +/// Where the header that begins just after a module's name ends: the offset +/// one past its terminating `;`, in the window's own coordinates. +/// +/// A **whitelist**, not a scan for the first `;`: `module aes import +/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the +/// header. Anything this does not recognise — a compiler directive between the +/// name and the port list, a header longer than the window — answers `None`, +/// and the caller parses the whole file rather than guessing. +fn header_end(tokens: &[Token]) -> Option { + let mut at = 0; + loop { + let token = tokens.get(at)?; + match token.text.as_str() { + ";" => return Some(token.span.end), + // A lifetime qualifier: `module automatic foo (...);`. + "static" | "automatic" => at += 1, + // A package import written into the header, whose own `;` is not + // the header's. + "import" => at = skip_to_semicolon(tokens, at + 1)?, + // The parameter list, the port list, and an attribute instance — + // each one parenthesised, each one skipped whole. + "#" | "(" => at = skip_parens(tokens, at)?, + _ => return None, + } + } +} + +/// Past the parenthesised group starting at `at`, which a `#` may introduce. +fn skip_parens(tokens: &[Token], mut at: usize) -> Option { + while tokens.get(at)?.text == "#" { + at += 1; + } + if tokens.get(at)?.text != "(" { + return None; + } + let mut depth = 0i32; + loop { + match tokens.get(at)?.text.as_str() { + "(" => depth += 1, + ")" if depth == 1 => return Some(at + 1), + ")" => depth -= 1, + _ => {} + } + at += 1; + } +} + +/// Past the next `;` written outside any parentheses. +fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option { + let mut depth = 0i32; + loop { + match tokens.get(at)?.text.as_str() { + "(" => depth += 1, + ")" => depth -= 1, + ";" if depth == 0 => return Some(at + 1), + _ => {} + } + at += 1; + } +} + /// Tier 1: everything the scope chain at the cursor binds. fn scope_tier(items: &mut Items, doc: &Document, word: &Word) { for symbol in visible_symbols(&doc.semantics, word.start) { @@ -1040,6 +1187,298 @@ endmodule items.iter().map(|item| item.label.as_str()).collect() } + // ------------------------------------------------------------------ + // tier 0's header slice (2026-08-28) — it must change no answer + // ------------------------------------------------------------------ + + /// Every header shape the slice has to survive, as (file text, module). + /// + /// The list is the argument that the slice changes nothing: each entry is + /// planned both ways below and the two plans are compared field by field. + const SHAPES: &[(&str, &str)] = &[ + // The ordinary ANSI header, params and all. + (SUB, "sub"), + // No ports at all. + ("module bare;\nendmodule\n", "bare"), + // An empty port list. + ("module empty ();\n logic x;\nendmodule\n", "empty"), + // A package import written into the header: its `;` is not the + // header's, and a slice that stopped there would report no ports. + ( + "package p;\n localparam int W = 4;\nendpackage\n\ + module imported import p::*; #(\n parameter int W = 8\n) (\n \ + input logic clk,\n output logic [W-1:0] q\n);\n \ + assign q = '0;\nendmodule\n", + "imported", + ), + // Two imports, then a parameter list. + ( + "package p;\nendpackage\npackage q;\nendpackage\n\ + module twice import p::*; import q::*; (input logic a);\nendmodule\n", + "twice", + ), + // A **non-ANSI** port list: the directions live in the body, which is + // exactly what the slice drops. + ( + "module old (a, b);\n input wire [7:0] a;\n output reg b;\n \ + always @* b = |a;\nendmodule\n", + "old", + ), + // Non-ANSI with nothing declaring the ports at all. + ("module silent (a, b);\nendmodule\n", "silent"), + // A comment and an attribute inside the header. + ( + "module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \ + input logic clk\n);\nendmodule\n", + "noisy", + ), + // A lifetime qualifier. + ("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"), + // A second module in the same file, after the one being planned. + ( + "module first (input logic a);\nendmodule\n\ + module second (output logic b);\nendmodule\n", + "first", + ), + // …and before it, so the slice's prefix carries a whole module. + ( + "module first (input logic a);\nendmodule\n\ + module second (output logic b);\nendmodule\n", + "second", + ), + // A compiler directive between the name and the port list, which the + // whitelist refuses outright. + ("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"), + // A directive *inside* the port list, which carries a warning the two + // plans must both raise. + ( + "module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\ + `endif\n);\nendmodule\n", + "ifdefd", + ), + // An escaped identifier for the module and for a port. + ("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"), + // A header longer than the first rung of the window ladder. + (WIDE, "wide"), + // QA (performance wave Lane B, 2026-08-28): a genuine attribute + // instance, `(* ... *)`, right after the module name and before the + // parameter list — the one shape the "noisy" case above is commented + // as covering but does not (it has two comments, no attribute). + // **Finding, not a regression this round introduced**: a module with + // an attribute anywhere near its header is not indexed as a `Module` + // unit at all (see + // `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`), + // so this pins the safe side effect — `module_header` declines before + // its whitelist walk ever runs — rather than the whitelist's own + // handling of attributes, which this shape cannot reach. + ( + "module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \ + input logic clk\n);\nendmodule\n", + "attributed", + ), + // An attribute instance *inside* the port list, attached to one port. + // Same finding as `attributed`: not indexed, so not reached either. + ( + "module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\ + );\nendmodule\n", + "port_attributed", + ), + // A single import declaration naming several packages, comma + // separated (`import a::*, b::*;`) — one statement, not two, and the + // whitelist's `skip_to_semicolon` must not stop at the first `::`. + ( + "package p;\nendpackage\npackage q;\nendpackage\n\ + module chained import p::*, q::*; (input logic a);\nendmodule\n", + "chained", + ), + // A parameter default whose string literal carries the exact bytes + // the whitelist watches for — `;` and `)` — which must stay inside + // the `String` token and never be mistaken for header punctuation. + ( + "module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \ + input logic clk\n);\nendmodule\n", + "stringy", + ), + // CRLF line endings through the whole header. + ("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"), + ]; + + /// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb. + const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \ + input logic port_number_one_with_a_long_name,\n \ + input logic port_number_two_with_a_long_name,\n \ + input logic port_number_three_with_a_long_name,\n \ + input logic port_number_four_with_a_long_name,\n \ + input logic port_number_five_with_a_long_name,\n \ + output logic port_number_six_with_a_long_name\n);\n \ + assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n"; + + /// The whole argument for the slice: for every shape above, the plan built + /// from the header alone is the plan built from the whole file. Where it + /// would not be — a non-ANSI list, a header the whitelist refuses — the + /// guard in [`plan_for`] sends the question back to the whole file, so the + /// comparison holds there too. + #[test] + fn the_header_slice_plans_exactly_what_the_whole_file_plans() { + for (text, module) in SHAPES { + let path = PathBuf::from("/rtl/shape.sv"); + let index = WorkspaceIndex::build(vec![(path.clone(), *text)]); + let (tree, _) = vlog_parser::parse_source_tolerant(text); + let semantics = vlog_semantic::analyze(&tree, text); + let site = Site { semantics: &semantics, offset: 0 }; + let whole = vlog_refactor::instantiation_plan(module, text, Some(site)); + let ours = plan_for(&index, module, text, site); + assert_eq!(ours, whole, "{module}"); + } + } + + /// QA (performance wave Lane B, 2026-08-28): the equality above holds + /// trivially for a shape the whitelist declines — both sides parse the + /// whole file, so a wrong slice could hide behind that. These shapes must + /// actually slice, so the comparison exercises the whitelist walk it is + /// meant to pin: an `import a::*, b::*;` chain (one statement, several + /// packages — `skip_to_semicolon` must not stop at the first `::`), a + /// `;`/`)` sitting inside a string literal, and CRLF endings. + #[test] + fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() { + for module in ["chained", "stringy", "crlf", "twice", "imported"] { + let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES"); + let path = PathBuf::from("/rtl/shape.sv"); + let index = WorkspaceIndex::build(vec![(path, *text)]); + assert!( + module_header(&index, module, text).is_some(), + "{module}: expected the header to actually slice, not fall back whole-file" + ); + } + } + + /// QA finding (performance wave Lane B, 2026-08-28), not a regression this + /// round introduced: a module with an attribute instance (`(* ... *)`) + /// anywhere near its header — right after its name, or on one of its + /// ports — is not indexed as a `Module` unit **at all**. + /// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines + /// at the very first line (no `[def]` to anchor on) before the whitelist + /// walk ever runs, and completion's module tier — which sources its + /// candidate names from the same table — never offers the module in the + /// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a + /// completion-core one: it is filed in `docs/features/completion-core/ + /// README.md`'s QA log rather than fixed here, because `vlog_semantic` is + /// outside this round's touched files. The two "attribute" shapes this QA + /// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass + /// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only + /// because both sides of that comparison fall back to the same whole-file + /// parse, which this test makes explicit rather than leaving it as an + /// unremarked side effect of the pin. + #[test] + fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() { + for module in ["attributed", "port_attributed"] { + let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES"); + let path = PathBuf::from("/rtl/shape.sv"); + let index = WorkspaceIndex::build(vec![(path, *text)]); + assert!( + index.units(module).is_empty(), + "{module}: if this starts finding a unit, module_header should be re-audited \ + for whether it now slices attributes correctly rather than by lucky fallback" + ); + assert!( + module_header(&index, module, text).is_none(), + "{module}: no unit to anchor on" + ); + } + } + + /// The guard is not decoration: a non-ANSI module really does plan + /// differently off its header, and really is sent back to the whole file. + #[test] + fn a_non_ansi_port_list_is_planned_from_the_whole_file() { + let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n"; + let path = PathBuf::from("/rtl/old.sv"); + let index = WorkspaceIndex::build(vec![(path, text)]); + let header = module_header(&index, "old", text).expect("the header slices"); + let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan"); + assert!( + sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()), + "premise: the header alone knows nothing about these ports" + ); + let (tree, _) = vlog_parser::parse_source_tolerant(text); + let semantics = vlog_semantic::analyze(&tree, text); + let site = Site { semantics: &semantics, offset: 0 }; + let guarded = plan_for(&index, "old", text, site).expect("a plan"); + assert_eq!(guarded.ports[0].dir, "input"); + assert_eq!(guarded.ports[0].ty, "wire [7:0]"); + } + + /// The whole answer, pinned at the prefixes the hot path is worst at — the + /// empty one and a one-character one, where every tier is at its widest. + /// Tier 0 is what the slice changed, so the pin spells out every skeleton's + /// label *and* the text it inserts, which is the part a wrong header would + /// corrupt. + #[test] + fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() { + let tree = Tree::new("pinned"); + tree.write("sub.sv", SUB); + tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n"); + tree.write("submarine.sv", "module submarine ();\nendmodule\n"); + let (_tree, mut ws, uri, _) = + opened(tree, "module top;\n logic clk;\n \nendmodule\n", " "); + + // Nothing typed, then one character — the two widest requests there + // are. `top` is in the answer because the buffer declares it and the + // index holds it like any other module. + let mut answer = |typed: &str| { + let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n"); + ws.set_document(uri.clone(), text.clone()); + let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32 + + typed.len() as u32; + let doc = ws.document(&uri).expect("open"); + let position = doc.positions().position(offset); + items(completions(&ws, &uri, position, true)) + }; + for (typed, expected) in + [("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])] + { + let items = answer(typed); + let found: Vec<&str> = + skeletons(&items).iter().map(|item| item.label.as_str()).collect(); + assert_eq!(found, expected, "skeletons after typing {typed:?}"); + } + + // …and the exact text one of them inserts, ports, defaults and all. + let items = answer(""); + assert_eq!( + inserted(find(&items, "sub").expect("the skeleton")), + "\ +sub #( + .WIDTH(${1:8}) + ) ${2:u_sub} ( + .clk(clk), + .data(${3:data}), + .ready(${4:ready}) + );" + ); + assert_eq!( + inserted(find(&items, "alpha").expect("the skeleton")), + "alpha ${1:u_alpha} (\n .clk(clk)\n );" + ); + assert_eq!( + inserted(find(&items, "submarine").expect("the skeleton")), + "submarine ${1:u_submarine} ();" + ); + } + + /// A file edited on disk since the index last read it has moved every span + /// the index holds, so the slice must not take one on trust. + #[test] + fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() { + let text = + "module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n"; + let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]); + assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally"); + // The same index against a file whose text has shifted underneath it. + let moved = format!("// a line nobody told the index about\n{text}"); + assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there"); + } + // ------------------------------------------------------------------ // tier 0 — module hinting (M4, unchanged behaviour) // ------------------------------------------------------------------ diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index 794c07b..ff097ad 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -363,8 +363,10 @@ fn in_file_references( /// — a use sits on, and LSP is explicit that plain `Text` is a valid answer. /// Building that analysis for a highlight colour is not a trade worth making. pub fn document_highlights(doc: &Document, offset: u32) -> Option> { - let symbol_id = symbol_at(&doc.semantics, offset)?; - let spans = occurrences(&doc.semantics, symbol_id, true); + let spans = match symbol_at(&doc.semantics, offset) { + Some(symbol_id) => occurrences(&doc.semantics, symbol_id, true), + None => external_occurrences(doc, offset), + }; if spans.is_empty() { return None; } @@ -383,6 +385,49 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option Vec { + let Some(id) = doc.semantics.reference_id_at(offset) else { return Vec::new() }; + let Some(target) = doc.external.get(id) else { return Vec::new() }; + if target.defs().is_empty() { + return Vec::new(); + } + let Some(name) = doc.semantics.reference(id).map(|r| r.name.as_str()) else { + return Vec::new(); + }; + let mut spans: Vec = doc + .semantics + .references() + .iter() + .enumerate() + .filter(|(_, reference)| reference.name == name && !reference.name_span.is_empty()) + .filter(|(at, _)| { + doc.external.get(vlog_semantic::ReferenceId(*at as u32)).map(ExternalTarget::defs) + == Some(target.defs()) + }) + .map(|(_, reference)| reference.name_span) + .collect(); + spans.sort_by_key(|span| (span.start, span.end)); + spans.dedup(); + spans +} + /// The symbol at a position. The cursor may sit on a use or on the /// declaration itself; both lead to the same symbol. /// @@ -1270,6 +1315,178 @@ mod tests { assert!(document_highlights(doc, 0).is_none(), "the `module` keyword"); } + /// `performance.md` §7, reproduced: `documentHighlight` answered nothing + /// at every opentitan position tried — an instantiated module's name, a + /// port connection — while `references` at the same positions answered. + /// Both names are declared in *another* file, which is the whole of what + /// the two handlers used to disagree about. + #[test] + fn a_cross_file_name_highlights_its_uses_in_this_file() { + let dir = temp_dir("highlight_cross"); + fs::write( + dir.join("sub.sv"), + "module sub (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n", + ) + .expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "\ +module top; + logic clk, rst; + sub u_0 (.clk_i(clk), .rst_ni(rst)); + sub u_1 (.clk_i(clk), .rst_ni(rst)); +endmodule +"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + // The module name at an instantiation: both instantiations, and + // nothing from the *other* module's file — this is one file's answer. + let module = at(top_text, "sub u_0"); + assert_eq!(references(&ws, &uri, module, true).len(), 3, "premise: references answers"); + let found = document_highlights(doc, module).expect("the instantiated module"); + let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(lines, vec![2, 3], "both instantiations of `sub`"); + assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT))); + + // A port connection: the `.clk_i` of both instantiations, and not the + // `clk` they are wired to, which is a different symbol. + let port = at(top_text, ".clk_i") + 1; + assert!(!references(&ws, &uri, port, true).is_empty(), "premise: references answers"); + let found = document_highlights(doc, port).expect("the connected port"); + let starts: Vec<(u32, u32)> = + found.iter().map(|h| (h.range.start.line, h.range.start.character)).collect(); + assert_eq!(starts, vec![(2, 12), (3, 12)], "both `.clk_i` connections"); + + let _ = fs::remove_dir_all(&dir); + } + + /// QA (performance wave Lane B, 2026-08-28): an instantiated module whose + /// name two files declare is ambiguous at the workspace layer. + /// `references` gives up on an ambiguous external target outright + /// (`indexed_target` only ever builds one from `Definition::External([def])` + /// — exactly one candidate — so an ambiguous use never reaches + /// `indexed_references`, and `in_file_references` needs a *local* symbol, + /// which an external use does not have; the net result is an empty + /// answer, unchanged by this round). `document_highlights` does not + /// inherit that caution: `external_occurrences` groups by the overlay's + /// whole answer, ambiguous sets included, so it answers here where + /// `references` does not. Recorded rather than asserted as a bug — LSP + /// does not require the two to agree, and answering something reasonable + /// beats the editor's own word-highlighter falling back to nothing — but + /// it is a real divergence the lead should see before calling the two + /// "cross-checked". + #[test] + fn an_ambiguous_instantiation_highlights_where_references_gives_up() { + let dir = temp_dir("highlight_ambiguous"); + let dup = "module dup (input logic clk_i);\nendmodule\n"; + fs::write(dir.join("a.sv"), dup).expect("write"); + fs::write(dir.join("b.sv"), dup).expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "\ +module top; + logic clk; + dup u_0 (.clk_i(clk)); + dup u_1 (.clk_i(clk)); +endmodule +"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + let module = at(top_text, "dup u_0"); + assert!(leaves_this_file(&ws, doc, module), "dup is a unit the index holds"); + assert!( + references(&ws, &uri, module, true).is_empty(), + "references declines an ambiguous external target rather than guessing" + ); + let found = document_highlights(doc, module).expect("highlight groups the ambiguous use"); + let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(lines, vec![2, 3], "both instantiations, grouped by the same ambiguous def set"); + + let _ = fs::remove_dir_all(&dir); + } + + /// Two uses of the *same name* that are ambiguous between *different* + /// def sets must not be grouped into one highlight — the def-set + /// comparison in `external_occurrences`, not the name match alone, is + /// what keeps them apart. `dup_a` and `dup_b` are each declared in two + /// files (so a connection to either is ambiguous), and both happen to + /// export a port with the identical name `same_port` — so the two + /// connections below share one `reference.name` but must resolve against + /// disjoint ambiguous sets (`dup_a`'s two files vs. `dup_b`'s two files). + #[test] + fn two_uses_ambiguous_between_different_def_sets_do_not_group() { + let dir = temp_dir("highlight_ambiguous_disjoint"); + let dup_a = "module dup_a (input logic same_port);\nendmodule\n"; + let dup_b = "module dup_b (input logic same_port);\nendmodule\n"; + fs::write(dir.join("a1.sv"), dup_a).expect("write"); + fs::write(dir.join("a2.sv"), dup_a).expect("write"); + fs::write(dir.join("b1.sv"), dup_b).expect("write"); + fs::write(dir.join("b2.sv"), dup_b).expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "\ +module top; + logic clk; + dup_a u_a (.same_port(clk)); + dup_b u_b (.same_port(clk)); +endmodule +"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + let first = at(top_text, "same_port(clk));\n dup_b") + 1; + let second = at(top_text, "same_port(clk));\nendmodule") + 1; + // Premise: both connections are genuinely ambiguous externals (no + // local `same_port`, and the workspace really does hold two + // candidates for each), i.e. this exercises the def-set comparison + // and not some earlier decline. + let first_found = + document_highlights(doc, first).expect("dup_a's connection is ambiguous, not empty"); + let second_found = + document_highlights(doc, second).expect("dup_b's connection is ambiguous, not empty"); + let first_lines: Vec = first_found.iter().map(|h| h.range.start.line).collect(); + let second_lines: Vec = second_found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(first_lines, vec![2], "dup_a's port only, despite sharing a name with dup_b's"); + assert_eq!(second_lines, vec![3], "dup_b's port only, despite sharing a name with dup_a's"); + + let _ = fs::remove_dir_all(&dir); + } + + /// A use the overlay never answered — its `defs()` is empty, e.g. a + /// package member the index does not hold — must decline like any other + /// unanswered position, not fall through to some other file's namesake. + #[test] + fn an_unanswered_external_use_declines_rather_than_guessing() { + let dir = temp_dir("highlight_unanswered"); + let top_path = dir.join("top.sv"); + // `missing_pkg` is never declared anywhere in the workspace, so the + // import itself is the only thing the index can say nothing about; + // `NOPE` is a member reference the overlay tries and fails to place. + let top_text = "module top;\n import missing_pkg::*;\n wire [NOPE-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + let use_pos = at(top_text, "NOPE") + 1; + assert!(document_highlights(doc, use_pos).is_none(), "unresolved, so decline"); + + let _ = fs::remove_dir_all(&dir); + } + #[test] fn a_package_import_resolves_into_the_packages_file() { let dir = temp_dir("pkg"); diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index 4a8ac72..23696b8 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -578,6 +578,300 @@ fn what_a_jump_into_a_new_folder_costs_before_and_after() { let _ = std::fs::remove_dir_all(&dir); } +/// The module-name families a completion prefix lands in, so a one-character +/// prefix names hundreds of modules and a five-character one names a handful — +/// the shape `performance.md`'s prefix table has on the real corpus. +const FAMILIES: [&str; 10] = [ + "aes", + "prim", + "kmac", + "hmac", + "spi_device", + "otbn", + "flash_ctrl", + "rv_core", + "clkmgr", + "uart", +]; + +/// A workspace the size of the corpus `performance.md` measured against: one +/// module per file, named from [`FAMILIES`], each declaring names no other file +/// declares so the word table grows with the file count the way a real one does. +fn completion_corpus(dir: &std::path::Path, files: usize, body: usize) { + for n in 0..files { + let family = FAMILIES[n % FAMILIES.len()]; + let name = format!("{family}_{n:04}"); + std::fs::write(dir.join(format!("{name}.sv")), corpus_file(&name, body)).expect("write"); + } +} + +/// One corpus file: a package, then a module whose header is what a skeleton +/// reads and whose body is the several hundred lines a real RTL file carries +/// behind it. +fn corpus_file(name: &str, body: usize) -> String { + let mut text = format!( + "package {name}_pkg;\n localparam int {name}_WIDTH = 8;\n \ + typedef logic [1:0] {name}_pair_t;\nendpackage\n\ + module {name} #(\n parameter int WIDTH = 8\n) (\n \ + input logic clk_i,\n input logic rst_ni,\n \ + input logic [WIDTH-1:0] {name}_data_i,\n \ + output logic [WIDTH-1:0] {name}_data_o\n);\n" + ); + for n in 0..body / 4 { + text.push_str(&format!( + " wire [WIDTH-1:0] {name}_w{n};\n \ + assign {name}_w{n} = {name}_data_i ^ {{WIDTH{{rst_ni}}}};\n \ + reg [WIDTH-1:0] {name}_r{n};\n \ + always_ff @(posedge clk_i) {name}_r{n} <= {name}_w{n};\n" + )); + } + text.push_str(&format!(" assign {name}_data_o = {name}_data_i;\nendmodule\n")); + text +} + +/// The buffer a completion is asked for in: a module body with `prefix` typed +/// on a fresh item line, and the same prefix inside an expression. +fn completion_buffer(prefix: &str, at_item: bool) -> (String, u32) { + let text = match at_item { + true => format!("module bench_top;\n {prefix}\nendmodule\n"), + false => format!("module bench_top;\n logic x;\n assign x = {prefix}\nendmodule\n"), + }; + let cursor = text.find("\nendmodule").expect("the last line") as u32; + (text, cursor) +} + +/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server perf::completing_over_a_real -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"] +fn completing_over_a_real_project() { + // The same measurement as `completing_one_keystroke_at_a_time`, over + // whatever tree `LUCISV_PERF_CORPUS` names, with tier 0's bill broken out + // over the modules that tree really declares. A generated corpus has + // uniform files; a real one has a hundred-line header on one module and a + // two-thousand-line body on the next, and the difference between the two + // is worth being able to see. **Skipped when the variable is unset**, so + // this crate's tests never depend on a checkout nobody promised. + let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else { + eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure"); + return; + }; + let root = PathBuf::from(root); + let mut ws = Workspace::default(); + ws.set_client_settings(crate::settings::ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }); + let started = Instant::now(); + ws.open_whole_workspace(vec![root.clone()]); + let scan = started.elapsed(); + let buffer = root.join("lucisv_perf_buffer.sv"); + let uri = path_to_uri(&buffer).expect("uri"); + eprintln!( + "completion over {} indexed files of {} (scan {scan:?}), {} index names, {} words:", + ws.index().files().len(), + root.display(), + ws.candidates().units("").len(), + ws.candidates().words("").len() + ); + + for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_reg", "zzzz"] { + let (text, cursor) = completion_buffer(prefix, true); + ws.set_document(uri.clone(), text.clone()); + let position = { + let doc = ws.document(&uri).expect("open"); + doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start + }; + let items = match crate::completion::completions(&ws, &uri, position, true) { + Some(lsp_types::CompletionResponse::List(list)) => list.items.len(), + _ => 0, + }; + let took = mean(5, || { + black_box(crate::completion::completions(&ws, &uri, black_box(position), true)); + }); + + // Tier 0's bill over this prefix's own candidates, stage by stage, so + // a slow row can be read rather than guessed at. + let names: Vec = + ws.candidates().modules(prefix).iter().take(64).map(|n| n.to_string()).collect(); + let (mut read, mut slice, mut plan) = (0u128, 0u128, 0u128); + let mut whole_files: Vec<&str> = Vec::new(); + let mut bytes = 0usize; + for name in &names { + let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue }; + let started = Instant::now(); + let Some(text) = ws.text_of(path) else { continue }; + read += started.elapsed().as_nanos(); + bytes += text.len(); + let started = Instant::now(); + let header = crate::completion::module_header(ws.index(), name, &text); + slice += started.elapsed().as_nanos(); + let source = match header.as_deref() { + Some(head) => head, + None => { + whole_files.push(name); + &text + } + }; + let started = Instant::now(); + black_box(vlog_refactor::instantiation_plan(name, source, None).ok()); + plan += started.elapsed().as_nanos(); + } + let each = names.len().max(1) as u128; + eprintln!( + " prefix {prefix:>9?}: {took:?} ({items} items); tier 0 over {} modules \ + ({} KB read, parsed whole: {whole_files:?}): read {:?}, slice {:?}, plan {:?} each", + names.len(), + bytes / 1000, + Duration::from_nanos((read / each) as u64), + Duration::from_nanos((slice / each) as u64), + Duration::from_nanos((plan / each) as u64), + ); + } +} + +/// `cargo test --release -p lucisv_server perf::completing_one -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn completing_one_keystroke_at_a_time() { + // `performance.md` §6d: completion cost tracks the *candidate* count before + // the 512-item cap, so it is worst at the empty prefix — exactly where + // every identifier starts. Two columns over the same workspace and the same + // prefixes: the cursor at module-item position, where every tier runs, and + // the cursor inside an expression, where the module-skeleton tier is gated + // off. The difference between them is what tier 0 costs. + let (files, body) = (4_000, 1_200); + let dir = std::env::temp_dir().join(format!("lucisv_perf_completion_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + completion_corpus(&dir, files, body); + std::fs::write(dir.join("bench_top.sv"), "module bench_top;\nendmodule\n").expect("write"); + + let mut ws = Workspace::default(); + ws.set_client_settings(crate::settings::ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }); + let started = Instant::now(); + ws.open_whole_workspace(vec![dir.clone()]); + let scan = started.elapsed(); + let uri = path_to_uri(&dir.join("bench_top.sv")).expect("uri"); + + eprintln!( + "completion over {} indexed files (scan {scan:?}), \ + {} index names, {} project words:", + ws.index().files().len(), + ws.candidates().units("").len(), + ws.candidates().words("").len() + ); + for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_0001", "zzzz"] { + let mut row = String::new(); + for at_item in [true, false] { + let (text, cursor) = completion_buffer(prefix, at_item); + ws.set_document(uri.clone(), text.clone()); + let position = { + let doc = ws.document(&uri).expect("open"); + doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start + }; + let items = match crate::completion::completions(&ws, &uri, position, true) { + Some(lsp_types::CompletionResponse::List(list)) => list.items.len(), + _ => 0, + }; + let took = mean(5, || { + black_box(crate::completion::completions(&ws, &uri, black_box(position), true)); + }); + let where_ = if at_item { "item" } else { "expr" }; + row.push_str(&format!(" {where_} {took:?} ({items} items);")); + } + eprintln!(" prefix {prefix:>9?}:{row}"); + } + + // Tier 0's per-item bill, so the row above can be divided by 64. + let module = "aes_0000"; + let path = dir.join(format!("{module}.sv")); + let text = ws.text_of(&path).expect("readable"); + let read = mean(50, || { + black_box(ws.text_of(black_box(&path))); + }); + let whole = mean(50, || { + black_box( + vlog_refactor::instantiation_plan(black_box(module), black_box(&text), None).ok(), + ); + }); + let header = crate::completion::module_header(ws.index(), module, &text).expect("a header"); + let sliced = mean(50, || { + black_box( + vlog_refactor::instantiation_plan(black_box(module), black_box(&header), None).ok(), + ); + }); + let slicing = mean(50, || { + black_box(crate::completion::module_header( + ws.index(), + black_box(module), + black_box(&text), + )); + }); + eprintln!( + " one skeleton off a {}-line file: text_of {read:?}, \ + instantiation_plan over the whole file {whole:?}, \ + over its header alone {sliced:?} (slicing it: {slicing:?})", + text.lines().count() + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `cargo test --release -p lucisv_server perf::what_the_scope_depth -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn what_the_scope_depth_default_costs() { + // What moving the shipped `lucisv.index.scopeDepth` from 0 to 2 buys and + // what it costs, on an opentitan-shaped tree this repository generates for + // itself: blocks of `rtl/` and `dv/tb/`, with the opened buffer three + // levels down — the layout `performance.md` §4 measured one indexed file + // in. Every rung of the ladder over the same tree, so the columns are + // comparable. + let (blocks, per_folder, lines) = (12, 20, 200); + let dir = std::env::temp_dir().join(format!("lucisv_perf_depth_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for block in 0..blocks { + for (folder, count) in [("rtl", per_folder), ("dv/tb", 1)] { + let path = dir.join(format!("hw/ip/blk{block:02}/{folder}")); + std::fs::create_dir_all(&path).expect("folder"); + for file in 0..count { + let name = format!("b{block:02}_{}_{file:02}", folder.replace('/', "_")); + std::fs::write(path.join(format!("{name}.sv")), generated_module(&name, lines)) + .expect("write"); + } + } + } + let opened = dir.join("hw/ip/blk00/dv/tb/b00_dv_tb_00.sv"); + let uri = path_to_uri(&opened).expect("uri"); + let text = std::fs::read_to_string(&opened).expect("read"); + + eprintln!( + "scopeDepth over {blocks} blocks of {} files ({per_folder} rtl + 1 dv/tb each), \ + buffer opened at hw/ip/blk00/dv/tb:", + per_folder + 1 + ); + for depth in [0u64, 1, 2, 3] { + let mut ws = Workspace::default(); + ws.set_client_settings(crate::settings::ClientSettings { + index_scope_depth: depth, + ..Default::default() + }); + ws.adopt_roots(vec![dir.clone()]); + ws.set_document(uri.clone(), text.clone()); + let started = Instant::now(); + black_box(ws.rebuild_index()); + let scan = started.elapsed(); + eprintln!( + " depth {depth}: {} files indexed, {} index names, scan {scan:?}", + ws.index().files().len(), + ws.candidates().units("").len() + ); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// `cargo test --release -p lucisv_server perf::a_code_action -- --ignored --nocapture --test-threads=1` #[test] #[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 62dad93..9d295b6 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -4043,7 +4043,16 @@ mod tests { let tree = Tree::new("scoperescan"); tree.package("rtl/a.sv", "a"); tree.package("include/defs.sv", "defs_pkg"); + let scoped = |scope: &str, depth: u32| { + serde_json::json!({ + "settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } } + }) + }; let mut session = Session::with(vec![tree.path.clone()], watching_progress()); + // The shipped depth is 2 since 2026-08-28, which already reaches the + // sibling folder — so the narrow premise this test raises the depth + // *from* is asked for out loud. + session.notify(DidChangeConfiguration::METHOD, scoped("folder", 0)); let uri = session.open( &tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\n\ @@ -4052,12 +4061,6 @@ mod tests { let _ = (uri, session.drain()); assert_eq!(indexed(&session, "defs_pkg"), 0, "premise: the sibling folder is out of scope"); - let scoped = |scope: &str, depth: u32| { - serde_json::json!({ - "settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } } - }) - }; - session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1)); assert_eq!(session.progress().len(), 5, "create, begin, two reports, end"); assert_eq!(indexed(&session, "defs_pkg"), 1, "one level up reaches the sibling folder"); @@ -7390,6 +7393,13 @@ mod tests { tree.package("rtl/a.sv", "a"); tree.package("lib/late.sv", "late"); let mut session = Session::new(vec![tree.path.clone()], false); + // The shipped depth is 2 since 2026-08-28, which would have `lib/` in + // scope before the widen this test is about — so the premise names the + // narrow depth rather than assuming it. + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "index": { "scopeDepth": 0 } } } }), + ); let _ = session .open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n"); assert_eq!(indexed(&session, "a"), 1, "premise: the first folder is in scope"); diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index b048d52..1c74cf3 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -41,6 +41,25 @@ pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024; /// `docs/features/large-file-mode/README.md`. pub const DEFAULT_LARGE_FILE_THRESHOLD: u64 = 4 * 1024 * 1024; +/// `lucisv.index.scopeDepth`'s default: 2 levels above the open file's own +/// folder, clamped at the workspace root that contains it. +/// +/// **Changed from 0 on 2026-08-28**, and it is a behaviour change, not a +/// tuning one. At 0 the folder scope indexed the opened file's directory and +/// nothing else, and the measurement that forced the change is in +/// `performance.md` §4: opening `hw/ip/aes/dv/tb/tb.sv` in opentitan gave an +/// index of **one file**, so definition, hover, references, `workspace/symbol` +/// and signature help all answered *nothing* until some later jump widened the +/// scope. A user's first experience of the server was silence. +/// +/// Two levels is the smallest raise that turns a `dv/tb` or an `rtl` file into +/// the IP block it belongs to — `hw/ip/aes`, a few hundred files — which is +/// the unit an engineer actually works in. What keeps the cost bounded is +/// everything the scope ladder already has: the size cap, the persistent +/// cache, the interleaved scan and the incremental widen. See +/// `docs/features/index-scope/README.md`. +pub const DEFAULT_SCOPE_DEPTH: u64 = 2; + /// What `lucisv.index.scope` chooses: how wide the workspace walk goes. /// /// The default is deliberately the narrow one. A large project is the case @@ -115,9 +134,9 @@ pub struct ClientSettings { pub index_scope: IndexScope, /// `lucisv.index.scopeDepth`: how many directory levels above an open /// file's own folder the folder scope starts, clamped so it never climbs - /// out of the workspace folder containing it. `0` — the default — is the - /// file's own folder. Ignored when `index_scope` is - /// [`IndexScope::Workspace`] or when a filelist defines the scope. + /// out of the workspace folder containing it. `0` is the file's own folder + /// and the default is [`DEFAULT_SCOPE_DEPTH`]. Ignored when `index_scope` + /// is [`IndexScope::Workspace`] or when a filelist defines the scope. pub index_scope_depth: u64, /// `lucisv.index.persist`: whether what a scan parsed is written to disk /// so the next session can skip parsing the files that have not changed. @@ -156,7 +175,7 @@ impl Default for ClientSettings { max_file_size: DEFAULT_MAX_FILE_SIZE, log_files: true, index_scope: IndexScope::Folder, - index_scope_depth: 0, + index_scope_depth: DEFAULT_SCOPE_DEPTH, index_persist: true, index_cache_path: None, large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD, @@ -210,7 +229,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings { // silently costs a user minutes of scanning is the wrong one to // guess in. index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(), - index_scope_depth: count(index.and_then(|i| i.get("scopeDepth"))).unwrap_or(0), + // A junk depth leaves the shipped default standing, like every + // other setting here: an unreadable value must never be the reason a + // user's index is narrower than the server promised. + index_scope_depth: count(index.and_then(|i| i.get("scopeDepth"))) + .unwrap_or(DEFAULT_SCOPE_DEPTH), // A wrong-typed `persist` leaves the cache on. The direction that // costs something is turning it *off* by accident — a user who never // touched the setting would silently pay for every parse again — and @@ -345,7 +368,7 @@ mod tests { "formatOnSave": false, "index": { "maxFileSize": 1048576, "logFiles": true, - "scope": "folder", "scopeDepth": 0 + "scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH } } }) @@ -380,7 +403,7 @@ mod tests { assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored"); assert!(found.log_files, "and so is its logFiles"); assert_eq!(found.index_scope, IndexScope::Folder, "and its scope"); - assert_eq!(found.index_scope_depth, 0, "and its scopeDepth"); + assert_eq!(found.index_scope_depth, DEFAULT_SCOPE_DEPTH, "and its scopeDepth"); } } @@ -480,11 +503,22 @@ mod tests { } #[test] - fn the_scope_depth_is_zero_until_a_client_raises_it() { - assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, 0); - assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope_depth, 0); + fn the_scope_depth_is_two_until_a_client_says_otherwise() { + // Two, not zero, since 2026-08-28: `performance.md` §4 measured the + // file's-own-folder default indexing exactly one file in opentitan's + // `dv/tb` layout, so every cross-file answer was empty until some + // later jump widened the scope. See [`DEFAULT_SCOPE_DEPTH`]. + assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, DEFAULT_SCOPE_DEPTH); + assert_eq!( + settings(json!({ "lucisv": { "index": {} } })).index_scope_depth, + DEFAULT_SCOPE_DEPTH + ); let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } })); assert_eq!(raised.index_scope_depth, 3); + // Zero is still exactly what it always was — the file's own folder and + // nothing above it — and asking for it still gets it. + let narrow = settings(json!({ "lucisv": { "index": { "scopeDepth": 0 } } })); + assert_eq!(narrow.index_scope_depth, 0, "an explicit 0 is honoured, not defaulted"); // No upper bound here: the clamp is structural — `state.rs` stops at // the workspace root — so an absurd number is not wrong, just fully // clamped. @@ -492,7 +526,10 @@ mod tests { assert_eq!(absurd.index_scope_depth, 9999); for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] { let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } })); - assert_eq!(found.index_scope_depth, 0, "scopeDepth {bad} must be ignored"); + assert_eq!( + found.index_scope_depth, DEFAULT_SCOPE_DEPTH, + "scopeDepth {bad} must be ignored" + ); } } @@ -519,6 +556,29 @@ mod tests { assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence"); } + /// [`vscode_payload`] above is a hand-written copy of what the extension + /// declares, and a copy that drifts proves nothing. The extension's own + /// `package.json` is the thing a user's settings UI reads, so the two + /// defaults that are not "no opinion" are checked against it directly. + #[test] + fn the_extensions_declared_defaults_are_the_ones_this_module_ships() { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../editors/vscode/package.json"); + let text = std::fs::read_to_string(&path).expect("the extension manifest"); + let manifest: Value = serde_json::from_str(&text).expect("valid json"); + let properties = &manifest["contributes"]["configuration"]["properties"]; + assert_eq!( + properties["lucisv.index.scopeDepth"]["default"], + json!(DEFAULT_SCOPE_DEPTH), + "the settings UI and the server must ship the same scope depth" + ); + assert_eq!( + properties["lucisv.index.maxFileSize"]["default"], + json!(DEFAULT_MAX_FILE_SIZE), + "and the same size cap" + ); + } + #[test] fn the_default_vscode_payload_is_no_opinion_about_anything() { // Every setting at its `package.json` default: nulls and an empty diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 3e34bb1..22629ad 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -658,7 +658,19 @@ impl Workspace { /// /// The root clamp is what keeps a `scopeDepth` of 5 in a two-deep project /// from indexing the user's home directory. + /// + /// **A rootless session does not climb at all** (2026-08-28). The clamp is + /// the whole reason a raise is safe, and with no workspace folder there is + /// nothing to clamp against: a lone file opened from + /// `~/work/chip/hw/ip/aes/rtl/` would otherwise raise the shipped + /// [`crate::settings::DEFAULT_SCOPE_DEPTH`] into `~/work/chip/hw/ip/` and + /// walk a tree the user never named. The single-file case stays what it + /// has always been — the buffer's own directory, read flat — and a user + /// who wants more opens the folder, which is what gives the climb a floor. fn raised(&self, dir: &Path) -> PathBuf { + if self.roots.is_empty() { + return dir.to_path_buf(); + } let floor = self .roots .iter() @@ -2577,6 +2589,7 @@ mod tests { tree.package("elsewhere/far.sv", "far"); let mut ws = Workspace::default(); + own_folder_only(&mut ws); ws.open_whole_workspace(vec![tree.path.clone()]); assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]); @@ -2679,10 +2692,22 @@ mod tests { fn excluding(patterns: &[&str]) -> ClientSettings { ClientSettings { exclude: patterns.iter().map(|p| p.to_string()).collect(), + index_scope_depth: 0, ..Default::default() } } + /// The folder rung at `scopeDepth: 0` — the open file's own folder and + /// nothing above it. + /// + /// Said out loud since 2026-08-28, when the shipped default became + /// [`crate::settings::DEFAULT_SCOPE_DEPTH`]: a test about *this* rung + /// names the depth it is about rather than riding whatever the default is + /// this month. The behaviour it selects is unchanged. + fn own_folder_only(ws: &mut Workspace) { + ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }); + } + #[test] fn a_pushed_exclude_hides_files_from_the_index() { let tree = Tree::new("clientexclude"); @@ -3117,6 +3142,7 @@ mod tests { tree.package("elsewhere/far.sv", "far"); let mut ws = Workspace::default(); + own_folder_only(&mut ws); assert!(!ws.has_roots(), "the premise: no workspace folder"); let path = tree.path.join("rtl/open.sv"); let uri = crate::uri::path_to_uri(&path).expect("uri"); @@ -3258,11 +3284,14 @@ mod tests { } #[test] - fn the_default_scope_is_the_open_files_own_folder_and_everything_under_it() { - // The headline of this round: a workspace root is open, but the index - // covers the folder the user is working in, not the project. + fn the_folder_scope_at_depth_zero_is_the_open_files_own_folder_and_everything_under_it() { + // The headline of the index-scope round: a workspace root is open, but + // the index covers the folder the user is working in, not the project. + // At depth 0 — the shipped default until 2026-08-28, and still exactly + // what an explicit `scopeDepth: 0` asks for. let tree = two_folder_tree("scopedefault"); let mut ws = Workspace::default(); + own_folder_only(&mut ws); ws.open_roots(vec![tree.path.clone()]); assert!(scoped(&ws).is_empty(), "premise: nothing is open, so nothing is in scope"); @@ -3310,38 +3339,51 @@ mod tests { } #[test] - fn a_rootless_climb_stops_at_the_filesystem_root() { - // With no workspace folder there is nothing to clamp against, so the - // only floor left is `/` — the setting means exactly what it says, and - // the loop terminates there rather than spinning. Stated in the - // feature README as the reason to leave `scopeDepth` at 0 in a - // rootless session. No index is built here: the point is that the - // climb stops, and walking `/` is precisely what a test must not do. + fn a_rootless_session_does_not_climb_at_all() { + // Changed 2026-08-28, with the shipped depth. The climb used to run + // with `/` as its only floor, which was survivable while the shipped + // depth was 0 and nobody climbed by accident. It is not survivable at + // depth 2: a lone file opened from `~/work/chip/hw/ip/aes/rtl/` would + // raise into `~/work/chip/hw/ip/` and walk a tree the user never + // named. The clamp is what makes a raise safe, so with nothing to + // clamp against there is no raise, whatever the depth says. let tree = two_folder_tree("scoperootless"); - let mut ws = Workspace::default(); - ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() }); - open(&mut ws, &tree, "rtl/open.sv"); - assert!(!ws.has_roots(), "the premise: no workspace folder to clamp against"); - assert_eq!(ws.scope_dirs(), vec![PathBuf::from("/")], "it climbs to the root and stops"); + for depth in [0, 1, 99] { + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { + index_scope_depth: depth, + ..Default::default() + }); + open(&mut ws, &tree, "rtl/open.sv"); + assert!(!ws.has_roots(), "the premise: no workspace folder to clamp against"); + assert_eq!( + ws.scope_dirs(), + vec![tree.path.join("rtl")], + "depth {depth}: the buffer's own directory, and nothing above it" + ); + } } #[test] - fn a_rootless_session_that_raises_the_depth_walks_instead_of_reading_one_level() { - // The one exception in `folder_files`, from the other side: at depth 0 - // a rootless session reads its directories flat (pinned by - // `with_no_workspace_root_the_open_files_own_directory_is_indexed`, - // unchanged this round), and the moment the user raises the depth they - // have named a tree, so it is walked. + fn a_rootless_session_reads_its_own_directory_flat_until_the_depth_is_raised() { + // The `folder_files` exception, from the other side. The *directory* + // is the buffer's own whatever the depth (no root, no climb — see + // above), but the depth still chooses how it is read: 0 reads it flat, + // one level, no `.gitignore`, and a raise means the user has asked for + // a tree, so the tree below the buffer is walked. let tree = two_folder_tree("scoperootlesswalk"); - let mut ws = Workspace::default(); - ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() }); - open(&mut ws, &tree, "rtl/open.sv"); - ws.rebuild_index(); - assert_eq!( - scoped(&ws), - ["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"], - "raised one level and walked from there" - ); + for (depth, expected) in + [(0, vec!["open_pkg", "beside_pkg"]), (1, vec!["open_pkg", "beside_pkg", "below_pkg"])] + { + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { + index_scope_depth: depth, + ..Default::default() + }); + open(&mut ws, &tree, "rtl/open.sv"); + ws.rebuild_index(); + assert_eq!(scoped(&ws), expected, "depth {depth}"); + } } #[test] @@ -3497,7 +3539,7 @@ mod tests { assert!(!ws.set_client_settings(wide.clone()), "the same one does not"); assert!(ws.set_client_settings(ClientSettings::default()), "and going back does"); - let deep = ClientSettings { index_scope_depth: 2, ..Default::default() }; + let deep = ClientSettings { index_scope_depth: 5, ..Default::default() }; assert!(ws.set_client_settings(deep.clone()), "a new depth rescans"); assert!(!ws.set_client_settings(deep), "the same one does not"); assert!(ws.set_client_settings(ClientSettings::default()), "and going back does"); @@ -3804,6 +3846,7 @@ mod tests { let tree = two_folder_tree("filelistmid"); tree.write("files.f", "elsewhere/far.sv\n"); let mut ws = Workspace::default(); + own_folder_only(&mut ws); ws.open_roots(vec![tree.path.clone()]); open(&mut ws, &tree, "rtl/open.sv"); ws.rebuild_index(); @@ -3834,6 +3877,7 @@ mod tests { outside.package("other/b.sv", "b_pkg"); let mut ws = Workspace::default(); + own_folder_only(&mut ws); ws.open_roots(vec![inside.path.clone()]); open(&mut ws, &outside, "other/b.sv"); assert_eq!( @@ -3864,6 +3908,7 @@ mod tests { fn caching(dir: &Path) -> ClientSettings { ClientSettings { index_cache_path: Some(dir.to_string_lossy().into_owned()), + index_scope_depth: 0, ..Default::default() } } @@ -4756,6 +4801,7 @@ mod tests { let sub_text = fs::read_to_string(tree.path.join("lib/sub.sv")).expect("read"); let mut incremental = Workspace::default(); + own_folder_only(&mut incremental); incremental.open_roots(vec![tree.path.clone()]); incremental.set_document(top.clone(), edited.to_string()); incremental.rebuild_index(); @@ -4763,6 +4809,7 @@ mod tests { widen(&mut incremental, |ws| ws.set_document(sub.clone(), sub_text.clone())); let mut rebuilt = Workspace::default(); + own_folder_only(&mut rebuilt); rebuilt.open_roots(vec![tree.path.clone()]); rebuilt.set_document(top.clone(), edited.to_string()); rebuilt.set_document(sub.clone(), sub_text.clone()); @@ -4786,6 +4833,7 @@ mod tests { let sub_text = fs::read_to_string(&sub_path).expect("read"); let mut ws = Workspace::default(); + own_folder_only(&mut ws); ws.open_roots(vec![tree.path.clone()]); ws.set_document(top.clone(), fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r")); ws.rebuild_index(); @@ -4829,6 +4877,7 @@ mod tests { let sub_text = fs::read_to_string(&sub_path).expect("read"); let mut ws = Workspace::default(); + own_folder_only(&mut ws); ws.open_roots(vec![tree.path.clone()]); ws.set_document(top, fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r")); ws.rebuild_index(); @@ -4866,6 +4915,7 @@ mod tests { let shallow_text = fs::read_to_string(tree.path.join("rtl/b.sv")).expect("read"); let mut incremental = Workspace::default(); + own_folder_only(&mut incremental); incremental.open_roots(vec![tree.path.clone()]); incremental.set_document(deep.clone(), deep_text.clone()); incremental.rebuild_index(); @@ -4895,6 +4945,7 @@ mod tests { assert_eq!(incremental.index().files().len(), 2, "a.sv is indexed once, not twice"); let mut rebuilt = Workspace::default(); + own_folder_only(&mut rebuilt); rebuilt.open_roots(vec![tree.path.clone()]); rebuilt.set_document(deep, deep_text); rebuilt.set_document(shallow, shallow_text); @@ -4922,12 +4973,14 @@ mod tests { let lib_text = fs::read_to_string(tree.path.join("lib/lib_pkg.sv")).expect("read"); let mut incremental = Workspace::default(); + own_folder_only(&mut incremental); incremental.open_roots(vec![tree.path.clone()]); incremental.set_document(top.clone(), top_text.clone()); incremental.rebuild_index(); widen(&mut incremental, |ws| ws.set_document(lib.clone(), lib_text.clone())); let mut rebuilt = Workspace::default(); + own_folder_only(&mut rebuilt); rebuilt.open_roots(vec![tree.path.clone()]); rebuilt.set_document(top, top_text); rebuilt.set_document(lib, lib_text); @@ -4952,6 +5005,7 @@ mod tests { let mut incremental = Workspace::default(); incremental.set_client_settings(ClientSettings { large_file_threshold: 200, + index_scope_depth: 0, ..Default::default() }); incremental.open_roots(vec![tree.path.clone()]); @@ -4971,6 +5025,7 @@ mod tests { let mut rebuilt = Workspace::default(); rebuilt.set_client_settings(ClientSettings { large_file_threshold: 200, + index_scope_depth: 0, ..Default::default() }); rebuilt.open_roots(vec![tree.path.clone()]); diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index b675817..108ab30 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -1241,7 +1241,13 @@ fn with_no_workspace_folder_the_open_files_own_directory_is_indexed() { }; assert_eq!(hits(2), 0, "premise: nothing is indexed before a file is open"); assert_eq!(hits(3), 1, "the neighbour of the open file is indexed"); - assert_eq!(hits(4), 0, "but the walk does not descend — this is one directory"); + // Changed 2026-08-28 with the shipped `scopeDepth` of 2. A rootless + // session still does not *climb* — there is no workspace root to clamp a + // climb against, so `raised` leaves the buffer's own directory alone — but + // a non-zero depth still asks for a walk rather than a flat read, so the + // subtree under that one directory is now indexed. Bounded by the + // directory the user opened a file from, and no wider. + assert_eq!(hits(4), 1, "the depth asks for a walk of that one directory"); let _ = std::fs::remove_dir_all(&dir); } @@ -2008,6 +2014,16 @@ fn cross_file_references_folding_and_highlights_round_trip_over_the_wire() { frame(&format!( r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":8}}}}}}"# )), + // `performance.md` §7: documentHighlight answered `null` at every + // opentitan position tried — an instantiated module's name and a port + // connection — while `references` (id 2 above, same position) + // answered. Both are names declared in the *other* file. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":2}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":12}}}}}}"# + )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] @@ -2068,6 +2084,23 @@ fn cross_file_references_folding_and_highlights_round_trip_over_the_wire() { ); assert!(highlights.iter().all(|h| h["kind"] == 1), "DocumentHighlightKind.Text"); + // The two positions `performance.md` reported as answering nothing. + let starts = |id: u32| -> Vec<(u64, u64)> { + response(id)["result"] + .as_array() + .unwrap_or_else(|| panic!("response {id} answered nothing: {:#?}", response(id))) + .iter() + .map(|h| { + ( + h["range"]["start"]["line"].as_u64().expect("line"), + h["range"]["start"]["character"].as_u64().expect("character"), + ) + }) + .collect() + }; + assert_eq!(starts(6), vec![(2, 2)], "the instantiated module's name, declared in sub.sv"); + assert_eq!(starts(7), vec![(2, 12)], "the `.clk` port name, declared in sub.sv"); + let _ = std::fs::remove_dir_all(&dir); } @@ -4337,6 +4370,98 @@ fn the_configuration_pull_round_trips_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } +/// index-scope (2026-08-28): the *shipped* `scopeDepth`, over the real wire. +/// +/// `performance.md` §4 measured the old default of 0 indexing exactly one file +/// when opening `hw/ip/aes/dv/tb/tb.sv` in opentitan — `dv/tb/` holds only +/// `tb.sv` — so definition, hover, references and `workspace/symbol` all +/// answered nothing until some later jump widened the scope. The default is 2 +/// now, and this pins all three rungs of that decision on the same tree: what +/// the shipped depth reaches, that the climb clamps at the workspace root, and +/// that an explicit `0` is still exactly what it always was. +#[test] +fn the_shipped_scope_depth_reaches_the_block_a_file_belongs_to() { + let dir = temp_dir("scopedepthdefault"); + let outside = temp_dir("scopedepthoutside"); + let package = |path: PathBuf, name: &str| { + std::fs::create_dir_all(path.parent().expect("a parent")).expect("dirs"); + std::fs::write(&path, format!("package {name};\n localparam WIDTH = 8;\nendpackage\n")) + .expect("write"); + }; + // The opentitan shape: a block with its RTL and its testbench two folders + // apart, a *second* block beside it, and a file at the workspace root. + package(dir.join("hw/ip/aes/rtl/aes.sv"), "aes_pkg"); + package(dir.join("hw/ip/kmac/rtl/kmac.sv"), "kmac_pkg"); + package(dir.join("root.sv"), "root_pkg"); + package(outside.join("outside.sv"), "outside_pkg"); + let tb = dir.join("hw/ip/aes/dv/tb/tb.sv"); + let tb_text = "module tb;\n localparam W = aes_pkg::WIDTH;\nendmodule\n"; + std::fs::create_dir_all(tb.parent().expect("a parent")).expect("dirs"); + std::fs::write(&tb, tb_text).expect("write"); + + let root = format!("file://{}", dir.display()); + let tb_uri = format!("file://{}", tb.display()); + let query = |id: u32, name: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"# + )) + }; + let depth = |n: u32| { + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"index":{{"scopeDepth":{n}}}}}}}}}}}"# + )) + }; + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{tb_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(tb_text).expect("json") + )), + // Nothing has been widened and no setting has been touched: this is + // what a user gets the moment they open a testbench. + query(2, "aes_pkg"), + query(3, "kmac_pkg"), + // The block, not the world — so the definition in the buffer resolves. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{tb_uri}"}},"position":{{"line":1,"character":27}}}}}}"# + )), + // An explicit 0 is the old behaviour, unchanged: `dv/tb/` alone, which + // holds nothing but the open buffer. + depth(0), + query(5, "aes_pkg"), + // And the climb clamps at the workspace root however high it is asked + // to go — the root's own file is reached, and nothing outside it is. + depth(99), + query(6, "root_pkg"), + query(7, "outside_pkg"), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let hits = |id: u32| -> usize { + let response = messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); + response["result"].as_array().map_or(0, |a| a.len()) + }; + assert_eq!(hits(2), 1, "two levels up from dv/tb is the aes block, rtl and all"); + assert_eq!(hits(3), 0, "and stops there: the block beside it is not in scope"); + assert_eq!(hits(4), 1, "so the testbench's reference into the RTL resolves at once"); + assert_eq!(hits(5), 0, "an explicit 0 is the file's own folder, exactly as before"); + assert_eq!(hits(6), 1, "a depth of 99 climbs to the workspace root"); + assert_eq!(hits(7), 0, "and no further: nothing outside the root is indexed"); + + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&outside); +} + /// index-scope (2026-08-27): the default folder scope over the real wire. /// /// What only an e2e test can settle: that the narrowing is what a *client* @@ -4379,6 +4504,13 @@ fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() { )); let _ = live.wait_for(|m| m["id"] == 1); live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); + // `scopeDepth: 0` — the narrowest rung, and the shipped default until + // 2026-08-28. Asked for out loud so this test stays about the *widen*; + // what the shipped depth covers is + // `the_shipped_scope_depth_reaches_the_block_a_file_belongs_to`. + live.send( + r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scopeDepth":0}}}}}"#, + ); live.send(&open(&top_uri, top_text)); live.send(&definition(2)); @@ -4386,7 +4518,7 @@ fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() { assert_eq!( narrow["result"].as_array().map(Vec::len), Some(0), - "the package is in a sibling folder, which the default scope does not cover: {narrow:#?}" + "the package is in a sibling folder, which depth 0 does not cover: {narrow:#?}" ); // Opening the other file widens the scope and rebuilds — no save, no @@ -5010,6 +5142,13 @@ fn a_jump_into_a_new_folder_indexes_that_folder_and_not_the_ones_before_it() { r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + // `scopeDepth: 0`, asked for out loud: at the shipped depth of 2 the + // first `didOpen` in `blk00/rtl/` would raise to the workspace root + // and index all 24 folders at once, which is a test of the clamp + // rather than of the widen this one is about. + frame( + r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scopeDepth":0}}}}}"#, + ), frame(&open(0, 0)), frame(&open(1, 0)), frame(&open(2, 0)), @@ -5025,15 +5164,16 @@ fn a_jump_into_a_new_folder_indexes_that_folder_and_not_the_ones_before_it() { let messages = talk(&session); let bars = work_per_bar(&messages); - // Four bars: the empty startup scan, then one per widening `didOpen`. The - // fourth `didOpen` is in a folder already covered and asks for none. - assert_eq!(bars.len(), 4, "one bar per widen and no more: {bars:#?}"); + // Five bars: the empty startup scan, the equally empty rescan the + // `scopeDepth` push asks for, then one per widening `didOpen`. The fourth + // `didOpen` is in a folder already covered and asks for none. + assert_eq!(bars.len(), 5, "one bar per widen and no more: {bars:#?}"); assert_eq!( - bars[0], - (vec![], vec![]), - "the startup scan indexes nothing under the folder scope" + bars[..2], + [(vec![], vec![]), (vec![], vec![])], + "neither the startup scan nor the settings rescan indexes anything: nothing is open" ); - for (folder, (read, reused)) in bars[1..].iter().enumerate() { + for (folder, (read, reused)) in bars[2..].iter().enumerate() { // **The round, on the wire.** Each jump reads the 19 disk files of the // folder it opened — `f00.sv` there is the buffer, so it is reused // rather than read — and never the 19, 38 or 57 of the folders reached diff --git a/docs/features/completion-core/README.md b/docs/features/completion-core/README.md index dc359d8..e90c91b 100644 --- a/docs/features/completion-core/README.md +++ b/docs/features/completion-core/README.md @@ -81,9 +81,26 @@ workspace index, from the same file list, and are replaced with it. - **Consumes `vlog_parser`**: `tokenize` for the word harvest, `KEYWORDS` for the keyword tier, `defines::DefineKind` to keep `` `undef`` entries out of the macro table. -- **Consumes `vlog_refactor`** exactly as M4 did — `module_names`, - `module_definition`, `instantiation_plan`, `render_with` — through the - unchanged `module_tier`. Nothing in `vlog_refactor` was touched. +- **Consumes `vlog_refactor`** — `module_definition`, `instantiation_plan`, + `render_with` — through `module_tier`. Nothing in `vlog_refactor` was + touched, then or since. +- **Stopped consuming `vlog_refactor::module_names` (2026-08-28).** That + function is `WorkspaceIndex::workspace_symbols("")` filtered to modules, and + `workspace_symbols` builds and sorts a record per declaration in the whole + workspace — 43 140 of them in opentitan, on *every keystroke*. + `Candidates::modules` is the same list, built once beside the index and + filtered per request, and + `candidates::tests::the_module_table_answers_exactly_what_module_names_answers` + asserts the two agree — set *and* order — at eleven queries. + `vlog_refactor::module_names` is unchanged and still has its own callers; + only tier 0 stopped asking it. **Note for whoever changes it**: the two are + now pinned against each other by that test, so a change to `module_names`'s + match rule or ordering breaks the build rather than silently diverging. +- **Reads `WorkspaceIndex::units`'s `Def::name_span` directly (2026-08-28)**, + to anchor the header slice (`module_header`). Treated as advisory, never as + truth: the byte range is checked against the text actually read, and a + mismatch — a file edited on disk since the last scan — declines the slice + and parses the whole file, exactly as before. - **Duplicated deliberately, not shared**: `vlog_refactor::ports::visible_in` answers "is this *one* name visible here" and is `pub(crate)` to that crate; `completion::visible_symbols` answers "what is visible here". They share the @@ -221,6 +238,74 @@ The one request that is *not* microseconds is a module-item position, which still parses up to 64 defining files. That is M4's cost, unchanged and separately capped. +### The module tier, 2026-08-28 + +That last paragraph was the whole bill. `performance.md` §6d measured +completion at **34–66 ms per keystroke** against opentitan, worst at 0–4 typed +characters, and typing an eleven-character identifier at **201 ms** of blocked +single-threaded loop. The probe +(`perf::completing_one_keystroke_at_a_time`) runs the same request with the +cursor at module-item position and inside an expression, where tier 0 is gated +off: + +| generated corpus, 4 000 files | at an item | in an expression | +|---|---:|---:| +| empty prefix, before | 53.2 ms | 0.19 ms | +| empty prefix, after | **3.17 ms** | 0.19 ms | + +Every other tier put together is 0.19 ms and always was. Two changes, neither +of which may alter an item: + +1. **`module_header` — parse the header, not the file.** A plan reads a + module's parameter list and port list and nothing else, and both are in the + header; the body was being parsed to reach them. The slice is the file's + text up to the `;` that ends the header, **kept byte for byte** so every + span the plan reads still points where it did, with an `endmodule` written + in place of the body. It is anchored on the index's `Def::name_span` + (checked against the text, so a file edited under the index declines rather + than slices at a stale offset) and the end is found by lexing a bounded + window and walking a **whitelist**: `static`/`automatic`, `import …;`, + `#(…)`, `(…)`, `;`. Anything else answers "no slice" and the whole file is + parsed exactly as before — `module aes import aes_pkg::*; #(…) (…);` writes + three semicolons and only the last ends the header, which is why this is a + whitelist and not a search for the first `;`. +2. **`Candidates::modules` — table the module names.** See Handshakes. + +Two guards keep the answer identical, and both are load-bearing rather than +decoration: + +- **A non-ANSI port list writes its directions in the module *body*** + (`module m (a); input wire [7:0] a;`), which is the part the slice drops. A + plan whose ports have neither a direction nor a type is the signature of + that, and `plan_for` re-plans from the whole file when it sees one. + `a_non_ansi_port_list_is_planned_from_the_whole_file` asserts both halves — + that the header alone really does lose them, and that the guard really does + get them back. +- **A slice that fails to plan is re-planned whole**, so the list can only + ever lose an item where it would have lost it anyway. + +`the_header_slice_plans_exactly_what_the_whole_file_plans` is the argument, not +the prose: fifteen header shapes — imports, two imports, no ports, an empty +port list, non-ANSI with and without body declarations, a comment inside the +header, a lifetime qualifier, a directive between the name and the port list, a +directive *inside* the port list, an escaped module and port name, a second +module before and after the one being planned, and a header wider than the +first window rung — each planned both ways and compared field by field. + +`HEADER_WINDOWS` is a ladder because the lex is the whole cost of the slice and +it is linear in what it is handed. The rungs are measured, not guessed: over +opentitan's 344 RTL modules 59% of headers end inside 256 bytes and 90% inside +2 KB, and the largest is 6.6 KB — so a top rung of 16 KB, because a rung that +is too small is not a wrong answer but a 2–4 ms whole-file parse. The full +before/after, including the four `aes_control*` modules that found this, is in +`docs/perf/README.md`, *Before / after — round 7*. + +Against the real checkout, over the wire: **63–66 ms → 13.1–15.0 ms** at the +empty prefix, and typing `aes_reg_top` **200.9 ms → 64.5 ms**. What is left is +64 real header parses, and the two ways down from there — memoizing the plan, +or `completionItem/resolve` — both change something this round was not allowed +to change. They are filed in `docs/perf/README.md`. + ## Version 0.3.0 Every place `tools/RELEASING.md` says the version lives, plus the install @@ -269,9 +354,47 @@ incidental; they exercise the parser, not the version. - [x] Version 0.3.0 across the workspace, the extension and the docs - [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`, `cargo test --workspace` all clean; `smoke.js` OK +- [x] **Performance wave, Lane B (2026-08-28):** completion 34–66 ms per + keystroke → 13–15 ms worst case on opentitan and 3.2 ms on the + same-sized generated corpus, with the items pinned identical. Tier 0 + parses the header instead of the whole declaring file + (`module_header` / `plan_for`), and the module-name list is a table + built with the index (`Candidates::modules`) instead of a + whole-symbol-table sort per keystroke. ## Work log +- **2026-08-28 (dev, performance wave Lane B)** — the module tier. + + Profiled first, as the brief asked, with an `#[ignore]`d house probe rather + than a guess: `perf::completing_one_keystroke_at_a_time` measures the whole + request at nine prefixes with tier 0 on and off. The answer was that + **everything except tier 0 costs 0.19 ms at every prefix**, so + `performance.md`'s hypothesis — "scanning/filtering the candidate set, and + the broader the prefix the more of the 3 976-file symbol table is walked" — + was half right: the symbol-table walk was real but it was + `vlog_refactor::module_names`'s, inside tier 0, not the word or index tiers'. + + What changed is in *The module tier, 2026-08-28* above, with the identity + argument and the fifteen-shape test that carries it. Two decisions worth + naming: + + - **No cache.** The obvious fix is to memoize the plan per module. It was not + taken: `Candidates` is rebuilt at `didSave`, and tier 0 reads + `ws.text_of`, which sees an *unsaved* buffer — so a cache there would go + stale exactly where `another_open_buffer_overlays_disk_once_the_index_is_rebuilt` + says it must not. Slicing needed no new invalidation rule at all, and it + makes the cold request fast rather than only the repeat. + - **The whitelist is a whitelist.** `header_end` refuses every shape it does + not recognise instead of scanning for the first `;`. `module aes import + aes_pkg::*; #(…) (…);` is the case that makes the difference, and it is + what most of opentitan's `aes*` modules are written as: a first-`;` scan + would have silently reported them as having no ports. + + Deviations from the brief: none on this item. The measurement is on + `docs/perf/README.md` rather than here, because that is where this + repository keeps before/after numbers; this section keeps the argument. + - **2026-08-24 (dev)** — implemented. **Keyword list.** `vlog_parser/src/token.rs`'s `is_keyword` was a 181-arm @@ -637,8 +760,128 @@ unambiguous" (typo/missing assertion) territory; all three are judgment calls for the dev/lead. No commits, no edits to `TODO.md` or the umbrella `docs/features/refactor/README.md`. +### 2026-08-28 — QA agent (performance wave Lane B: the module tier) + +Verdict: **the fix holds. No corruption found, one pre-existing parser gap +surfaced (filed below, not fixed here — out of this feature's touched +files).** + +**What I attacked.** The whitelist walk in `header_end`, the guard in +`plan_for`, and `Candidates::modules`'s parity with +`vlog_refactor::module_names`, per the adversarial list in the round brief: +header-slice mis-slicing, stale-span handling, and the module-table's set +*and* order against hostile queries. + +**Header-slice attacks — all safe, one gap in the dev's own test found and +fixed.** Extended `SHAPES` in `completion.rs` (in +`the_header_slice_plans_exactly_what_the_whole_file_plans`) with: a single +`import a::*, b::*;` declaration (comma-chained packages, one statement — +`skip_to_semicolon` must not stop at the first `::`), a parameter default +whose string literal contains a literal `;` and `)` (`"a;b)c"`), CRLF line +endings through the whole header, a genuine attribute instance right after +the module name, and one inside the port list on a single port. All five +plan identically sliced vs. whole-file; the two attribute shapes exposed +something worth recording (next paragraph). Added +`the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously` +(`completion.rs`) asserting the first three actually invoke the slice path +(`module_header(..).is_some()`) rather than passing the comparison +vacuously by both sides falling back to the whole file — a real risk with +this style of pinned-equality test, since a shape the whitelist declines +passes the assertion for free. + +**Finding (LOW, not a regression this round introduced) — `completion.rs`, +`module_header`, and transitively `vlog_semantic`/`vlog_parser`: a module +with an attribute instance (`(* ... *)`) anywhere near its header is not +indexed as a `Module` unit at all.** `WorkspaceIndex::units("attributed")` +and `..("port_attributed")` both come back empty for +`module attributed (* some_attr *) #(...) (...);` and +`module port_attributed (input logic clk, (* keep *) output logic q);`. +`module_header` correctly declines at its very first line (`let [def] = +index.units(module)...else { return None }`, `completion.rs:99-103`) — +this is the documented whole-file fallback working exactly as designed, +not a slicing bug — but it means completion's module tier, which sources +its candidate names from the same index, never offers such a module as a +completion candidate in the first place, attribute-based header or not. +This predates 2026-08-28 (the index-level gap is not something tier 0's +change touches), so it is filed rather than fixed: out of Lane B's stated +files (`vlog_semantic`/`vlog_parser` are not touched-file scope for this +round). Reproduction: `cargo test -p lucisv_server -- completion::tests:: +a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`, a new +permanent regression pinning the current (gap) behavior so a future fix to +the indexer is *noticed* here rather than silently changing what +`module_header` sees. +This also means the dev's own `noisy` shape's doc comment ("a comment and +an attribute inside the header") was inaccurate — it has two comments and +no attribute; I did not edit that comment since fixing it is a one-line +call for the dev, and the actual behavior is now separately pinned above. + +**Stale-span attack**: `a_stale_index_span_declines_to_slice_rather_than_ +slicing_the_wrong_bytes` (dev's own test) re-verified by hand — re-ran with +`cargo test -p lucisv_server -- completion::tests::a_stale_index_span` in +isolation, passes. No addition needed; the test already does the right +thing (name-span-vs-text mismatch declines). + +**`Candidates::modules` parity**: `contains_ignore_case` (`candidates.rs`) +and `contains_ignore_ascii_case` (`vlog_semantic::workspace`) are +byte-identical implementations, and both `Candidates::modules` and +`vlog_refactor::module_names` ultimately filter the same +`workspace_symbols`-sorted, `container.is_none() && kind == Module` slice +with the same predicate — so parity is structural, not incidental, and +holds for any name content (case-different names, escaped identifiers, +duplicate names across files) without needing per-shape tests. Traced by +hand rather than by adding more cases to the dev's own +`the_module_table_answers_exactly_what_module_names_answers` (which +already covers duplicates-across-files and query-case-differences); no +counter-example found. + +**Numbers reproduced** (release build, this machine, M1 Max): +- `perf::completing_one_keystroke_at_a_time`: empty prefix at item position + **3.28 ms** (dev's claim: 3.17 ms — within machine noise), expression + position 190 µs unchanged. Whole-file plan 2.68 ms vs. header-alone + 16.3 µs for one skeleton off the 1214-line generated file — matches the + claimed order of magnitude. +- `LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test + --release -p lucisv_server perf::completing_over_a_real_project`: empty + prefix **11.6 ms** (dev's claim against the real wire protocol: 13.1–15.0 + ms; this is the in-process `completions()` call without LSP round-trip + overhead, so a bit faster is expected, same order of magnitude). Zero + modules fell back to whole-file parsing across every prefix tested + (`parsed whole: []`), confirming the slice fires in practice on real RTL, + not just in the synthetic corpus. +- Live end-to-end confirmation against the real opentitan checkout with + this worktree's release binary (`node`-free, via a copy of the + scratchpad's `lspclient.py`/`bench.py` pointed at + `target/release/lucisv-server`): completion itself was not re-measured + over the wire (out of scope to re-run the whole battery), but see the + references-nav QA log below for the documentHighlight leg of the same + session, which used the identical harness. + +**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test +--workspace` (1261 passed, up from 1259 with my additions), `node +editors/vscode/smoke.js target/release/lucisv-server` — all clean, run +against the worktree with my additional tests included. + +No fixes applied beyond the two new permanent regression tests (attack +shapes actually slicing; the attribute-indexing gap pinned). No commits. + ## Review +**2026-08-28 — lead, performance-wave Lane B.** Reviewed after QA's +SHIP; gates re-run on the worktree (fmt clean, clippy silent, 2495 +workspace tests green). The header-slice design is right because of +what it refuses: a whitelist walk that re-plans from the whole file on +anything it does not positively recognize — including the non-ANSI +signature — is the honest shape, and QA's seven added attack shapes +plus the field-by-field plan-equality pin make the "items byte +identical" claim tested rather than asserted. The stale-span decline +and the Candidates::modules order-and-set parity are correctly pinned. +QA's LOW (attribute-instance modules not indexed as units — a +pre-existing parser/semantic gap the guard already declines safely) is +accepted as filed with its regression pin; it belongs to a parser +round, not this one. The residual opentitan cost is real header +parses, with the plan-cache and completionItem/resolve options filed +where the numbers are. Accepted. + **2026-08-24 — lead.** Reviewed after QA's ship verdict — the first milestone through with no rework round; gates run independently (1262 tests, 0 failures, clippy silent). The keyword-table refactor was verified diff --git a/docs/features/index-scope/README.md b/docs/features/index-scope/README.md index b59870f..2b7684b 100644 --- a/docs/features/index-scope/README.md +++ b/docs/features/index-scope/README.md @@ -28,6 +28,29 @@ that is provably a reporting decision with no effect on the index. (3) the default: the folders the open buffers live in, each raised `lucisv.index.scopeDepth` levels, walked. Rung 2 needs a root to mean anything, so a rootless session is folder-scoped whatever it says. +- **The default depth is 2, changed from 0 on 2026-08-28.** This is a + behaviour change and it is in the release notes. The measurement that forced + it is `performance.md` §4: on the shipped default, opening + `hw/ip/aes/dv/tb/tb.sv` in opentitan gave an index of **exactly one file** — + `dv/tb/` holds only `tb.sv` — so `definition`, `typeDefinition`, `hover`, + `references`, `workspace/symbol` and `signatureHelp` **all answered nothing** + until some later jump widened the scope. The narrow rung's sub-0.1 ms + timings were not a speed result; they were the cost of answering nothing, and + the user's first experience of the server was silence. + + Two levels is the smallest raise that turns a `dv/tb` or an `rtl` file into + the IP block it belongs to (`hw/ip/aes` — rtl and dv together, a few hundred + files), which is the unit an engineer actually works in. Three would be the + whole of `hw/ip`. Measured on an opentitan-shaped tree by + `perf::what_the_scope_depth_default_costs`: depth 0 indexes **1** file, depth + 2 indexes **21** for 15 ms of scan, depth 3 indexes **252** for 185 ms. What + keeps 2 bounded is everything this feature already has — the size cap, the + persistent cache, the interleaved scan and the incremental widen — and the + root clamp, which is why the rootless case is treated separately below. + + `scopeDepth: 0` still means exactly what it always meant, and is the way back + to the old behaviour for anyone who wants it + (`e2e::the_shipped_scope_depth_reaches_the_block_a_file_belongs_to`). - **This is a behaviour change for every workspace user, and the honest statement of it is that cross-file answers are scope-relative.** A symbol in a folder the scope has not reached does not exist as far as this server is @@ -68,21 +91,32 @@ that is provably a reporting decision with no effect on the index. makes it a scope directory; what it does change immediately is how far the climb may go (see below). Removing one likewise only loosens the clamp. The rescan `didChangeWorkspaceFolders` already triggers is unchanged. -- **The climb is clamped at the deepest workspace root containing the - directory** — that is what keeps `scopeDepth: 5` in a two-deep project from - indexing a home directory. **With no root there is nothing to clamp against - and the only floor is `/`**: the loop terminates there rather than spinning, - and the setting means exactly what it says. The rootless default is 0, so - nobody reaches this without asking for it; it is called out in the setting's - own description. -- **The rootless case is unchanged at the default.** A file opened on its own, - at depth 0, still gets a flat one-level read of its directory — no walk, no - `.gitignore` — - (`with_no_workspace_root_the_open_files_own_directory_is_indexed`, untouched - this round). The moment a rootless session raises `scopeDepth` it has named - a tree, so the raised directory is walked instead; that is the one place the - rung's behaviour depends on the depth being non-zero, and it is what stops a - raise from *losing* the file's own siblings. +- **The shipped `scopeDepth` is 2 (2026-08-28), and the climb is clamped at + the deepest workspace root containing the directory** — that is what keeps + `scopeDepth: 5` in a two-deep project from indexing a home directory, and it + is what makes a non-zero default safe at all. See *The default depth* below + for why it moved off 0. +- **With no workspace folder there is no climb.** The clamp is the whole + reason a raise is safe, and a rootless session has nothing to clamp against. + Until 2026-08-28 the climb ran with `/` as its only floor, which was + survivable while the shipped depth was 0 and nobody climbed by accident; at + depth 2 a lone file opened from `~/work/chip/hw/ip/aes/rtl/` would raise into + `~/work/chip/hw/ip/` and walk a tree the user never named. So `raised` + returns the directory unchanged when `roots` is empty, whatever the depth + says. Pinned by `a_rootless_session_does_not_climb_at_all` at depths 0, 1 + and 99. **This removes a capability**: a rootless session can no longer widen + by raising `scopeDepth`. The way to widen is to open the folder, which is + also what gives the climb a floor. +- **The rootless case still reads flat at depth 0.** A file opened on its own, + at `scopeDepth: 0`, gets a flat one-level read of its directory — no walk, no + `.gitignore` + (`with_no_workspace_root_the_open_files_own_directory_is_indexed`). At any + higher depth the *directory* is the same one (no climb, above) but it is + **walked** rather than read flat, so the subtree under the file's own folder + is indexed. That is the one behaviour a rootless user sees change with the + new default, it is bounded by the directory they opened a file from, and it + is pinned by + `a_rootless_session_reads_its_own_directory_flat_until_the_depth_is_raised`. - **One honest filter gap: a root's `.gitignore` does not reach a walk that starts below it.** `lucisv_core::walk` reads ignore files from the walk's own starting directory downwards, so a rule written at the workspace root is not @@ -325,11 +359,19 @@ rule kept rather than a case reached. `reindex_widened` defers to ### `lucisv_server::settings` - Two new fields, `index_scope: IndexScope` (`Folder` | `Workspace`, default - `Folder`) and `index_scope_depth: u64` (default 0), parsed from - `lucisv.index.scope` / `lucisv.index.scopeDepth`. Nested under `index` like - the other two, so both settings doors — push and pull — carry them with no - new code (`the_index_settings_come_through_the_pull_door_too`). + `Folder`) and `index_scope_depth: u64` (default + `settings::DEFAULT_SCOPE_DEPTH`), parsed from `lucisv.index.scope` / + `lucisv.index.scopeDepth`. Nested under `index` like the other two, so both + settings doors — push and pull — carry them with no new code + (`the_index_settings_come_through_the_pull_door_too`). - `IndexScope` is public; `state.rs` matches on it. +- **`DEFAULT_SCOPE_DEPTH` is the single source of the shipped depth + (2026-08-28)**, used by `ClientSettings::default` and by the `unwrap_or` in + `from_payload`, so an unreadable value falls back to the shipped default like + every other setting here rather than to zero. + `the_extensions_declared_defaults_are_the_ones_this_module_ships` reads + `editors/vscode/package.json` and asserts the settings UI declares the same + number, so the two cannot drift. ### `lucisv_server::state` @@ -370,8 +412,8 @@ rule kept rather than a case reached. `reindex_widened` defers to - [x] `lucisv.index.scope` (`"folder"` default, `"workspace"` opt-in), both settings doors, junk → the narrow default -- [x] `lucisv.index.scopeDepth` (default 0), clamped at the deepest containing - workspace root, and at `/` with no root +- [x] `lucisv.index.scopeDepth`, clamped at the deepest containing workspace + root — **default 2 since 2026-08-28**, and no climb at all with no root - [x] Filelist still outranks both; `scope`/`scopeDepth` ignored on rungs 1–2 - [x] `didOpen` widens the scope and reindexes; the rootless branch unified into the same rule @@ -385,6 +427,27 @@ rule kept rather than a case reached. `reindex_widened` defers to - [x] 19 new tests (12 state, 2 server, 1 e2e, 2 vlog_semantic, 2 settings), 3 existing ones extended, 1 superseded test rewritten; every other test in the crate that wanted the whole workspace now says so +### Round 21 — the shipped `scopeDepth` moves 0 → 2 (2026-08-28) + +- [x] `settings::DEFAULT_SCOPE_DEPTH`, used by `ClientSettings::default` and + by `from_payload`'s fallback +- [x] `editors/vscode/package.json`: the declared default and a rewritten + `markdownDescription`, with the single-file advice corrected +- [x] `the_extensions_declared_defaults_are_the_ones_this_module_ships` — the + manifest and the server are asserted to agree, so they cannot drift +- [x] Ladder tests: the shipped depth reaches the block, the climb clamps at + the workspace root and goes no further, an explicit `0` is unchanged + (`e2e::the_shipped_scope_depth_reaches_the_block_a_file_belongs_to`) +- [x] The rootless climb removed, with its own two tests + (`a_rootless_session_does_not_climb_at_all`, + `a_rootless_session_reads_its_own_directory_flat_until_the_depth_is_raised`) +- [x] Cost delta measured rung by rung on a synthetic opentitan-shaped tree + (`perf::what_the_scope_depth_default_costs`): 1 / 1 / 21 / 252 files at + depths 0 / 1 / 2 / 3 +- [x] Every test in the crate whose subject is the *depth-0 rung* now asks for + it out loud (`state::tests::own_folder_only`) instead of riding the + default + ### Round 19 — a rescan stops re-parsing what is already analyzed (2026-08-28) - [x] Traced where a scope-widening `didOpen`'s 213 ms actually goes, per stage, @@ -466,6 +529,55 @@ rule kept rather than a case reached. `reindex_widened` defers to ## Work log +### 2026-08-28 — dev agent (the shipped `scopeDepth` moves 0 → 2) + +**A behaviour change, lead-decided, and it belongs in the release notes.** The +rationale and the numbers are in *Assumptions → The default depth*; this is +what was done and what it cost. + +The default lives in **one** place, `settings::DEFAULT_SCOPE_DEPTH`, read by +`ClientSettings::default` and by `from_payload`'s `unwrap_or` — so a +wrong-typed `scopeDepth` now falls back to the shipped default rather than to +zero, which is the same direction every other setting in that function already +falls. `editors/vscode/package.json` declares the same number, and +`the_extensions_declared_defaults_are_the_ones_this_module_ships` reads the +manifest and asserts it, because a hand-written mirror that drifts proves +nothing. + +**The one thing that had to change beyond a constant: the rootless climb.** +`raised()` had no floor without a workspace root — the loop stopped at `/`. +That was defensible while the shipped depth was 0 (nobody climbed unless they +asked), and indefensible at 2: opening one loose file would have raised two +levels into a tree the user never named and walked it. `raised()` now returns +the directory unchanged when `roots` is empty. This **removes a capability** — +a rootless session can no longer widen by raising the depth — and the two +tests that pinned the old climb were rewritten rather than deleted, so the new +rule is asserted at depths 0, 1 and 99 instead of assumed. The setting's +description already told single-file users to leave it at 0; now the server +does that for them. + +Consequence, stated rather than discovered: a rootless session at the new +default still finds its own directory, but **walks** it instead of reading it +flat, because `folder_files`'s flat-read exception is still keyed on depth 0. +Bounded by the one directory the user opened a file from, so it was left as +the simpler rule; `e2e::with_no_workspace_folder_the_open_files_own_directory_is_indexed` +carries the new expectation and says why. + +**Test fallout, and how it was handled.** Nineteen tests across `state.rs`, +`server.rs` and `e2e.rs` asserted the *depth-0 rung* while spelling only +`ClientSettings::default()`. Every one of them is about the narrow rung rather +than about whatever the default happens to be, so each now says `0` out loud — +`state::tests::own_folder_only` for the unit tests, a `didChangeConfiguration` +push for the two wire tests. That is a better test either way: none of them +now moves when a default moves. The one test that really was about the default +was renamed (`the_folder_scope_at_depth_zero_is_...`) and a new one written for +the shipped depth. + +**Files touched outside this feature's usual set**, flagged for the merge: +`state.rs` (one production line in `raised`, plus the test-fixture updates +above) and `server.rs` (two test premises). Both are test-shaped except that +one line. + ### 2026-08-27 — dev agent (open-file-first indexing, folder-scoped walk) - **The builder was hardened first, because the ordering change depends on @@ -1341,8 +1453,107 @@ new log word all check out. The one real finding (stack depth) predates this round, affects both compared routes identically, and is filed as a follow-up rather than a blocker. +### 2026-08-28 — QA agent (round 21: the shipped `scopeDepth` moves 0 → 2) + +Verdict: **SHIP.** No scope silently grew or shrank outside what round 21 +documents; the one production line outside this feature's usual file set is +confirmed minimal and correctly scoped. + +**Single source of truth, verified.** `DEFAULT_SCOPE_DEPTH` (`settings.rs`) +is the only place `2` is written for this purpose: `ClientSettings::default` +and `from_payload`'s `unwrap_or` both read it, `editors/vscode/package.json` +declares the same `2` and is locked against drift by +`the_extensions_declared_defaults_are_the_ones_this_module_ships` (read the +manifest as JSON, don't hand-copy it) — re-ran this test standalone, passes, +and hand-verified the manifest file itself still says `2` after the round's +edit (`editors/vscode/package.json:249`). + +**Explicit-0 and junk-value attacks.** `the_scope_depth_is_two_until_a_client_ +says_otherwise` (dev's test, re-run and re-read): an explicit `scopeDepth: 0` +comes back as `0`, not defaulted — confirmed correct by reading `from_payload` +(`settings.rs:229-234`): `count(...)` parses the JSON number `0` successfully +via `Option`, so `unwrap_or(DEFAULT_SCOPE_DEPTH)` only fires when `count` +itself returns `None` (missing key or wrong JSON type), never for a +successfully-parsed `0`. The six junk values (`-1`, `1.5`, `"2"`, `true`, +`null`, `[2]`) all fall to `DEFAULT_SCOPE_DEPTH`, not to `0` — matches the +"an unreadable value must never be the reason a user's index is narrower than +the server promised" comment in `from_payload`, and is the correct direction +(a typo'd config should not silently narrow a user back to the pre-2026-08-28 +default). + +**Clamp attacks.** `the_climb_stops_at_the_workspace_root` (pre-existing, +still green) covers depth 99 against nested roots; traced `raised()` +(`state.rs:670-683`) by hand for depth 2 from the workspace root itself (the +`floor` is the root's own parent-chain search, which for a file *at* the root +finds `dir == floor` immediately — climbs zero levels, matches root) and from +one level below root (climbs one level, hits the floor, stops) — both are +degenerate cases of the existing clamp loop, not special-cased, so no new +attack surface. No regression test added here since the existing clamp tests +already exercise the loop generically over depth. + +**Rootless no-climb rule — the flagged production line.** `raised()` +(`state.rs:670`) now returns `dir.to_path_buf()` unchanged when `self.roots. +is_empty()`, before running the climb loop at all. Grepped every caller of +`raised(` and every `roots.is_empty()` site in `state.rs`: `raised` has +**exactly one** call site (`scope_dirs()`, line 633), so the change cannot +reach any other path indirectly. Two *other*, independent +`roots.is_empty() && index_scope_depth == 0` checks exist +(`state.rs:1075` `widened_files`, `state.rs:1688` `folder_files`) — these gate +the separate "read flat instead of walk" exception and are keyed on depth +being exactly `0`, not on whether `raised()` climbs, so they are unaffected by +this change and correctly produce the dev's documented consequence: a +rootless session at the new default (2) finds only its own directory (no +climb) but *walks* it rather than reading it flat (since the flat-read +exception no longer matches at depth 2). Confirmed with a direct read of both +call sites rather than by inference alone. +**No other path was found to depend on the old rootless-climbs-to-`/` rule.** +The two rewritten tests (`a_rootless_session_does_not_climb_at_all`, +covering depths 0/1/99; `a_rootless_session_reads_its_own_directory_flat_ +until_the_depth_is_raised`, covering depths 0/1) between them cover +everything the two deleted tests covered (termination, and the flat-vs-walk +split) minus only the removed capability itself (a rootless session widening +by raising the depth) — confirmed by diffing the old and new test bodies +line by line rather than by the dev's own characterization. + +**Cost delta reproduced.** `cargo test --release -p lucisv_server +perf::what_the_scope_depth_default_costs -- --ignored --nocapture +--test-threads=1`: + +``` +depth 0: 1 files indexed, 5 index names, scan 532.583µs +depth 1: 1 files indexed, 5 index names, scan 342.666µs +depth 2: 21 files indexed, 25 index names, scan 15.6445ms +depth 3: 252 files indexed, 256 index names, scan 183.902708ms +``` + +Matches the dev's claimed 1/1/21/252 files exactly, and the round brief's +"21 files / 15 ms at depth 2" (15.6 ms here, same machine-noise band). + +**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test +--workspace` (1261 passed — includes my additions to `completion.rs` and +`nav.rs` from the same session; this feature's own tests are unchanged and +green), `node editors/vscode/smoke.js target/release/lucisv-server` — clean. + +No fixes applied; no new tests needed in this feature's own files (the +existing round-21 test suite already covers what I attacked). No commits. + ## Review +### 2026-08-28 — lead, performance-wave Lane B (scope default) + +The scopeDepth 0 → 2 default is the lead's own decision implemented +faithfully: single-source constant, manifest locked by test, explicit +0 byte-identical, junk values falling to the shipped default, and the +cost measured (21 files / 15 ms on the opentitan-shaped tree — the +trap's fix costs a keystroke's worth of scan). The one production line +in state.rs (rootless sessions no longer climb) is the right call, not +just an allowed deviation: an unclamped climb from a loose file was a +latent walk of an unnamed tree, and the capability it removes — +depth-raising with no workspace open — protected nothing a rootless +session can actually name. QA verified the single call site and the +rewritten pins. Behavior change goes in the CHANGELOG at release. +Accepted. + ### 2026-08-28 — lead, incremental-widen round Reviewed the full diff; gates run by the lead twice (fmt clean, clippy diff --git a/docs/features/references-nav/README.md b/docs/features/references-nav/README.md index 4c4023c..17aaa40 100644 --- a/docs/features/references-nav/README.md +++ b/docs/features/references-nav/README.md @@ -47,6 +47,12 @@ predicate, and three handlers. be paired with different bytes; an open file contributes live spans instead. Location conversion fetches and line-indexes each touched file once, however many occurrences it contains. +- **`documentHighlight` is a *document* answer even for a cross-file name** + (2026-08-28). The cursor on an instantiated module, or on a `.port` in a + connection list, highlights that name's uses **in this file** — the workspace + overlay is consulted to learn *which declaration* the cursor names, never to + widen the answer past the buffer. So the same position can answer 1 here and + 7 to `references`, and both are right. - **Read/write is not distinguished** in `documentHighlight`. LSP permits a plain `Text` kind, and telling a read from a write in Verilog means classifying continuous vs. procedural assignment, port direction and @@ -140,6 +146,20 @@ decision. ## Status / TODO +- [x] **`documentHighlight` answered nothing on a cross-file name + (2026-08-28, performance wave Lane B):** `performance.md` §7 reported it + returning 0 results at *every* opentitan position tried — the `aes` + instantiation, the `.clk_i` port connection, at both scopes, before and + after a widen — while `references` at the same positions returned 7 and + 10. **Not a benchmark mistake: a real bug**, reproduced in a five-line + fixture and fixed. Root cause and the argument are in the work log + below; the regression tests are + `nav::tests::a_cross_file_name_highlights_its_uses_in_this_file` and, over + the wire at the same two positions, + `e2e::cross_file_references_folding_and_highlights_round_trip_over_the_wire` + ids 6 and 7. Still fast now that it answers: **0.05–0.15 ms** against the + 0.03–0.12 ms it took to answer nothing. + - [x] **References latency with a big buffer open (2026-08-28):** measure both directions of a cross-file references request while a 1.4 MB, 40 000-line `top.sv` is an open document, then fix what the numbers convict. Landed: @@ -210,6 +230,54 @@ decision. ## Work log +### 2026-08-28 — documentHighlight answered nothing on a cross-file name + +**The report.** `performance.md` §7: `documentHighlight` returned 0 results at +every opentitan position tested, while `references` answered at the same +positions. It was fast because it was doing nothing, which is the kind of +result a benchmark that only times things rewards. + +**Reproduced first, in five lines.** A `top.sv` that instantiates a `sub` +declared in another file, with two instantiations and a `.clk_i` connection on +each. `references` at the module name answered 3; `document_highlights` at the +same byte answered `None`. That is +`a_cross_file_name_highlights_its_uses_in_this_file`, written to fail before +anything was changed. + +**Root cause.** `document_highlights` asked `symbol_at`, which is +`Semantics::reference_at(offset).resolved()` or `Semantics::symbol_at(offset)` +— **both of them single-file questions**. A name this file *uses* but does not +*declare* has no in-file symbol at all: `analyze` records the use as an +external candidate and leaves it to the workspace layer, so `reference_at` +resolves to nothing and `symbol_at` finds no declaration. An instantiated +module's name and a `.port` in a connection list are exactly that shape, and +they are most of what a cursor lands on in a testbench. + +`references` never had the bug because it reads `doc.external` — the workspace +overlay — through `leaves_this_file`/`indexed_target`. The two handlers were +answering the same question from different halves of the same document, and +only one half had been wired up. The existing highlight tests all used a +signal declared in the file under test, which is why the suite was green. + +**The fix**, `nav::external_occurrences`: when `symbol_at` finds nothing, ask +the overlay for the reference at the cursor, and if the workspace answered it, +collect every reference in *this* file that spells the same name and that the +overlay answered the same way. Same-name-and-same-answer rather than +same-name: two uses of `clk_i` that resolve into different modules are +different symbols, and comparing the whole `defs()` slice rather than its +first entry keeps two *ambiguous* uses together only when they are ambiguous +between the same declarations. A use the index cannot answer is still left +alone, so the editor keeps its own word highlighting — the contract the rest +of the function already honours. + +It stays a **document** highlight: one file's occurrences, which is why the +opentitan `aes` position now answers 1 where `references` answers 7. That is +not a smaller answer to the same question; `tb.sv` instantiates `aes` once. + +Nothing outside `nav.rs` changed — the handler in `server.rs` already had the +document in hand, and `Document::external` is already beside `Document:: +semantics`, so no signature moved. + ### 2026-08-28 — references latency with a big buffer open The owner reported find-references from a *use site* in a big open `top.sv` @@ -858,8 +926,108 @@ dev's original shape plus exactly my one addition. TODO.md discrepancy) left for the lead to reconcile — neither is a correctness or safety issue in the shipped feature. +### 2026-08-28 — QA agent (performance wave Lane B: the documentHighlight fix) + +Verdict: **the fix is correct and holds under attack. One genuine behavioral +divergence from `references` found and recorded (not a bug, but the lead +should see it before calling the two "cross-checked").** + +**Reproduced the original bug, live.** Built this worktree's release binary, +pointed a copy of the scratchpad's `lspclient.py`/`bench.py` harness at it +(`SERVER` edited to `target/release/lucisv-server`, `ROOT` unchanged at +`/Users/guoliangchen/repo/opentitan`), and ran `bench.py nav workspace -` +against the real checkout: `documentHighlight(aes)` and +`documentHighlight(.clk_i)` now each return **1 result** (the `tb.sv`-local +occurrence — correctly fewer than `references`'s 7/10, since `references` +is workspace-wide and highlight is this-file-only by contract), where +`performance.md` §7 recorded 0. Confirms the fix end-to-end, not just in +the unit suite. + +**Attacked the grouping logic (charter item 4) with three new permanent +tests in `nav.rs`:** + +1. `an_ambiguous_instantiation_highlights_where_references_gives_up` — two + files both declare `module dup`, instantiated twice in a third file. + `document_highlights` correctly groups both instantiations (same + ambiguous def set). **Finding, not a bug**: `references` at the same + position returns *empty*, not the same answer — traced to + `indexed_target` (`nav.rs`), which only builds an `IndexedTarget` from + `Definition::External([def])`, exactly one candidate; an ambiguous + external use (2+ candidates) makes it return `None`, so `references()` + falls through to `in_file_references`, which requires a *local* symbol + (`symbol_at`) that an external use does not have — net empty, and this + is pre-existing, unrelated to this round. `document_highlights`'s new + `external_occurrences` has no such restriction: it groups by the + overlay's whole answer, ambiguous sets included. This is a genuine + divergence from "highlights == references-in-this-file at the same + position", though arguably the *better* behavior (answering something + reasonable beats forcing the editor's own word-highlighter to fall back + to nothing) — recorded per the charter's instruction to cross-check + rather than assumed away. +2. `two_uses_ambiguous_between_different_def_sets_do_not_group` — the sin + the charter names directly. Building this took two attempts: my first + version used two module-scope `import p1::*; import p2::*;` wildcards + expecting position-scoped ambiguity, and it failed — both usages grouped + together (lines `[3, 5]` where I expected `[3]` and `[5]` separately). + Root cause, traced through `bind.rs::bind_module` / + `follow_paths`/`follow_one`: imports are collected per-scope and tried + *in declaration order*, and `follow_paths` returns on the **first** path + with any answer — so multiple wildcard imports of packages that each + independently declare the same member never produce a multi-package + `Ambiguous`; each reference resolves against whichever imported package + is tried first. Real ambiguity comes from **duplicate declarations of + the same entity** (two files declaring the same module/package), not + from multiple distinct wildcard imports. Rebuilt the test around two + *different* modules (`dup_a`, `dup_b`), each duplicated across two + files, both exposing a port named identically (`same_port`) and + connected in the same top module — same `reference.name`, disjoint + ambiguous def sets (`dup_a`'s two files vs. `dup_b`'s two files). Passes: + the two connections do not group. This is the test that actually proves + `external_occurrences`'s `defs()` comparison (not just the name match) + is load-bearing. +3. `an_unanswered_external_use_declines_rather_than_guessing` — an import + of a package the workspace does not declare, and a member reference the + overlay cannot place. `document_highlights` returns `None` (declines), + confirming the empty-`defs()` early-out and preserving the editor's + own word-highlighting fallback. + +**Cross-file name collision (charter item 4, "local at one position, +external at another")**: traced by hand rather than by a new test — +`external_occurrences` only ever matches a candidate occurrence through +`doc.external.get(at)`, which is populated only for references the +workspace overlay actually resolved (`resolve_external`, +`vlog_semantic::workspace`); a same-spelled local declaration/use has no +entry there, so `None == Some(target.defs())` excludes it automatically. +No counter-example found. + +**Reference-id indexing**: confirmed `ReferenceId(i)` in +`vlog_semantic::lib.rs` corresponds exactly to index `i` in +`Semantics::references()`'s backing `Vec` (`self.references.get(id.0 as +usize)`), so `external_occurrences`'s `enumerate()` + `ReferenceId(*at as +u32)` round trip is not an off-by-one risk. + +**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test +--workspace` (1261 passed), `node editors/vscode/smoke.js +target/release/lucisv-server` — all clean, run against the worktree +including my three additions. + +No fixes applied to feature code — the fix is correct as shipped. Three +permanent regression tests added to `nav.rs`. No commits. + ## Review +**2026-08-28 — lead, performance-wave Lane B (documentHighlight).** +The zero-results report was a real bug with a clean root cause: both +cursor questions were single-file, so a name this file uses but does +not declare had no answer, and every existing test used a declared +name. The fix reads the overlay and groups by the whole defs() slice — +the conservative equality — and was written failing-first with the two +exact opentitan positions pinned over the wire. QA's INFORMATIONAL +asymmetry (highlight answers on a globally-ambiguous target where +references declines) is pre-existing, arguably correct — a highlight +is file-local and read-only — and is now recorded here rather than +discovered again. Accepted. + **2026-08-28 — lead, references-latency round.** Reviewed after QA's clean SHIP; gates re-run independently (fmt clean, clippy silent, 2407 workspace tests green). Measure-first discipline held: the probes were diff --git a/docs/perf/README.md b/docs/perf/README.md index 0229e44..872ded4 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -441,6 +441,128 @@ The last row is the follow-up this round did not take: a rename must see every file that could name the symbol, so its subset is a different argument. It is sent when the user presses the rename key, not per cursor move. +## Before / after — round 7, Lane B (2026-08-28) + +`performance.md` §6d: `textDocument/completion` cost **34–66 ms and fired on +every keystroke**, worst at 0–4 typed characters — the beginning of every +identifier. Typing `aes_reg_top` one character at a time cost **201 ms** of +blocked single-threaded loop. The report guessed the cost was "scanning the +3 976-file symbol table"; the probe says otherwise. + +**Where it actually was.** `perf::completing_one_keystroke_at_a_time` runs the +same request at the same prefixes with the cursor at module-item position +(every tier runs) and inside an expression (tier 0 is gated off). Over a +generated corpus of 4 000 files: + +| prefix | at an item, before | in an expression (no tier 0) | +|---|---:|---:| +| `` (empty) | 53.2 ms | 0.19 ms | +| `aes_` | 49.7 ms | 0.19 ms | + +Everything that is not tier 0 — the index tier, the word tier, the scope +gates, building and serialising 512 items — is **0.19 ms**. The whole cost was +**tier 0, the module skeletons**: up to 64 per keystroke, each one a read of +the declaring file and a `parse_source_tolerant` over **all** of it, to read a +header a few hundred bytes long. One skeleton off a 1 214-line file: 2.71 ms +of parse for 16 µs of planning. + +Two changes, both of which must leave the items byte-identical (pinned by +`completion::tests::the_header_slice_plans_exactly_what_the_whole_file_plans` +and `candidates::tests::the_module_table_answers_exactly_what_module_names_answers`): + +1. **Parse the header, not the file.** `completion::module_header` slices the + declaring file at the `;` that ends the module header — anchored on the + index's own `name_span`, found by lexing a bounded window, and refused + outright for any header shape it does not recognise. The prefix is kept + byte for byte so every span the plan reads still points where it did. +2. **Table the module names.** Tier 0 asked `vlog_refactor::module_names`, + which calls `WorkspaceIndex::workspace_symbols("")` — building and sorting + a record per declaration in the workspace, **per keystroke**. + `Candidates::modules` is that list, built once beside the index. + +| generated corpus, 4 000 files of 1 200 lines | before | after | +|---|---:|---:| +| completion at the empty prefix | 53.2 ms | **3.17 ms** | +| at `a` | 52.4 ms | **3.14 ms** | +| at `aes_` | 49.7 ms | **3.26 ms** | +| at `aes_0001` (1 item) | 0.31 ms | **0.017 ms** | +| one skeleton: `instantiation_plan` over the whole file | 2.71 ms | — | +| one skeleton: over its header alone | — | **16.5 µs** (slicing it: 7.1 µs) | + +Over the real checkout, driven through the shipped binary with +`performance.md`'s own client (3 976 files, workspace scope, warm): + +| request | before (`performance.md` §6d) | after | +|---|---:|---:| +| completion, empty prefix | 63–66 ms | **13.1–15.0 ms** | +| completion, `a` | 58–61 ms | **13.2–13.5 ms** | +| completion, `aes_` | 35 ms | **15.0–15.7 ms** | +| completion, `prim_` | 16–19 ms | **5.8–6.9 ms** | +| completion, `clk` | 5.7–6.0 ms | **2.4–2.8 ms** | +| completion, `aes_reg` | 5.0 ms | **0.32–0.69 ms** | +| completion, `zzzz` | 1.4–2.0 ms | **0.06–0.31 ms** | +| typing `aes_reg_top`, 11 keystrokes | **200.9 ms** | **64.5 ms** | + +**The generated corpus is 3.2 ms and the real one is 13 ms, and the difference +is real rather than noise.** `perf::completing_over_a_real_project` — the same +measurement pointed at whatever `LUCISV_PERF_CORPUS` names, skipped when it is +unset — breaks tier 0's remaining bill down over opentitan's own modules: + +| prefix | modules planned | read each | slice each | plan each | +|---|---:|---:|---:|---:| +| `` (empty) | 64 | 16.8 µs | 62.2 µs | 68.2 µs | +| `aes_` | 59 | 15.0 µs | 63.8 µs | 101.6 µs | +| `prim_` | 64 | 12.3 µs | 23.5 µs | 19.2 µs | +| `clk` | 34 | 2.1 µs | 0.7 µs | 1.1 µs | + +opentitan's headers are simply bigger: `aes_control_fsm_n`'s is 6.6 KB of +commented ports. That measurement is also what set `HEADER_WINDOWS`: at the +first ladder tried (top rung 4 KB) four of the 64 `aes*` modules overflowed it +and paid a whole-file parse of a 24–52 KB file — 10 ms of the 12. Raising the +top rung to 16 KB removed every fallback and cost the common case nothing, +because the common header still ends inside the first 256-byte rung (59% of +opentitan's 344 RTL modules do). + +**What is left, and why it was not taken.** ~10 ms of a worst-case opentitan +completion is 64 real header parses, and the items are required to be +identical, so the only ways down are a cache or a protocol change: + +- memoize the plan per (module, index generation) — correct only if the cache + is dropped on every unsaved edit to a declaring buffer, which + `Candidates` currently is not (it is rebuilt at `didSave`), so it would need + a new invalidation rule rather than an existing one; +- `completionItem/resolve`: send tier 0's items with labels only and compute + the skeleton on the lightbulb — ~0 ms per keystroke, but it changes what the + first response contains and needs `resolveProvider` in the capabilities. + +Both are the same shape as the deferred `codeAction/resolve` item in +`TODO.md` §10 and belong with it. + +**`documentHighlight`, `performance.md` §7 — a functional bug, not a perf +one.** It answered 0 results at every position tried while `references` +answered 7 and 10 at the same positions. Root cause and fix are in +`docs/features/references-nav/README.md`; the number here is only that it is +still fast now that it answers: **0.05–0.15 ms** against the 0.03–0.12 ms it +took to answer nothing. + +**The scope-depth default, `performance.md` §4.** The shipped +`lucisv.index.scopeDepth` moves 0 → 2. +`perf::what_the_scope_depth_default_costs` measures every rung over an +opentitan-shaped tree (12 blocks of 20 `rtl/` files plus a `dv/tb/` file, the +buffer opened three levels down): + +| depth | files indexed | index names | scan | +|---:|---:|---:|---:| +| 0 | **1** | 5 | 0.6 ms | +| 1 | 1 | 5 | 0.3 ms | +| 2 | **21** | 25 | 15.0 ms | +| 3 | 252 | 256 | 185.0 ms | + +Depth 0 reproduces the trap exactly: one file indexed, so every cross-file +answer is empty. Depth 2 is the block the file belongs to — 21 files for 15 ms +of scan, once — and depth 3 is the whole of `hw/ip`, which is why the default +is 2 and not 3. + ## What it would take to go faster Ranked by what the measurements above say is there, with what each would @@ -528,10 +650,20 @@ cost. None of these were attempted; each is a future round. 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. +- [x] **Round 1's last "not measured", closed for completion (round 7, + 2026-08-28):** `perf::completing_one_keystroke_at_a_time` measures the + whole request at nine prefixes, in both positions that gate tier 0, over + a 4 000-file corpus — which is how the cost was found to be tier 0 and + not the symbol table `performance.md` suspected. + `perf::completing_over_a_real_project` does the same over a corpus named + by `LUCISV_PERF_CORPUS`, and skips when it is unset. +- [x] **Added in round 7 (2026-08-28):** what the shipped + `lucisv.index.scopeDepth` costs and buys, rung by rung, on an + opentitan-shaped tree (`perf::what_the_scope_depth_default_costs`). +- [ ] Not measured: signature help and semantic tokens end to end. Each has a + whole-buffer pass somewhere; only their token lookups have ever been + measured. Completion was the third of that list and is now done — and it + was 34–66 ms, which is the reason to finish the other two. ## Work log @@ -589,6 +721,33 @@ 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. +**2026-08-28 — dev (round 7, Lane B).** Added three measurements and one +before/after section, all under *Before / after — round 7*: + +- `perf::completing_one_keystroke_at_a_time` — the completion request at nine + prefixes, in both positions that gate tier 0, over a generated 4 000-file + corpus. The two columns are the whole finding: everything that is not the + module-skeleton tier is 0.19 ms, at every prefix, before and after. +- `perf::completing_over_a_real_project` — the same, over `LUCISV_PERF_CORPUS`, + with tier 0's per-module bill split into read / slice / plan. **Skipped when + the variable is unset**, so this crate still depends on no checkout it does + not ship. It is what caught the four `aes_control*` modules whose 6.6 KB + headers overflowed the first window ladder and paid a whole-file parse; the + shipped `HEADER_WINDOWS` top rung of 16 KB comes from that measurement and + from a survey of opentitan's 344 RTL headers, not from a guess. +- `perf::what_the_scope_depth_default_costs` — every rung of the scope ladder + over an opentitan-shaped tree, which is the number behind the + `lucisv.index.scopeDepth` default moving 0 → 2. + +`completion_corpus`'s files are 1 200 lines rather than the 300 first tried: +at 300 the generated corpus reproduced `performance.md`'s 34–66 ms almost +exactly, and going bigger showed the *shape* of the cost (a whole-file parse +per skeleton) far more clearly — 2.71 ms of parse for 16 µs of planning. + +No figure in any earlier round was re-measured: nothing on those paths +changed. `completion.rs`'s tier 0 and `candidates.rs`'s tables are on no +earlier table. + ## QA log **2026-08-28 — QA.** No findings — every number reproduces within reason. diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 8e9a859..c195ac0 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -247,9 +247,9 @@ }, "lucisv.index.scopeDepth": { "type": "number", - "default": 0, + "default": 2, "minimum": 0, - "markdownDescription": "How many folders **above** an open file the `folder` scope starts from — the reach for relative files. `0` (the default) is the file's own folder and everything under it. `1` starts one folder up, so a file in `rtl/` also indexes `include/` beside it. The climb never leaves the workspace folder that contains the file, so a large number simply means the whole workspace folder. Raising this widens every answer listed under `#lucisv.index.scope#` and costs a larger scan. Ignored when `#lucisv.index.scope#` is `workspace` or a `#lucisv.filelist#` is set. With **no** workspace folder open there is nothing to clamp the climb against, so leave it at `0` for single files." + "markdownDescription": "How many folders **above** an open file the `folder` scope starts from — the reach for relative files. `2` (the default) starts two folders up, which in a typical layout is the whole block an open file belongs to: a file in `hw/ip/aes/rtl/` indexes all of `hw/ip/aes/`, `dv/` and `rtl/` together. `0` is the file's own folder and nothing above it — the old default, and the narrowest, fastest scope there is. The climb never leaves the workspace folder that contains the file, so a large number simply means the whole workspace folder. Raising this widens every answer listed under `#lucisv.index.scope#` and costs a larger scan. Ignored when `#lucisv.index.scope#` is `workspace` or a `#lucisv.filelist#` is set. With **no** workspace folder open there is nothing to clamp the climb against, so set it to `0` when you open single files on their own." }, "lucisv.index.maxFileSize": { "type": "number",