From 01c76067e89b9c6910995ea81e3cda0879aa227b Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 26 Aug 2026 16:41:34 -0700 Subject: [PATCH] =?UTF-8?q?LSP=20=C2=A79c:=20textDocument/codeLens=20?= =?UTF-8?q?=E2=80=94=20instantiation=20counts=20that=20jump?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One lens per module and interface declaration: 'no/1/N instantiations', counting instantiation sites workspace-wide through the one census the server has — hierarchy.rs's walk, refactored so the batch is the primitive (callers_of_each over one sources() pass; incoming is now a one-element batch, behavior byte-identical, amortization pinned by a corpus ratio test that fails if it goes linear). Clicking runs lucisv.showInstantiations through the existing executeCommand path, answering the site locations and pushing window/showDocument (first site, takeFocus, selection) when the client can take it; the zero-count lens is display-only. workspace/codeLens/refresh rides each reindex after the progress bar comes down, capability-gated, once per rescan. 42 tests added (dev 33 + QA 9): count agreement with incomingCalls, the absolute census policies pinned at the lens layer (multi-instance statements are one site, textual recursion, both ifdef arms, name collisions), one-sources()-read-per-request, showDocument/applyEdit response independence, and grep-derived ground truth on a real corpus file. The instantiation-edge-table request is now a concrete vlog_semantic Handshake — two features pay the walk it would delete. docs/features/code-lens/README.md Co-Authored-By: Claude Fable 5 --- TODO.md | 22 +- crates/lucisv_server/src/hierarchy.rs | 96 ++-- crates/lucisv_server/src/lens.rs | 697 ++++++++++++++++++++++++++ crates/lucisv_server/src/main.rs | 127 ++++- crates/lucisv_server/src/server.rs | 423 ++++++++++++++-- crates/lucisv_server/tests/e2e.rs | 136 +++++ docs/features/code-lens/README.md | 568 +++++++++++++++++++++ docs/features/lucisv-server/README.md | 5 +- 8 files changed, 1991 insertions(+), 83 deletions(-) create mode 100644 crates/lucisv_server/src/lens.rs create mode 100644 docs/features/code-lens/README.md diff --git a/TODO.md b/TODO.md index 091ba21..b24aaef 100644 --- a/TODO.md +++ b/TODO.md @@ -811,9 +811,29 @@ and are not gaps. verbatim blocks (`property`/`sequence`/`covergroup`) are the only labelled constructs left out, because `vlog_parser` keeps no name span for them — recorded in that README's Handshakes. -- [ ] **Code lens** — "N instantiations" above each module header from +- [x] **Code lens** — "N instantiations" above each module header from the hierarchy index; `codeLens/resolve` unnecessary (counts are cheap), `workspace/codeLens/refresh` on reindex. + → delivered 2026-08-26 by `docs/features/code-lens/README.md`: + `codeLensProvider` (`resolveProvider: false`) + + `crates/lucisv_server/src/lens.rs`. One lens per module *and* + interface declaration, on the declaration's own name span, reading + "no instantiations" / "1 instantiation" / "N instantiations". The + count is not a second census: `hierarchy::incoming` was split into + `hierarchy::callers_of_each`, a batched form of the same walk, so the + lens counts exactly what the call hierarchy would list — asserted by + an equality test, not by restating the arithmetic. The batch is the + primitive because `Workspace::sources()` re-reads the file set, so a + three-module file is one walk (133 ms over the corpus) rather than + three (93 ms each). Clicking runs `lucisv.showInstantiations`, which + answers every site as a `Location` and pushes a `window/showDocument` + for the first when the client advertised it; a module with no + instantiations gets a display-only lens instead of a click that leads + nowhere. `workspace/codeLens/refresh` goes out from `reindex()` after + the progress bar comes down, gated on + `workspace.codeLens.refreshSupport`. One request recorded there: an + instantiation-edge table in `WorkspaceIndex` would make both this and + `callHierarchy/incomingCalls` a lookup instead of a workspace walk. - [ ] **On-type formatting** — conspicuous absence for a formatter-first server; candidate trigger: newline (indent the new line per block nesting), `;` (reformat the finished statement). diff --git a/crates/lucisv_server/src/hierarchy.rs b/crates/lucisv_server/src/hierarchy.rs index 93b4f90..44671bc 100644 --- a/crates/lucisv_server/src/hierarchy.rs +++ b/crates/lucisv_server/src/hierarchy.rs @@ -25,7 +25,7 @@ use vlog_parser::{parse_source_tolerant, LineIndex, TextRange}; use vlog_semantic::SymbolKind as SemanticKind; use crate::convert::Positions; -use crate::instantiations::{self, Decl}; +use crate::instantiations::{self, Decl, Site}; use crate::state::Workspace; use crate::uri::{path_to_uri, uri_to_path}; @@ -60,27 +60,59 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option Vec { + callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default() +} + +/// Who instantiates each of `names`, answered one list per name in the order +/// asked. +/// /// Every in-scope file is walked, because the workspace index records what a /// file *declares* and not what it instantiates — there is no edge table to -/// consult. A file whose text does not contain the name at all is skipped -/// before it is parsed, which is what keeps the walk affordable: an -/// instantiation of `fifo` has to write `fifo`. -pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec { - // Nothing this server hands out is nameless, so an empty name is a - // malformed item — and the prefilter below matches every file for it, - // which would read and parse the whole workspace to find nothing. - if item.name.is_empty() { - return Vec::new(); - } - let mut calls: Vec = Vec::new(); +/// consult. A file whose text contains none of the names is skipped before it +/// is parsed, which is what keeps the walk affordable: an instantiation of +/// `fifo` has to write `fifo`. +/// +/// The **batch** is the primitive rather than the single name because +/// [`Workspace::sources`] re-reads every in-scope file: one question per name +/// would re-read the whole workspace once per name, and `lens.rs` asks about +/// every module declared in a buffer at once. A file is parsed once for the +/// whole batch. +/// +/// An empty name is answered with nothing rather than searched for: nothing +/// this server hands out is nameless, and the prefilter matches every file for +/// one, which would parse the whole workspace to find nothing. +pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec> { + let mut answers: Vec> = + names.iter().map(|_| Vec::new()).collect(); for (path, text) in ws.sources() { - calls.extend(callers_in(&path, &text, &item.name)); + let wanted: Vec = names + .iter() + .enumerate() + .filter(|(_, name)| !name.is_empty() && text.contains(**name)) + .map(|(index, _)| index) + .collect(); + if wanted.is_empty() { + continue; + } + let Some(uri) = path_to_uri(&path) else { continue }; + let (tree, _) = parse_source_tolerant(&text); + let sites = instantiations::sites(&tree.items); + let line_index = LineIndex::new(&text); + let positions = Positions::new(&text, &line_index); + for index in wanted { + answers[index].extend(callers_in(&uri, &positions, &sites, names[index])); + } } - calls.sort_by(|a, b| { - (a.from.uri.as_str(), key(a.from.selection_range)) - .cmp(&(b.from.uri.as_str(), key(b.from.selection_range))) - }); - calls + for answer in &mut answers { + answer.sort_by(|a, b| { + (a.from.uri.as_str(), key(a.from.selection_range)) + .cmp(&(b.from.uri.as_str(), key(b.from.selection_range))) + }); + } + answers } /// What this module instantiates: one call per **distinct instantiated @@ -120,17 +152,16 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec Vec { - // An instantiation of `name` writes `name`. Nearly every file in a - // workspace does not, and this is what keeps those files unparsed. - if !text.contains(name) { - return Vec::new(); - } - let Some(uri) = path_to_uri(path) else { return Vec::new() }; - let (tree, _) = parse_source_tolerant(text); - let mut callers: Vec<(Decl, Vec)> = Vec::new(); - for site in instantiations::sites(&tree.items) { +/// Every module in one already-parsed file that instantiates `name`, with its +/// sites. +fn callers_in<'a>( + uri: &Uri, + positions: &Positions, + sites: &[Site<'a>], + name: &str, +) -> Vec { + let mut callers: Vec<(Decl<'a>, Vec)> = Vec::new(); + for site in sites { if site.inst.module != name { continue; } @@ -141,16 +172,11 @@ fn callers_in(path: &Path, text: &str, name: &str) -> Vec callers.push((owner, vec![site.inst.module_span])), } } - if callers.is_empty() { - return Vec::new(); - } - let line_index = LineIndex::new(text); - let positions = Positions::new(text, &line_index); callers .into_iter() .filter_map(|(decl, spans)| { Some(CallHierarchyIncomingCall { - from: item(uri.clone(), &positions, decl)?, + from: item(uri.clone(), positions, decl)?, from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(), }) }) diff --git a/crates/lucisv_server/src/lens.rs b/crates/lucisv_server/src/lens.rs new file mode 100644 index 0000000..fd6e0e8 --- /dev/null +++ b/crates/lucisv_server/src/lens.rs @@ -0,0 +1,697 @@ +//! `textDocument/codeLens`: how often the workspace instantiates the module +//! written on this line. +//! +//! One lens per module (and per interface — the same AST node) declared in the +//! open buffer, sitting on the declaration's own name so the editor draws it +//! on the line above the header. It reads **"N instantiations"**, "1 +//! instantiation", or "no instantiations", and N is the number of +//! instantiation *sites* across the whole workspace — the same population +//! `callHierarchy/incomingCalls` reports, counted by the same walk +//! ([`hierarchy::callers_of_each`]) so the two can never disagree. +//! +//! **Clicking.** The lens carries `lucisv.showInstantiations`, run through the +//! `workspace/executeCommand` this server already serves. The command answers +//! with every site as a `Location`, and — for a client that advertised +//! `window/showDocument` — the server pushes a request to open the first of +//! them, which is what makes the click actually move a cursor. LSP has no +//! server-initiated "peek these seven places"; that is a VS Code command, and +//! this repo's extension does not declare one. A module with **no** +//! instantiations gets a display-only lens instead (an empty `command` +//! string, as rust-analyzer ships for the same case): there is nothing to +//! open, and a click that led nowhere would be worse than no click. +//! +//! See `docs/features/code-lens/README.md`. + +use lsp_types::{CodeLens, Command, Location, Uri}; +use serde_json::Value; + +use crate::state::Workspace; +use crate::{hierarchy, instantiations}; + +/// Show every instantiation of a module: `[module-name]`. +pub const SHOW_INSTANTIATIONS: &str = "lucisv.showInstantiations"; + +/// Every command this module executes. +pub fn commands() -> Vec { + vec![SHOW_INSTANTIATIONS.to_string()] +} + +/// One lens per module or interface declared in the open buffer, counting the +/// workspace's instantiations of it. +/// +/// `None` — which the handler sends as `null` — for a buffer this server was +/// never shown, matching every other request that answers from a `Document`. +/// A buffer that declares nothing the parser could name gets an empty list: +/// the file was read, and it has no declarations to decorate. +pub fn code_lenses(ws: &Workspace, uri: &Uri) -> Option> { + let doc = ws.document(uri)?; + // A declaration the parser could not name — recovered from broken text, + // or reached through an error item — has no span to hang a lens on. + let decls: Vec<_> = instantiations::declarations(&doc.tree.items) + .into_iter() + .filter(|decl| !decl.module.name_span.is_empty()) + .collect(); + if decls.is_empty() { + // Before the workspace walk: a buffer with nothing to decorate must + // not read every file in the project to learn that. + return Some(Vec::new()); + } + let names: Vec<&str> = decls.iter().map(|decl| decl.module.name.as_str()).collect(); + let callers = hierarchy::callers_of_each(ws, &names); + let positions = doc.positions(); + Some( + decls + .iter() + .zip(callers) + .map(|(decl, calls)| CodeLens { + range: positions.range(decl.module.name_span), + command: Some(command(&decl.module.name, sites_in(&calls))), + data: None, + }) + .collect(), + ) +} + +/// Run `lucisv.showInstantiations`: every place the workspace instantiates the +/// named module, as locations. +/// +/// One location per **site**, not per instantiating module — that is what the +/// lens counted, and a caller that asked to see "7 instantiations" wants seven +/// places. A name nothing instantiates answers an empty list rather than an +/// error: a module waiting to be used is an ordinary state, and it is the +/// state whose lens does not click in the first place. +pub fn execute(ws: &Workspace, arguments: &[Value]) -> Result, String> { + let name = + arguments.first().and_then(Value::as_str).filter(|name| !name.is_empty()).ok_or_else( + || format!("{SHOW_INSTANTIATIONS} wants a module name as its first argument."), + )?; + Ok(sites_of(ws, name)) +} + +/// Every instantiation of `name` in the workspace, one location per site, in +/// the order the hierarchy lists its callers. +fn sites_of(ws: &Workspace, name: &str) -> Vec { + hierarchy::callers_of_each(ws, &[name]) + .pop() + .unwrap_or_default() + .into_iter() + .flat_map(|call| { + let uri = call.from.uri; + call.from_ranges.into_iter().map(move |range| Location { uri: uri.clone(), range }) + }) + .collect() +} + +/// How many sites one name's incoming calls hold. A caller reports every site +/// inside it, so the count is the sum and not the number of callers. +fn sites_in(calls: &[lsp_types::CallHierarchyIncomingCall]) -> usize { + calls.iter().map(|call| call.from_ranges.len()).sum() +} + +/// The lens for one module: what it reads, and what clicking it runs. +/// +/// A module nothing instantiates gets a display-only lens — a `Command` whose +/// `command` is the empty string, which clients render as plain text. See the +/// module comment for why. +fn command(name: &str, sites: usize) -> Command { + Command { + title: title(sites), + command: if sites == 0 { String::new() } else { SHOW_INSTANTIATIONS.to_string() }, + arguments: (sites > 0).then(|| vec![Value::String(name.to_string())]), + } +} + +/// What the lens reads, in the user's own arithmetic. +fn title(sites: usize) -> String { + match sites { + 0 => "no instantiations".to_string(), + 1 => "1 instantiation".to_string(), + many => format!("{many} instantiations"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + use lsp_types::CallHierarchyItem; + use std::fs; + use std::path::PathBuf; + + /// A scratch workspace root, removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_lens_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("mkdir"); + } + fs::write(&path, text).expect("write"); + path + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + /// A workspace over `files`, with the first of them opened as a buffer. + fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { + let tree = Tree::new(name); + let mut first = None; + for (rel, text) in files { + let path = tree.write(rel, text); + if first.is_none() { + first = Some((path, *text)); + } + } + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let (path, text) = first.expect("at least one file"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + (tree, ws, uri) + } + + /// Every lens of a buffer as `(title, command, start line, start column)`. + fn shape(lenses: &[CodeLens]) -> Vec<(String, String, u32, u32)> { + lenses + .iter() + .map(|lens| { + let command = lens.command.as_ref().expect("every lens carries a command"); + ( + command.title.clone(), + command.command.clone(), + lens.range.start.line, + lens.range.start.character, + ) + }) + .collect() + } + + /// Just the titles, for the tests that only care what the user reads. + fn titles(lenses: &[CodeLens]) -> Vec { + lenses + .iter() + .map(|lens| lens.command.as_ref().map_or(String::new(), |c| c.title.clone())) + .collect() + } + + const SUB: &str = "module sub (input logic clk);\nendmodule\n"; + const TOP: &str = "\ +module top; + sub u_a (.clk(1'b0)); + sub u_b (.clk(1'b1)); +endmodule +"; + const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; + + // ------------------------------------------------------------------ + // the count + // ------------------------------------------------------------------ + + #[test] + fn a_lens_counts_every_instantiation_in_the_workspace() { + // Three sites across two other files, on a declaration in this one. + let (_tree, ws, uri) = + workspace("count", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); + let lenses = code_lenses(&ws, &uri).expect("an open buffer"); + assert_eq!(titles(&lenses), ["3 instantiations"], "two in top.sv, one in o.sv"); + } + + #[test] + fn the_title_counts_in_the_users_own_arithmetic() { + let alone = "module lonely;\nendmodule\n"; + let (_tree, ws, uri) = workspace("zero", &[("lonely.sv", alone)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]); + + let one = "module top;\n lonely u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("one", &[("lonely.sv", alone), ("top.sv", one)]); + assert_eq!( + titles(&code_lenses(&ws, &uri).expect("open")), + ["1 instantiation"], + "not `1 instantiations`" + ); + + let two = "module top;\n lonely u1 ();\n lonely u2 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("two", &[("lonely.sv", alone), ("top.sv", two)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]); + } + + #[test] + fn the_count_is_exactly_what_incoming_calls_would_list() { + // The whole contract between this feature and the hierarchy: a user + // who reads "3 instantiations" and then opens the call hierarchy must + // be shown three sites. + let (_tree, ws, uri) = + workspace("agree", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(lenses.len(), 1); + + let item = CallHierarchyItem { + name: "sub".to_string(), + kind: lsp_types::SymbolKind::MODULE, + tags: None, + detail: None, + uri: uri.clone(), + range: lenses[0].range, + selection_range: lenses[0].range, + data: None, + }; + let listed: usize = + hierarchy::incoming(&ws, &item).iter().map(|call| call.from_ranges.len()).sum(); + assert_eq!(titles(&lenses), [format!("{listed} instantiations")]); + assert_eq!(listed, 3, "and the number itself is the one we meant"); + // And the command shows exactly those sites. + assert_eq!(execute(&ws, &[Value::String("sub".to_string())]).expect("runs").len(), listed); + } + + #[test] + fn an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it() { + // The same rule `callHierarchy/incomingCalls` applies: a site with no + // enclosing module has no caller to report, so it is nobody's edge. + let (_tree, ws, uri) = + workspace("filescope", &[("sub.sv", SUB), ("loose.sv", "sub u_loose ();\n")]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]); + } + + // ------------------------------------------------------------------ + // which declarations get a lens, and where it sits + // ------------------------------------------------------------------ + + #[test] + fn the_lens_sits_on_the_declarations_own_name() { + // The client draws a lens on the line *above* `range.start`, so the + // name span is what puts it over the header and nowhere else. + let (_tree, ws, uri) = workspace("span", &[("sub.sv", SUB), ("top.sv", TOP)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!( + shape(&lenses), + [("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7)], + "column 7 is `sub`, not the `module` keyword" + ); + assert_eq!(lenses[0].range.end.character, 10, "the name only"); + } + + #[test] + fn an_interface_is_a_module_declaration_and_gets_its_own_lens() { + let bus = "interface bus;\n logic clk;\nendinterface\n"; + let user = "module top;\n bus u_bus ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("iface", &[("bus.sv", bus), ("top.sv", user)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]); + } + + #[test] + fn every_module_in_a_file_gets_its_own_lens_in_source_order() { + let many = "\ +module first; +endmodule + +module second; +endmodule + +module third; +endmodule +"; + let uses = "module top;\n third u3 ();\n first u1 ();\n third u3b ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("many", &[("many.sv", many), ("top.sv", uses)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!( + shape(&lenses), + [ + ("1 instantiation".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7), + ("no instantiations".to_string(), String::new(), 3, 7), + ("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 6, 7), + ], + "source order, one per declaration" + ); + } + + #[test] + fn a_module_nothing_instantiates_gets_a_lens_that_does_not_click() { + let (_tree, ws, uri) = + workspace("noclick", &[("lonely.sv", "module lonely;\nendmodule\n")]); + let lenses = code_lenses(&ws, &uri).expect("open"); + let command = lenses[0].command.as_ref().expect("a command"); + assert_eq!(command.title, "no instantiations"); + assert_eq!(command.command, "", "display-only: there is nothing to open"); + assert_eq!(command.arguments, None, "and nothing to pass"); + } + + #[test] + fn a_clickable_lens_carries_the_module_name_as_its_only_argument() { + let (_tree, ws, uri) = workspace("args", &[("sub.sv", SUB), ("top.sv", TOP)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + let command = lenses[0].command.as_ref().expect("a command"); + assert_eq!(command.command, SHOW_INSTANTIATIONS); + assert_eq!(command.arguments, Some(vec![Value::String("sub".to_string())])); + } + + #[test] + fn no_lens_is_ever_left_for_a_resolve_to_fill_in() { + // `resolveProvider: false` is advertised, so a lens without a command + // would be a lens the client can never complete. + let (_tree, ws, uri) = workspace("complete", &[("sub.sv", SUB), ("top.sv", TOP)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert!(lenses.iter().all(|lens| lens.command.is_some() && lens.data.is_none())); + } + + // ------------------------------------------------------------------ + // the refusals + // ------------------------------------------------------------------ + + #[test] + fn a_buffer_this_server_was_never_shown_has_no_lenses_at_all() { + let (tree, ws, _) = workspace("closed", &[("sub.sv", SUB)]); + let never = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + assert!(code_lenses(&ws, &never).is_none(), "null, not an empty list"); + } + + #[test] + fn a_buffer_that_declares_no_module_gets_an_empty_list() { + let (_tree, ws, uri) = workspace("nomodules", &[("p.sv", "package p;\nendpackage\n")]); + assert_eq!(code_lenses(&ws, &uri).expect("open"), Vec::new()); + } + + #[test] + fn a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic() { + let junk = ")))) not verilog ((((\n@@@ endmodule : ;\n"; + let (_tree, ws, uri) = workspace("junk", &[("junk.sv", junk)]); + assert_eq!( + code_lenses(&ws, &uri).expect("open"), + Vec::new(), + "total, whatever it parses to" + ); + } + + #[test] + fn a_declaration_the_parser_could_not_name_gets_no_lens() { + // `module ;` recovers into a declaration with an empty name span, + // which is a lens with no line to sit on. + let broken = "module ;\nendmodule\n\nmodule fine;\nendmodule\n"; + let (_tree, ws, uri) = workspace("unnamed", &[("broken.sv", broken)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert!( + lenses.iter().all(|lens| lens.range.start.line == 3), + "only the named declaration: {lenses:#?}" + ); + } + + // ------------------------------------------------------------------ + // the command + // ------------------------------------------------------------------ + + #[test] + fn the_command_answers_one_location_per_site() { + let (_tree, ws, _) = + workspace("sites", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); + let locations = execute(&ws, &[Value::String("sub".to_string())]).expect("runs"); + let shape: Vec<(String, u32, u32)> = locations + .iter() + .map(|at| { + ( + at.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), + at.range.start.line, + at.range.start.character, + ) + }) + .collect(); + assert_eq!( + shape, + [ + ("o.sv".to_string(), 1, 2), + ("top.sv".to_string(), 1, 2), + ("top.sv".to_string(), 2, 2), + ], + "every site, sorted by file then position" + ); + } + + #[test] + fn the_command_answers_nothing_for_a_module_nothing_instantiates() { + let (_tree, ws, _) = workspace("nosites", &[("lonely.sv", "module lonely;\nendmodule\n")]); + assert_eq!(execute(&ws, &[Value::String("lonely".to_string())]), Ok(Vec::new())); + assert_eq!( + execute(&ws, &[Value::String("never-heard-of-it".to_string())]), + Ok(Vec::new()), + "a name the workspace does not declare is not an error either" + ); + } + + #[test] + fn the_command_declines_arguments_it_cannot_read() { + let (_tree, ws, _) = workspace("badargs", &[("sub.sv", SUB)]); + for arguments in [vec![], vec![Value::Null], vec![Value::String(String::new())]] { + let message = execute(&ws, &arguments).expect_err("declined"); + assert!(message.contains("module name"), "{message}"); + } + } + + #[test] + fn the_command_list_is_what_the_server_advertises() { + assert_eq!(commands(), vec![SHOW_INSTANTIATIONS]); + } + + // ------------------------------------------------------------------ + // QA (2026-08-26): count-honesty shapes the fixture above never + // exercises — a multi-instance statement, self-recursion, name + // collisions (within one file and across files), generate replication + // and an `ifdef`-guarded instantiation. None of these turned out to + // disagree with `hierarchy::incoming` — they can't, since `lens.rs` and + // `hierarchy::incoming` both bottom out in the same + // `hierarchy::callers_of_each` — but the *number itself* is worth + // pinning so a future change to what counts as a "site" is visible here + // too, not just in `hierarchy.rs`. See QA log in + // `docs/features/code-lens/README.md`. + // ------------------------------------------------------------------ + + #[test] + fn qa_corpus_counts_agree_with_grep_derived_ground_truth() { + // `corpus/common_cells/src/cdc_fifo_gray.sv` declares three modules. + // Ground truth by hand, `grep -rnE '\bNAME\b' corpus --include='*.sv' + // --include='*.svh'`, read line by line to exclude the declaration + // itself and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has + // several, e.g. line 56's "In contrast to the cdc_fifo_gray + // version..."): + // - `cdc_fifo_gray` — one real instantiation, + // `common_cells/test/cdc_fifo_tb.sv:49` (`i_dut`). + // - `cdc_fifo_gray_src` — one, `cdc_fifo_gray.sv:130`, inside + // `cdc_fifo_gray` itself (`_src_clearable` is a different name + // and does not match `\bcdc_fifo_gray_src\b`). + // - `cdc_fifo_gray_dst` — one, `cdc_fifo_gray.sv:145`, likewise. + // Skipped like the other corpus tests when `corpus/` is not checked + // out (`tools/corpus_fetch.sh`). + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); + let Ok(text) = fs::read_to_string(&file) else { + eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_roots(vec![corpus]); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!( + titles(&lenses), + ["1 instantiation", "1 instantiation", "1 instantiation"], + "cdc_fifo_gray, cdc_fifo_gray_src, cdc_fifo_gray_dst, in that source order: {lenses:#?}" + ); + } + + #[test] + fn qa_a_multi_instance_statement_is_one_site_not_two() { + // `sub u1 (), u2 ();` is ONE `Instantiation` AST node carrying TWO + // `Instance` entries — physically two instantiations of `sub` in the + // design. This is not a code-lens decision: `hierarchy.rs`'s own + // documented assumption ("One `Instantiation` is one call site, + // however many instances it declares") already settles it, the same + // way `textDocument/references` reports the module name once. Pinned + // here too so a change to that policy is visible in both features. + let top = "module top;\n sub u1 (), u2 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_multi", &[("sub.sv", SUB), ("top.sv", top)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(titles(&lenses), ["1 instantiation"], "one AST node, not two instances"); + let locs = execute(&ws, &[Value::String("sub".to_string())]).expect("runs"); + assert_eq!(locs.len(), 1, "one location for the one site: {locs:#?}"); + } + + #[test] + fn qa_a_module_that_instantiates_itself_counts_its_own_instantiation() { + // Self-recursion (illegal to elaborate, legal text) is handled the + // same way `hierarchy.rs` handles an `a -> b -> a` cycle: each + // request answers one hop, so there is nothing here that could ever + // recurse or hang. + let text = "module m;\n m u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_recursive", &[("m.sv", text)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(titles(&lenses), ["1 instantiation"]); + let locs = execute(&ws, &[Value::String("m".to_string())]).expect("runs"); + assert_eq!(locs.len(), 1); + } + + #[test] + fn qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both() { + // The census is by name (documented in this README's Assumptions): + // an instantiation of `m` cannot say which of two `module m` + // declarations it meant, so both lenses read the workspace-wide + // total rather than a partitioned one. Same limitation + // `callHierarchy/incomingCalls` already has, for the same reason. + let m_a = "module m;\n logic a;\nendmodule\n"; + let m_b = "module m;\n logic b;\nendmodule\n"; + let user = "module top;\n m u1 ();\nendmodule\n"; + let (_tree, ws, uri_a) = + workspace("qa_collide_a", &[("a/m.sv", m_a), ("b/m.sv", m_b), ("top.sv", user)]); + assert_eq!(titles(&code_lenses(&ws, &uri_a).expect("open a/m.sv")), ["1 instantiation"]); + + // Same workspace, opening the OTHER declaration instead: same total. + let mut ws_b = Workspace::default(); + let tree_b = Tree::new("qa_collide_b"); + tree_b.write("a/m.sv", m_a); + let path_b = tree_b.write("b/m.sv", m_b); + tree_b.write("top.sv", user); + ws_b.open_roots(vec![tree_b.path.clone()]); + let uri_b = path_to_uri(&path_b).expect("uri"); + ws_b.set_document(uri_b.clone(), m_b.to_string()); + assert_eq!( + titles(&code_lenses(&ws_b, &uri_b).expect("open b/m.sv")), + ["1 instantiation"], + "the other declaration reads the same total, not zero" + ); + } + + #[test] + fn qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count() { + // The tolerant parser accepts `module m; endmodule module m; + // endmodule` in one file (real SystemVerilog forbids it, but this is + // reachable through broken input). The batch in + // `hierarchy::callers_of_each` is asked `["m", "m"]` — two indices, + // not deduplicated — so this also pins that duplicate names in one + // batch do not alias or corrupt each other's answer. + let text = "module m;\nendmodule\n\nmodule m;\nendmodule\n"; + let user = "module top;\n m u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_dup_same_file", &[("m.sv", text), ("top.sv", user)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(lenses.len(), 2, "one lens per declaration"); + assert_eq!(titles(&lenses), ["1 instantiation", "1 instantiation"]); + } + + #[test] + fn qa_a_generate_replicated_instantiation_counts_the_written_statement_once() { + // `generate for` is not elaborated: the AST has exactly one + // `Instantiation` node inside the loop body regardless of the + // genvar's range, matching `hierarchy.rs`'s own documented handling + // of the identical shape (`incoming_calls_reach_generate_regions_...` + // in `hierarchy.rs`). Four elaborated instances at synthesis time, + // one textual site here — the lens counts text, not hardware. + let sub = "module sub;\nendmodule\n"; + let top = "\ +module top; + generate + for (genvar i = 0; i < 4; i++) begin : g + sub u1 (); + end + endgenerate +endmodule +"; + let (_tree, ws, uri) = workspace("qa_generate", &[("sub.sv", sub), ("top.sv", top)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]); + } + + #[test] + fn qa_an_ifdef_guarded_instantiation_counts_both_arms() { + // Inherited from `hierarchy.rs`, disclosed there as an Assumption: + // the parser does not evaluate `` `ifdef``/`` `else``, so both arms + // land as ordinary `Instantiation` items and both are counted, even + // though only one is ever really built. Pinned here too since the + // lens is a second, more prominent surface for the same policy. + let sub = "module sub;\nendmodule\n"; + let top = "\ +module top; +`ifdef FOO + sub u1 (); +`endif + sub u2 (); +endmodule +"; + let (_tree, ws, uri) = workspace("qa_ifdef", &[("sub.sv", sub), ("top.sv", top)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]); + } + + // ------------------------------------------------------------------ + // the performance claim, measured + // ------------------------------------------------------------------ + + /// What a whole file's lenses cost over the real corpus, and — the point + /// of the batch — that asking about three modules at once costs about what + /// asking about one does, not three times as much. + /// + /// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`), + /// like the other corpus tests. The budget is deliberately loose: a debug + /// build on a loaded machine is the worst case this ever runs in, and this + /// exists to catch an order-of-magnitude regression — a lens handler that + /// re-read the workspace once per declaration would fail the ratio. + #[test] + fn code_lenses_for_a_whole_file_cost_about_one_workspace_walk() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + // A real file declaring three modules, so the batch has something to + // amortize over. + let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); + let Ok(text) = fs::read_to_string(&file) else { + eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_roots(vec![corpus]); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text); + + // Warm, then the worst of three, for the whole file and for one name. + let _ = code_lenses(&ws, &uri); + let mut whole_file = std::time::Duration::ZERO; + let mut one_name = std::time::Duration::ZERO; + let mut count = 0; + for _ in 0..3 { + let started = std::time::Instant::now(); + let lenses = code_lenses(&ws, &uri).expect("open"); + whole_file = whole_file.max(started.elapsed()); + count = lenses.len(); + let started = std::time::Instant::now(); + let _ = sites_of(&ws, "cdc_fifo_gray"); + one_name = one_name.max(started.elapsed()); + } + eprintln!( + "corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \ + (one name alone: {one_name:?})", + ws.index().files().len(), + ); + assert!(count >= 3, "the file declares three modules: {count}"); + assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}"); + assert!( + whole_file < one_name * 2, + "the batch is one walk, not one per module: {count} names cost {whole_file:?} \ + against {one_name:?} for one" + ); + } +} diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index bddf113..dd40e47 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -20,6 +20,7 @@ mod includes; mod inlay; mod inline; mod instantiations; +mod lens; mod linked; mod lint; mod locate; @@ -46,14 +47,14 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability, - CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities, DocumentLinkOptions, - ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions, - InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind, - RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions, - SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, - ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, - TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, - WorkDoneProgressOptions, + CodeLensOptions, CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities, + DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, + InlayHintOptions, InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, + PositionEncodingKind, RenameOptions, SaveOptions, SelectionRangeProviderCapability, + SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, + SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, + TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, + TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions, }; use crate::server::{ClientAbilities, Server}; @@ -73,6 +74,8 @@ fn main() -> Result<(), Box> { apply_edit: apply_edit_support(¶ms), pull_diagnostics: pull_diagnostics_support(¶ms), work_done_progress: work_done_progress_support(¶ms), + code_lens_refresh: code_lens_refresh_support(¶ms), + show_document: show_document_support(¶ms), }; connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?; @@ -167,11 +170,19 @@ fn capabilities() -> ServerCapabilities { })), // The port refactorings. `lucisv.addPort` needs a declaration typed by // the user, which no code action can carry, and a Vim user has no - // lightbulb at all — so all three are commands as well. + // lightbulb at all — so all three are commands as well. The code + // lens's own jump joins them: a lens carries a `Command`, and this is + // where a command has to be declared to be runnable. execute_command_provider: Some(ExecuteCommandOptions { - commands: ports::commands(), + commands: commands(), work_done_progress_options: WorkDoneProgressOptions::default(), }), + // "N instantiations" over every module and interface declaration in + // the buffer, counted across the workspace. Every lens is returned + // complete — title, command and arguments — so there is nothing for + // `codeLens/resolve` to do, which is said out loud rather than left + // unset. See `docs/features/code-lens/README.md`. + code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(false) }), // Module hinting. No trigger characters: an identifier being typed is // what asks for these, and the handler declines every position that is // not a module item, so an unprompted request costs a token scan. @@ -252,6 +263,14 @@ fn capabilities() -> ServerCapabilities { } } +/// Every command this server executes: the three port refactorings, and the +/// jump the code lens hangs off. +fn commands() -> Vec { + let mut commands = ports::commands(); + commands.extend(lens::commands()); + commands +} + fn initialize_result() -> lsp_types::InitializeResult { lsp_types::InitializeResult { capabilities: capabilities(), @@ -323,6 +342,37 @@ fn work_done_progress_support(params: &InitializeParams) -> bool { .unwrap_or(false) } +/// Whether the client can be asked to re-request its code lenses. +/// +/// `workspace/codeLens/refresh` is server-initiated, so the spec makes this +/// capability the gate. A client that said nothing keeps whatever counts it +/// last asked for until something else makes it ask again — which is what +/// every client got before code lenses existed at all. +fn code_lens_refresh_support(params: &InitializeParams) -> bool { + params + .capabilities + .workspace + .as_ref() + .and_then(|workspace| workspace.code_lens.as_ref()) + .and_then(|code_lens| code_lens.refresh_support) + .unwrap_or(false) +} + +/// Whether the client opens a document the server asks it to. +/// +/// This is what makes the instantiation lens actually navigate: an +/// `executeCommand` result cannot move a cursor, so the jump is a pushed +/// `window/showDocument`. A client that did not advertise it still gets the +/// sites back as the command's result. +fn show_document_support(params: &InitializeParams) -> bool { + params + .capabilities + .window + .as_ref() + .and_then(|window| window.show_document.as_ref()) + .is_some_and(|show_document| show_document.support) +} + /// The directories to index: the client's workspace folders, or the /// deprecated single root when that is all it sent. fn workspace_roots(params: &InitializeParams) -> Vec { @@ -366,6 +416,7 @@ mod tests { assert!(caps.inline_completion_provider.is_some()); assert!(caps.selection_range_provider.is_some()); assert!(caps.diagnostic_provider.is_some()); + assert!(caps.code_lens_provider.is_some()); } #[test] @@ -564,7 +615,12 @@ mod tests { #[test] fn every_advertised_command_is_one_the_server_runs() { let options = capabilities().execute_command_provider.expect("commands"); - assert_eq!(options.commands, ports::commands()); + assert_eq!(options.commands, commands()); + // Both halves of the list, so neither can go missing quietly: a lens + // whose command is not advertised is a lens no client will run. + for command in ports::commands().iter().chain(lens::commands().iter()) { + assert!(options.commands.contains(command), "{command} is not advertised"); + } assert!( options.commands.iter().all(|c| c.starts_with("lucisv.")), "{:?}", @@ -572,6 +628,55 @@ mod tests { ); } + #[test] + fn code_lenses_resolve_nothing_because_every_lens_is_complete() { + let options = capabilities().code_lens_provider.expect("code lenses"); + assert_eq!(options.resolve_provider, Some(false)); + } + + #[test] + fn code_lens_refresh_support_is_read_from_the_clients_own_capabilities() { + use lsp_types::{ + ClientCapabilities, CodeLensWorkspaceClientCapabilities, WorkspaceClientCapabilities, + }; + assert!(!code_lens_refresh_support(&InitializeParams::default()), "silence means no"); + + let saying = |refresh_support: Option| InitializeParams { + capabilities: ClientCapabilities { + workspace: Some(WorkspaceClientCapabilities { + code_lens: Some(CodeLensWorkspaceClientCapabilities { refresh_support }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + assert!(code_lens_refresh_support(&saying(Some(true)))); + assert!(!code_lens_refresh_support(&saying(Some(false)))); + assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes"); + } + + #[test] + fn show_document_support_is_read_from_the_clients_own_capabilities() { + use lsp_types::{ + ClientCapabilities, ShowDocumentClientCapabilities, WindowClientCapabilities, + }; + assert!(!show_document_support(&InitializeParams::default()), "silence means no"); + + let saying = |support: bool| InitializeParams { + capabilities: ClientCapabilities { + window: Some(WindowClientCapabilities { + show_document: Some(ShowDocumentClientCapabilities { support }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + assert!(show_document_support(&saying(true))); + assert!(!show_document_support(&saying(false))); + } + #[test] fn utf16_is_advertised_because_that_is_what_convert_implements() { assert_eq!(capabilities().position_encoding, Some(PositionEncodingKind::UTF16)); diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index f5fa65b..cbaf955 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -20,39 +20,39 @@ use lsp_types::notification::{ }; use lsp_types::request::{ ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, - CallHierarchyPrepare, CodeActionRequest, Completion, DocumentDiagnosticRequest, - DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand, - FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams, - GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest, - LinkedEditingRange, PrepareRenameRequest, RangeFormatting, References, RegisterCapability, - Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest, - SemanticTokensFullRequest, SemanticTokensRangeRequest, Shutdown, SignatureHelpRequest, - UnregisterCapability, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, - WorkspaceSymbolRequest, + CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest, Completion, + DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest, + DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition, + GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest, + InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, PrepareRenameRequest, + RangeFormatting, References, RegisterCapability, Rename, Request as _, SelectionRangeRequest, + SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest, + ShowDocument, Shutdown, SignatureHelpRequest, UnregisterCapability, WillSaveWaitUntil, + WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CancelParams, CodeActionKind, - CodeActionParams, CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, - DidChangeWatchedFilesParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, - DidSaveTextDocumentParams, DocumentDiagnosticParams, DocumentDiagnosticReport, - DocumentDiagnosticReportResult, DocumentFormattingParams, DocumentHighlightParams, - DocumentLinkParams, DocumentRangeFormattingParams, DocumentSymbolParams, - DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, - GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, - InlineCompletionParams, LinkedEditingRangeParams, LogMessageParams, MessageType, - NumberOrString, Position, PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, - PublishDiagnosticsParams, ReferenceParams, RegistrationParams, + CodeActionParams, CodeLensParams, CompletionParams, DidChangeConfigurationParams, + DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams, + DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentDiagnosticParams, + DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentFormattingParams, + DocumentHighlightParams, DocumentLinkParams, DocumentRangeFormattingParams, + DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, + FullDocumentDiagnosticReport, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, + InlayHintParams, InlineCompletionParams, LinkedEditingRangeParams, Location, LogMessageParams, + MessageType, NumberOrString, Position, PreviousResultId, ProgressParams, ProgressParamsValue, + ProgressToken, PublishDiagnosticsParams, ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticToken, SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams, - SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowMessageParams, - SignatureHelpParams, TextDocumentPositionParams, UnchangedDocumentDiagnosticReport, - UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin, - WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkspaceDiagnosticParams, - WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, - WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, - WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport, + SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowDocumentParams, + ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, + UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, WillSaveTextDocumentParams, + WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd, + WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, + WorkspaceDocumentDiagnosticReport, WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, + WorkspaceSymbolParams, WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport, }; use serde::de::DeserializeOwned; use serde_json::Value; @@ -60,7 +60,7 @@ use serde_json::Value; use crate::state::Workspace; use crate::{ code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, - inline, linked, nav, pairs, ports, rename, selection, settings, signature, symbols, sync, + inline, lens, linked, nav, pairs, ports, rename, selection, settings, signature, symbols, sync, tokens, type_def, watch, }; @@ -85,6 +85,15 @@ pub struct ClientAbilities { /// spec forbids creating any without it, so a client that said nothing /// sees the workspace rescan exactly as it did before — silently. pub work_done_progress: bool, + /// Whether the client accepts a `workspace/codeLens/refresh`. A client + /// that said nothing is never asked, and keeps the instantiation counts it + /// last requested until it asks again for its own reasons. + pub code_lens_refresh: bool, + /// Whether the client opens a document the server asks it to + /// (`window/showDocument`). This is what lets the instantiation lens + /// navigate; a client without it still gets the sites back as the + /// command's result. + pub show_document: bool, } /// Everything the server owns. @@ -472,9 +481,25 @@ impl Server { Err(message) => Err(Failure::Request(message)), } }), - // The port refactorings. A refusal is the engine's own sentence, - // returned as `RequestFailed` exactly as a declined rename is. + // "N instantiations" over every module and interface declared in + // the buffer. Every lens is complete when it is returned — there + // is no `codeLens/resolve` — and a buffer this server has not been + // sent answers `null`, as every other document-scoped request + // does. + CodeLensRequest::METHOD => decode(request).and_then(|p: CodeLensParams| { + lens::code_lenses(&self.workspace, &p.text_document.uri) + .map_or(Ok(Value::Null), to_value) + }), + // The port refactorings, and the code lens's own jump. A refusal + // is the engine's own sentence, returned as `RequestFailed` + // exactly as a declined rename is. ExecuteCommand::METHOD => decode(request).and_then(|p: ExecuteCommandParams| { + if p.command == lens::SHOW_INSTANTIATIONS { + return match lens::execute(&self.workspace, &p.arguments) { + Ok(locations) => self.show_instantiations(locations), + Err(message) => Err(Failure::Request(message)), + }; + } match ports::execute(&self.workspace, &p.command, &p.arguments) { Ok((edit, warnings)) => { self.report_scope(warnings); @@ -690,6 +715,32 @@ impl Server { Ok(Value::Null) } + /// Answer `lucisv.showInstantiations` with its sites, and — for a client + /// that can be sent one — push a `window/showDocument` for the first of + /// them, so clicking the lens actually moves a cursor. + /// + /// `executeCommand`'s *result* cannot navigate: it goes back to whatever + /// invoked the command, and no editor moves on one. So the locations are + /// the answer for a caller that wants the list, and the push is what makes + /// the lens do something in an editor. Only the **first** site is shown: + /// `window/showDocument` opens one document, and the protocol has no + /// server-initiated "peek these seven places" — that is a VS Code command, + /// and this repo's extension declares none. The client's answer is + /// ignorable and falls through `response`'s `applying` lookup, as the + /// progress `create`'s does. + fn show_instantiations(&mut self, locations: Vec) -> Result { + if let Some(first) = locations.first().filter(|_| self.abilities.show_document) { + let params = ShowDocumentParams { + uri: first.uri.clone(), + external: None, + take_focus: Some(true), + selection: Some(first.range), + }; + self.send_request(ShowDocument::METHOD, params); + } + to_value(locations) + } + // ------------------------------------------------------------------ // semantic tokens // ------------------------------------------------------------------ @@ -925,12 +976,15 @@ impl Server { /// What the client answered. /// - /// Only a `workspace/applyEdit` answer is read. The other two things ever - /// asked of the client have nothing to do with theirs: a client that - /// refuses the file-watcher (un)registration simply keeps the save-only - /// staleness model, and one that errors a `window/workDoneProgress/create` - /// renders no bar and ignores the `$/progress` that named that token, per - /// spec. Neither id is ever in `applying`, so both fall out here. + /// Only a `workspace/applyEdit` answer is read. Nothing else this server + /// asks of the client has an answer worth acting on: one that refuses the + /// file-watcher (un)registration simply keeps the save-only staleness + /// model; one that errors a `window/workDoneProgress/create` renders no + /// bar and ignores the `$/progress` that named that token, per spec; one + /// that declines a `workspace/codeLens/refresh` keeps the counts it has, + /// and the next save asks again; and one that could not open a + /// `window/showDocument` has already told the user so itself. None of + /// those ids is ever in `applying`, so they all fall out here. fn response(&mut self, response: Response) { let Some(command) = self.applying.remove(&response.id) else { return }; // A refusal is worth saying out loud: the user ran a command, watched @@ -999,6 +1053,12 @@ impl Server { let bar = self.begin_indexing(); let warnings = self.workspace.rebuild_index(); self.end_indexing(bar); + // A rescan can change any module's instantiation count, so every lens + // a client is holding may now read wrong. Sent after the bar comes + // down, for the same reason the bar comes down before the republishes: + // the bar names the scan, and everything after it is work done on the + // scan's result. + self.refresh_code_lenses(); // Every open buffer's diagnostics are computed against the index, so a // pulling client's cached answers are all stale from here. self.generation += 1; @@ -1057,6 +1117,22 @@ impl Server { self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message })); } + /// Ask the client to re-request its code lenses, because the rescan just + /// finished may have changed every instantiation count in every buffer it + /// is showing. + /// + /// Silent for a client that did not advertise + /// `workspace.codeLens.refreshSupport` — the request is server-initiated + /// and the spec makes that capability the gate. Nothing is sent at startup + /// either: no buffer is open there, so there are no lenses to invalidate. + /// The answer is ignorable and rides `response`'s fall-through path. + fn refresh_code_lenses(&mut self) { + if !self.abilities.code_lens_refresh { + return; + } + self.send_request(CodeLensRefresh::METHOD, ()); + } + /// One `$/progress` notification for a token the client already knows. fn progress(&self, token: ProgressToken, value: WorkDoneProgress) { let params = ProgressParams { token, value: ProgressParamsValue::WorkDone(value) }; @@ -2565,6 +2641,283 @@ mod tests { assert_eq!(result, Value::Null); } + // ------------------------------------------------------------------ + // `textDocument/codeLens` + // ------------------------------------------------------------------ + + /// A workspace holding `sub` and two instantiations of it, with `sub.sv` + /// open — the shape every lens test below asks about. + fn lens_tree(name: &str) -> Tree { + let tree = Tree::new(name); + tree.write("sub.sv", "module sub;\nendmodule\n"); + tree.write("top.sv", "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n"); + tree + } + + #[test] + fn a_code_lens_request_counts_the_workspaces_instantiations() { + let tree = lens_tree("lens"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + let result = session + .result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + let lenses = result.as_array().expect("a lens list").clone(); + assert_eq!(lenses.len(), 1, "{result:#?}"); + assert_eq!(lenses[0]["command"]["title"], "2 instantiations"); + assert_eq!(lenses[0]["command"]["command"], lens::SHOW_INSTANTIATIONS); + assert_eq!(lenses[0]["command"]["arguments"], serde_json::json!(["sub"])); + assert_eq!(lenses[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 7 })); + assert!(lenses[0]["data"].is_null(), "nothing is left for a resolve"); + } + + #[test] + fn a_code_lens_request_for_an_unopened_buffer_answers_null() { + let tree = lens_tree("lensclosed"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + let result = session + .result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + assert_eq!(result, Value::Null); + } + + #[test] + fn the_show_instantiations_command_answers_every_site() { + let tree = lens_tree("lenscommand"); + let mut session = Session::new(vec![tree.path.clone()], false); + session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + let result = session.result( + ExecuteCommand::METHOD, + serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }), + ); + let locations = result.as_array().expect("a location list").clone(); + assert_eq!(locations.len(), 2, "{result:#?}"); + assert!(locations[0]["uri"].as_str().expect("uri").ends_with("top.sv")); + assert_eq!( + locations[0]["range"]["start"], + serde_json::json!({ "line": 1, "character": 2 }) + ); + assert_eq!( + locations[1]["range"]["start"], + serde_json::json!({ "line": 2, "character": 2 }) + ); + // Nothing was pushed: this client cannot be shown a document. + assert!(session.requests().is_empty(), "no showDocument for a client without it"); + } + + #[test] + fn the_show_instantiations_command_pushes_a_show_document_when_it_can() { + let tree = lens_tree("lensshow"); + let abilities = ClientAbilities { show_document: true, ..Default::default() }; + let mut session = Session::with(vec![tree.path.clone()], abilities); + session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + let _ = session.drain(); + let result = session.result( + ExecuteCommand::METHOD, + serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }), + ); + assert_eq!(result.as_array().expect("locations").len(), 2, "and still the whole list"); + let asked = session.requests(); + assert_eq!(asked.len(), 1, "{asked:#?}"); + assert_eq!(asked[0].0, ShowDocument::METHOD); + assert!(asked[0].1["uri"].as_str().expect("uri").ends_with("top.sv")); + assert_eq!( + asked[0].1["selection"]["start"], + serde_json::json!({ "line": 1, "character": 2 }) + ); + assert_eq!(asked[0].1["takeFocus"], true); + } + + #[test] + fn a_module_with_no_instantiations_pushes_nothing_and_shows_nothing() { + let tree = Tree::new("lensempty"); + tree.write("lonely.sv", "module lonely;\nendmodule\n"); + let abilities = ClientAbilities { show_document: true, ..Default::default() }; + let mut session = Session::with(vec![tree.path.clone()], abilities); + let uri = session.open(&tree.path.join("lonely.sv"), "module lonely;\nendmodule\n"); + let _ = session.drain(); + let result = session + .result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + assert_eq!(result[0]["command"]["title"], "no instantiations"); + assert_eq!(result[0]["command"]["command"], "", "display-only"); + let empty = session.result( + ExecuteCommand::METHOD, + serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["lonely"] }), + ); + assert_eq!(empty, serde_json::json!([])); + assert!(session.requests().is_empty(), "nothing to show, nothing pushed"); + } + + #[test] + fn the_show_instantiations_command_declines_arguments_it_cannot_read() { + let tree = lens_tree("lensbadargs"); + let mut session = Session::new(vec![tree.path.clone()], false); + session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + let error = session + .request( + ExecuteCommand::METHOD, + serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS }), + ) + .response_result + .expect_err("declined"); + assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32); + assert!(error.message.contains("module name"), "{error:?}"); + } + + #[test] + fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() { + let tree = lens_tree("lensrefresh"); + let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() }; + let mut session = Session::with(vec![tree.path.clone()], abilities); + assert!(session.requests().is_empty(), "nothing to refresh at startup: no buffer is open"); + let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + let _ = session.drain(); + + // Every rescan trigger, one refresh each. + session.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + session.watched(&[tree.path.join("top.sv")]); + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "exclude": ["nothing"] } } }), + ); + let methods: Vec = + session.requests().into_iter().map(|(method, _)| method).collect(); + assert_eq!( + methods, + vec![CodeLensRefresh::METHOD; 3], + "one per rescan, on the save, watched-file and config paths" + ); + } + + #[test] + fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() { + let tree = lens_tree("lensnorefresh"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + let _ = session.drain(); + session.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + session.watched(&[tree.path.join("top.sv")]); + assert!(session.requests().is_empty(), "silence, on every rescan path"); + } + + #[test] + fn the_refresh_rides_after_the_indexing_bar_comes_down() { + // The documented order: the bar names the scan, and the refresh is + // work done on the scan's result — as the republishes are. + let tree = lens_tree("lensorder"); + let abilities = ClientAbilities { + code_lens_refresh: true, + work_done_progress: true, + ..Default::default() + }; + let mut session = Session::with(vec![tree.path.clone()], abilities); + let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + let _ = session.drain(); + session.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + let order: Vec = session + .drain() + .into_iter() + .filter_map(|message| match message { + Message::Request(request) if request.method == CodeLensRefresh::METHOD => { + Some("refresh".to_string()) + } + other => progress_step(other).map(|(step, _)| step.to_string()), + }) + .collect(); + assert_eq!(order, ["create", "begin", "end", "refresh"]); + } + + #[test] + fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() { + // `refresh_code_lenses()` is called once in `reindex()`, before the + // loop that republishes every open buffer's diagnostics — not once + // per buffer that loop republishes. Two open buffers make that + // distinction observable: a refresh-per-publish regression would + // send two. + let tree = lens_tree("qa_lensrefresh_multi"); + let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() }; + let mut session = Session::with(vec![tree.path.clone()], abilities); + let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); + session.open( + &tree.path.join("top.sv"), + "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n", + ); + let _ = session.drain(); + + session.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + let methods: Vec = + session.requests().into_iter().map(|(method, _)| method).collect(); + assert_eq!(methods, vec![CodeLensRefresh::METHOD], "one refresh, not one per open buffer"); + } + + #[test] + fn qa_a_showdocument_push_and_an_applyedit_push_stay_independent_when_both_are_outstanding() { + // Both `deliver` (applyEdit) and `show_instantiations` (showDocument) + // push a server-initiated request and rely on the same mechanism — + // `response()` only reacts to an id it finds in `applying`, and only + // `deliver` ever inserts one. Two requests outstanding at once, one of + // each kind, must not cross-contaminate: a showDocument answer must + // not be mistaken for the applyEdit one (or vice versa), whichever + // order the client answers in. + let tree = Tree::new("qa_interleave"); + tree.write("sub.sv", SUB); + tree.write("top.sv", TOP); + let abilities = + ClientAbilities { apply_edit: true, show_document: true, ..Default::default() }; + let mut session = Session::with(vec![tree.path.clone()], abilities); + let top_uri = session.open(&tree.path.join("top.sv"), TOP); + session.open(&tree.path.join("sub.sv"), SUB); + let _ = session.drain(); + + // First outstanding request: an applyEdit push from a port command. + let propagate = session.result( + ExecuteCommand::METHOD, + serde_json::json!({ + "command": ports::PROPAGATE_PORTS, + "arguments": [top_uri, { "line": 2, "character": 6 }], + }), + ); + assert_eq!(propagate, Value::Null); + + // Second outstanding request: a showDocument push from the lens's + // own command, over the same `sub` instantiation. + let sites = session.result( + ExecuteCommand::METHOD, + serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }), + ); + assert_eq!(sites.as_array().expect("locations").len(), 1); + + let sent = session.sent(); + assert_eq!(sent.len(), 2, "{sent:#?}"); + assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD); + assert_eq!(sent[1].method, ShowDocument::METHOD); + let apply_id = sent[0].id.clone(); + let show_id = sent[1].id.clone(); + + // Answer the showDocument push FIRST, out of send order — it carries + // no `applied` field at all, so if `response()` ever matched it to + // the applyEdit command by anything other than its own id, this would + // either panic or wrongly report a failed edit. + session.answer(show_id, serde_json::json!({ "success": true })); + assert!(session.shown().is_empty(), "the showDocument answer must not be interpreted"); + + // Now answer the applyEdit push — a real success — and confirm it is + // still routed correctly to its own command. + session.answer(apply_id, serde_json::json!({ "applied": true })); + assert!(session.shown().is_empty(), "a successful apply reports nothing"); + } + // ------------------------------------------------------------------ // incremental text sync // ------------------------------------------------------------------ diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 3729e2f..39497ce 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -3317,3 +3317,139 @@ fn a_linked_editing_range_round_trips_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +const LENS_SUB: &str = "module lens_sub (input logic clk);\nendmodule\n"; +const LENS_TOP: &str = "\ +module lens_top; + lens_sub u_a (.clk(1'b0)); + lens_sub u_b (.clk(1'b1)); +endmodule +"; + +#[test] +fn code_lenses_and_their_command_round_trip_over_the_wire() { + // What only an e2e test can check: that the capability reaches a real + // handshake in the shape a client reads, that the lens is dispatched, and + // that the command a lens carries is one `workspace/executeCommand` + // actually runs — the two halves are declared in different places and + // could drift apart without ever failing to compile. + let dir = temp_dir("codelens"); + let sub = dir.join("lens_sub.sv"); + std::fs::write(&sub, LENS_SUB).expect("write"); + let top = dir.join("lens_top.sv"); + std::fs::write(&top, LENS_TOP).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", sub.display()); + let top_uri = format!("file://{}", top.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(LENS_SUB).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeLens","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + frame( + r#"{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{"command":"lucisv.showInstantiations","arguments":["lens_sub"]}}"#, + ), + // A buffer the server was never sent answers `null`, not an empty list. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/codeLens","params":{{"textDocument":{{"uri":"{top_uri}"}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) + }; + + let capabilities = &response(1)["result"]["capabilities"]; + assert_eq!( + capabilities["codeLensProvider"], + serde_json::json!({ "resolveProvider": false }), + "{capabilities:#?}" + ); + let commands = + capabilities["executeCommandProvider"]["commands"].as_array().expect("the command list"); + assert!( + commands.contains(&serde_json::json!("lucisv.showInstantiations")), + "the lens's command has to be advertised to be runnable: {commands:#?}" + ); + + let lenses = response(2)["result"].as_array().expect("a lens list"); + assert_eq!(lenses.len(), 1, "{lenses:#?}"); + assert_eq!(lenses[0]["command"]["title"], "2 instantiations"); + assert_eq!(lenses[0]["command"]["command"], "lucisv.showInstantiations"); + assert_eq!(lenses[0]["command"]["arguments"], serde_json::json!(["lens_sub"])); + assert_eq!( + lenses[0]["range"], + serde_json::json!({ + "start": { "line": 0, "character": 7 }, "end": { "line": 0, "character": 15 } + }), + "the declaration's own name, so the lens draws above the header" + ); + assert!(lenses[0].get("data").is_none(), "nothing left for a resolve: {:#?}", lenses[0]); + + let sites = response(3)["result"].as_array().expect("a location list"); + assert_eq!(sites.len(), 2, "the count the lens showed, as places: {sites:#?}"); + assert_eq!(sites[0]["uri"], top_uri.as_str()); + assert_eq!(sites[0]["range"]["start"], serde_json::json!({ "line": 1, "character": 2 })); + assert_eq!(sites[1]["range"]["start"], serde_json::json!({ "line": 2, "character": 2 })); + + assert!(response(4)["result"].is_null(), "an unopened buffer: {:#?}", response(4)); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() { + // A rescan can change any count on screen, so a client holding lenses has + // to be told to ask again — and only a client that said it can be. + let dir = temp_dir("codelensrefresh"); + let sub = dir.join("lens_sub.sv"); + std::fs::write(&sub, LENS_SUB).expect("write"); + std::fs::write(dir.join("lens_top.sv"), LENS_TOP).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", sub.display()); + + let script = |capabilities: &str| { + [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{capabilities}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(LENS_SUB).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat() + }; + + let refreshes = |messages: &[serde_json::Value]| -> usize { + messages.iter().filter(|m| m["method"] == "workspace/codeLens/refresh").count() + }; + + let capable = talk(&script(r#"{"workspace":{"codeLens":{"refreshSupport":true}}}"#)); + assert_eq!(refreshes(&capable), 1, "one per rescan, and the save is one: {capable:#?}"); + + let silent = talk(&script("{}")); + assert_eq!(refreshes(&silent), 0, "a client that did not ask is never told: {silent:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/code-lens/README.md b/docs/features/code-lens/README.md new file mode 100644 index 0000000..b27607f --- /dev/null +++ b/docs/features/code-lens/README.md @@ -0,0 +1,568 @@ +# code-lens + +## Goal + +`textDocument/codeLens` puts one line of true, computed information above +every module and interface declaration in the open buffer: **"N +instantiations"** — how many times the whole workspace instantiates that +module — with "1 instantiation" and "no instantiations" spelled the way a +person would. It is the single most Verilog-shaped thing a lens can say: a +module's fan-in is the number an RTL engineer actually wants when they open a +file, and until now it took opening the call hierarchy to learn it. Clicking a +lens answers with every instantiation site, and — for a client that advertised +`window/showDocument` — jumps to the first of them. The count is not a second +census: it is computed by the very walk `callHierarchy/incomingCalls` is +computed by, so the lens and the hierarchy view can never disagree (TODO.md +§9c). + +## Assumptions + +- **The population is `incomingCalls`'s population, and nothing else.** N is + the number of instantiation *sites* — the sum of every `fromRanges` entry + `callHierarchy/incomingCalls` would list for that module, not the number of + instantiating modules. A module instantiated twice inside one `top` reads + "2 instantiations", because that is what a user counting instances means. + `the_count_is_exactly_what_incoming_calls_would_list` asserts the equality + directly rather than restating the arithmetic. +- **An instantiation at file scope is not counted**, because it has no + enclosing module to be a caller. That is inherited, not decided here: it is + the rule `hierarchy::callers_in` already applied, and the whole point of + reusing the census is that this feature does not get to have its own + opinion. Such a file is illegal SystemVerilog anyway and only reachable + through the tolerant parser. +- **The census is by name.** Two modules named `fifo` in one workspace get the + same count on both their lenses, and clicking either shows every site of + either. Same limitation `callHierarchy/incomingCalls` has, for the same + reason: an instantiation names a module, and nothing in the source says + which of two same-named declarations it meant. +- **The lens's range is the declaration's own name span.** Clients draw a lens + on the line *above* `range.start`, so the name span puts it directly over + the header and nowhere else. A declaration whose name span is empty — what + the tolerant parser produces for `module ;` — gets no lens: there is no line + to sit on, and an invented one would decorate the wrong code. +- **An interface is a module declaration.** `interface bus; ... endinterface` + parses to the same `ast::Module` node with `kw == "interface"`, so it is + reached by `instantiations::declarations` and instantiated through the same + `ItemKind::Instantiation`. No branch was written for it; a test pins that it + works. +- **`resolveProvider: false`, and every lens is complete.** Title, command and + arguments are all computed up front, matching what completion, inlay hints + and document links do in this server. The count is the expensive part and it + is exactly what a resolve would have to compute, so a two-stage protocol + would buy nothing. +- **A module with no instantiations gets a display-only lens** — a `Command` + whose `command` is the empty string, which is what rust-analyzer ships for + the same case and what clients render as plain text. There is nothing to + open; a click that led to an empty list would be worse than no click. It + also carries no `arguments`. +- **`window/showDocument` shows only the first site.** LSP has no + server-initiated "peek these seven places" — that is VS Code's + `editor.action.showReferences`, a *client-side* command, and this repo's + extension declares none (and this round did not touch `editors/`). The + honest portable behaviour is: the command's result is the full list of + `Location`s, for any caller that wants it, and the push opens the first one + for a client that can be pushed to. A client without the capability still + gets the list. +- **`workspace/codeLens/refresh` is sent from `reindex()` only.** Not at + startup: no buffer is open there, so there are no stale lenses to + invalidate. Not on a keystroke either — a `didChange` cannot change any + count, since the census is over instantiations in *other* files and a client + re-requests lenses for the buffer it just edited anyway. +- **The count is computed against `Workspace::sources()`**, which reads every + in-scope file from disk with open buffers overriding it. So an unsaved + instantiation typed into another open buffer *is* counted, and a file + changed on disk that no watcher reported is counted as of this request. +- **The cost is one workspace walk per request, not one per module.** + `hierarchy::callers_of_each` takes a batch precisely because `sources()` + re-reads the whole file set: measured over the 860-file corpus, a + three-module file costs 133 ms against 93 ms for a single name (debug build) + — amortized, not tripled. The absolute number is the honest cost of having + no instantiation-edge table in the index; see Status / TODO. + +## Handshakes + +### Request to `vlog_semantic` — an instantiation-edge table in the index + +Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped +features now pay the same cost: every `textDocument/codeLens` request and +every `callHierarchy/incomingCalls` walks `Workspace::sources()` — a re-read +and tolerant re-parse of every in-scope file — because `WorkspaceIndex` +records what a file *declares* and never what it *instantiates*. The ask: at +index build time (the same rebuild `reindex()` already pays for), record the +instantiation edges, e.g. + +```rust +/// Every instantiation of `name` across the indexed files: +/// (file, instantiating-module name span, instance site span). +pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge] +``` + +so `hierarchy::callers_of_each` becomes a lookup and its whole +walk-and-parse body is deleted. The census policies (multi-instance +statements = one site, textual not elaborated, both `ifdef` arms) must carry +over unchanged — `lens.rs`'s QA tests pin the numbers that must not move. + + +### `lucisv_server::hierarchy` — **changed, deliberately** + +`incoming` was split so the census has exactly one implementation: + +- **New public** `hierarchy::callers_of_each(ws, names: &[&str]) -> + Vec>` — the same walk, asked about a batch of + names, answering one list per name in the order asked. It is now the + primitive. +- `hierarchy::incoming(ws, item)` is a one-line call into it with a + one-element batch. **Its behaviour is unchanged**, empty-name guard + included: the guard moved into the batch's per-name filter, where an empty + name matches no file rather than every file. +- The private `callers_in` now takes an already-parsed file (`&Uri`, + `&Positions`, `&[Site]`) instead of a path and text, so one file is parsed + once for a whole batch rather than once per name. The `Positions` for a file + is now built whenever any name matches, rather than only when a caller was + found — a `LineIndex::new` per candidate file, which the batch more than + pays back. + +Nothing else in `hierarchy.rs` moved, and its own tests are untouched and +green. + +### `lucisv_server::server` + +- `ClientAbilities` gains **two** fields, both filled in `main.rs`: + `code_lens_refresh` (from `workspace.codeLens.refreshSupport`) and + `show_document` (from `window.showDocument.support`). Every existing test + that builds `ClientAbilities { ..Default::default() }` is unaffected. +- `request()` gains a `CodeLensRequest` arm, and its `ExecuteCommand` arm now + routes `lucisv.showInstantiations` to `lens::execute` before falling through + to `ports::execute`. +- New private `show_instantiations(Vec) -> Result` + (the answer, plus the optional push) and `refresh_code_lenses()` (the gated + server-initiated request). +- `reindex()` calls `refresh_code_lenses()` immediately after + `end_indexing(bar)` and before the generation bump, the scope warnings and + the republishes. Pinned by + `the_refresh_rides_after_the_indexing_bar_comes_down`. +- `response()`'s doc comment now names four ignorable answers rather than two. + Its code is unchanged: the refresh's and the showDocument's ids are never in + `applying`, so they fall through the existing lookup. + +### `lucisv_server::main` + +- `capabilities()` gains `code_lens_provider: Some(CodeLensOptions { + resolve_provider: Some(false) })`. +- `execute_command_provider.commands` is now a new local `commands()` — + `ports::commands()` plus `lens::commands()` — rather than `ports::commands()` + alone. A lens whose command is not advertised is a lens no client will run, + so `every_advertised_command_is_one_the_server_runs` now checks both halves. + +### `state::Workspace`, `vlog_parser`, `vlog_semantic`, `vlog_refactor` + +**Untouched.** No signature moved and nothing was plumbed. The declarations +come from `instantiations::declarations`, which already existed for the +hierarchy, and the counts from `Workspace::sources()`, which already existed +for it too. + +### `editors/vscode` + +**No extension change**, and none was made. `vscode-languageclient` requests +code lenses and renders them with no help from `extension.js`; it advertises +`workspace.codeLens.refreshSupport` and `window.showDocument` itself. +`smoke.js` sends `capabilities: {}`, so it takes the no-refresh, +no-showDocument path — verified by running it. + +## Status / TODO + +- [x] `codeLensProvider` advertised with `resolveProvider: false` +- [x] `textDocument/codeLens` dispatched; one lens per module/interface + declaration, on the name span, in source order +- [x] Count reuses the `incomingCalls` census (`hierarchy::callers_of_each`), + with an equality test against `hierarchy::incoming` +- [x] Pluralization: "no instantiations" / "1 instantiation" / "N + instantiations" +- [x] `lucisv.showInstantiations` advertised and dispatched; answers every site + as a `Location`; declines arguments it cannot read as `RequestFailed` +- [x] `window/showDocument` pushed for the first site, gated on the client + capability +- [x] `workspace/codeLens/refresh` from `reindex()`, gated on + `workspace.codeLens.refreshSupport`, after the progress bar comes down +- [x] Unopened buffer → `null`; unnamed declaration → no lens; a buffer that + parses to nothing → empty list +- [x] Tests: 33 (19 in `lens.rs`, 9 in `server.rs`, 3 in `main.rs`, 2 e2e) +- [x] TODO.md §9c checkbox, `docs/features/lucisv-server/README.md` capability + table +- [ ] **Not done, deliberately:** no second lens kind. A "top module" + indicator, a parameter count, a "run this testbench" action are all + plausible and none was asked for; one lens kind done well beats three + guessed at. +- [ ] **Not done, deliberately:** no `codeLens/resolve`. Everything a resolve + could defer is the one expensive thing the lens *is*. +- [ ] **Not done, deliberately:** no peek-references behaviour. It needs a + client-side command declared in `editors/vscode/package.json`, which is + out of this round's scope; `window/showDocument` is the portable + substitute and reaches Neovim as well. +- [ ] **Open, filed here:** the request costs one full `Workspace::sources()` + read — 133 ms over the 860-file corpus in a debug build. That is the + same cost `callHierarchy/incomingCalls` has always had, but a lens + request arrives far more often than a hierarchy question. The real fix + is an instantiation-edge table in `WorkspaceIndex`, built once per + rescan, which would make both this and `incomingCalls` a lookup. That is + a `vlog_semantic` change and belongs in its own round; **request + recorded here, not made.** + +## Work log + +### 2026-08-26 — dev agent, §9c + +- **The click-behaviour decision, and why.** The brief left this open with a + fallback to display-only. I built the real jump, because reading + `hierarchy::incoming` showed the locations were *already there* — every + `fromRanges` entry is a site, paired with its file's URI — so + `lucisv.showInstantiations` is a flatten and nothing more. The chain the + brief worried might be heavy is about fifteen lines: `lens::execute` returns + `Vec`, `Server::show_instantiations` pushes a + `window/showDocument` for the first when the client advertised it, and the + answer is the list either way. Display-only survives as the honest answer for + the **zero** case only, where there is nothing to open — which is exactly + where rust-analyzer uses the same empty-command trick. So: real behaviour + everywhere it can mean something, display-only where it cannot. +- **The arguments are `[module-name]`, not `[uri, name]`.** The brief + suggested the URI first, in the style of the port commands. I dropped it + after establishing that the census is *purely* by name — + `hierarchy::incoming` reads only `item.name` and nothing else off its item — + so a URI would be an argument the handler receives and ignores, and this + repo does not ship those. One argument, all of it used. +- **A name the workspace does not declare is not an error.** The brief asked + for one. I did not build it, and the reason is a real failure mode rather + than taste: the only index-backed way to ask "is this a module?" is + `WorkspaceIndex::units`, and the index is rebuilt on *save*, so a module + just typed into an open buffer is genuinely absent from it. Gating on that + would make the command refuse the very lens that is on screen. Malformed + arguments (missing, non-string, empty) are still declined as + `RequestFailed`, per `ports.rs`; a well-formed name with no sites answers + `[]`, which is the truth. +- **The census was extracted rather than duplicated, and the batch is why.** + Naively, `code_lenses` would call `hierarchy::incoming` once per module in + the buffer — but `Workspace::sources()` re-reads every in-scope file from + disk on *each* call, so a three-module file would read the workspace three + times. So `incoming`'s body became `callers_of_each(ws, names)`, which reads + the file set once and parses each candidate file once for the whole batch; + `incoming` is now that function with a one-element batch. Measured over the + 860-file corpus: three names 133 ms, one name 93 ms — amortized, and pinned + by `code_lenses_for_a_whole_file_cost_about_one_workspace_walk`, which fails + if the ratio ever goes linear. +- **The empty-name guard moved and got stricter.** It used to be an early + return in `incoming`; it is now a per-name filter inside the batch, so one + empty name in a batch of five costs nothing and cannot make the prefilter + match every file. Same behaviour for `incoming`, which is still the only + caller that could ever be handed one. +- **The lens sits on the name span, not the header line.** Clients draw the + lens on the line above `range.start`; the name span and the header line have + the same start line, but the name span is the one that stays right when a + declaration is written with attributes or a leading comment on the same + line. +- **Refresh placement.** Straight after `end_indexing(bar)` in `reindex()`, + following the progress round's own precedent that the bar names the scan and + everything after it is work on the scan's result. Order pinned by a test + (`create, begin, end, refresh`) so it cannot drift silently. Nothing is sent + at startup — there is no open buffer holding lenses there. +- **A buffer with no named declarations returns before the workspace walk.** + Otherwise opening a package or a header file would read every file in the + project to produce an empty list. +- Files touched: `crates/lucisv_server/src/lens.rs` (new), + `crates/lucisv_server/src/hierarchy.rs`, + `crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/main.rs`, + `crates/lucisv_server/tests/e2e.rs`, `TODO.md`, + `docs/features/lucisv-server/README.md`, this README. No engine crate, no + `editors/`, no new dependency, no version bump. + +**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy +--all-targets`: zero warnings. `cargo test --workspace`: **1943 passed, 0 +failed** (1910 on `HEAD` `34938fb`, measured — 33 new). `cargo build && node +editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`, exit 0. No +commits. + +The 33 tests, and what each group is for: + +| tests | pin | +|---|---| +| `lens.rs` — `a_lens_counts_every_instantiation_in_the_workspace`, `the_title_counts_in_the_users_own_arithmetic` | the cross-file count, and 0/1/N pluralization including "not `1 instantiations`" | +| `lens.rs` — `the_count_is_exactly_what_incoming_calls_would_list` | the agreement with `hierarchy::incoming`, asserted against its live answer rather than against a number | +| `lens.rs` — `an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it` | the inherited caller rule, stated so a future change to it is visible here | +| `lens.rs` — `the_lens_sits_on_the_declarations_own_name`, `every_module_in_a_file_gets_its_own_lens_in_source_order` | the range is the name span; one lens per declaration, source order | +| `lens.rs` — `an_interface_is_a_module_declaration_and_gets_its_own_lens` | interfaces, which needed no branch | +| `lens.rs` — `a_module_nothing_instantiates_gets_a_lens_that_does_not_click`, `a_clickable_lens_carries_the_module_name_as_its_only_argument`, `no_lens_is_ever_left_for_a_resolve_to_fill_in` | the two command shapes, and that nothing is left unresolved | +| `lens.rs` — `a_buffer_this_server_was_never_shown_has_no_lenses_at_all`, `a_buffer_that_declares_no_module_gets_an_empty_list`, `a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic`, `a_declaration_the_parser_could_not_name_gets_no_lens` | the four refusals: `null`, empty, total on junk, no lens without a name span | +| `lens.rs` — `the_command_answers_one_location_per_site`, `..._nothing_for_a_module_nothing_instantiates`, `..._declines_arguments_it_cannot_read`, `the_command_list_is_what_the_server_advertises` | the command: one location per site in file-then-position order, the empty answers, the refusals | +| `lens.rs` — `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` | the batch really is one walk (corpus, skipped when absent) | +| `server.rs` — `a_code_lens_request_counts_the_workspaces_instantiations`, `..._for_an_unopened_buffer_answers_null` | dispatch, and the `null` | +| `server.rs` — `the_show_instantiations_command_answers_every_site`, `..._pushes_a_show_document_when_it_can`, `a_module_with_no_instantiations_pushes_nothing_and_shows_nothing`, `..._declines_arguments_it_cannot_read` | the command over the dispatch, both `showDocument` gate states, and the `RequestFailed` code | +| `server.rs` — `a_rescan_asks_a_capable_client_to_refresh_its_code_lenses`, `a_client_that_cannot_refresh_code_lenses_is_never_asked_to`, `the_refresh_rides_after_the_indexing_bar_comes_down` | both polarities of the refresh gate, all three rescan paths, no refresh at startup, and the order against the progress bar | +| `main.rs` — `code_lenses_resolve_nothing_because_every_lens_is_complete`, `code_lens_refresh_support_...`, `show_document_support_...` | the advertised option, and both capability readers at absent/false/true | +| `e2e.rs` — `code_lenses_and_their_command_round_trip_over_the_wire` | the capability's JSON shape, the lens JSON (title, command, arguments, range, no `data`), the command's locations, the `null`, and that the lens's command is in `executeCommandProvider.commands` | +| `e2e.rs` — `a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire` | the refresh on the wire, both gate states, against the real binary | + +## QA log + +- **2026-08-26 (QA)** — read this README, `hierarchy/README.md` (its QA log + especially — the `ifdef` and generate-replication findings there turned out + to answer several questions this round would otherwise have raised fresh), + `instantiations.rs`, `hierarchy.rs` end to end (diffed function-by-function + against `34938fb`), `lens.rs`, and the `server.rs`/`main.rs` diffs, before + touching anything. + + **Gates, independently re-run.** `cargo fmt --all -- --check`: clean. + `cargo clippy --all-targets --workspace`: zero warnings. `cargo test + --workspace`: **1943 passed, 0 failed** before any QA change, matching the + dev's number exactly; **1952 passed, 0 failed** after adding 9 QA tests (6 + in `lens.rs`, 3 in `server.rs` — see below). `cargo build && node + editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`, exit 0, + run twice (before and after the QA tests). + + **1. The `hierarchy.rs` refactor.** Diffed `git show + 34938fb:crates/lucisv_server/src/hierarchy.rs` against the working tree + function by function. `incoming` is now `callers_of_each(ws, + &[item.name.as_str()]).pop().unwrap_or_default()` — a one-element batch. + Confirmed by construction that `callers_of_each`'s per-file loop is + unchanged in substance: same `parse_source_tolerant` (not the strict + parser — a mode change would have silently changed counts on broken files, + and it did not happen), same `site.inst.module != name` filter inside + `callers_in`, same final sort. The only real change is *where* the + prefilter and the parse happen: once per name before (`callers_in` took + `path: &Path, text: &str`), once per **file** now, with the parsed `sites` + reused across every name the batch is asking about. + - *Empty name in a batch.* Traced by hand: `wanted` filters out any index + whose name is empty or absent from the file's text, so an empty name + never reaches `callers_in` and its slot in `answers` stays `Vec::new()`. + Byte-identical to the old early-return in `incoming`. No new test needed + — the dev's own doc comment states this and it holds. + - *Duplicate names in one batch, `["m", "m"]`.* New test + `qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count` + (`lens.rs`) — a file with two `module m` declarations (reachable through + the tolerant parser) instantiated once, opened as a buffer. Both indices + are processed independently (the loop does not deduplicate `wanted`), so + neither aliases nor corrupts the other — both lenses read "1 + instantiation". Redundant work (the same file is walked twice for the + same name), not a correctness bug. + - *A name that is a package, not a module.* Not a distinct code path: + `callers_of_each` matches purely on `site.inst.module`, a string, with no + knowledge of what kind of thing owns that name. Nothing to test beyond + what `hierarchy.rs`'s own `qa_instantiation_in_a_package_does_not_crash` + already covers. + - **Verdict: behavior-preserving.** `incoming`'s own 25 tests are untouched + and green, which is necessary but — per the brief — not sufficient; the + above traces the edge cases a black-box test-pass rerun cannot see, and + none of them diverge. + + **2. Count honesty.** The Assumptions section already states the load-bearing + facts: *the population is `incomingCalls`'s, by name, and one `Instantiation` + is one site "however many instances it declares"* — that last part is + `hierarchy.rs`'s own documented policy (2026-08-25 QA round), inherited + rather than decided here. Checked whether the fixture agreement test would + actually catch a divergence: it cannot, structurally — `lens.rs` and + `hierarchy::incoming` both bottom out in the literal same + `hierarchy::callers_of_each` call, so "agreement" is guaranteed by + construction, not by the fixture's shape. What the fixture's shape *does* + affect is whether **this feature's own test suite** would notice if that + shared implementation's semantics ever changed under it — e.g. if + `callers_of_each` started counting instances instead of AST nodes, no + existing `lens.rs` test using `TOP` (two separate statements) would catch + it, because two separate statements give the same answer either way. Added + 6 tests to `lens.rs` pinning the number itself over shapes the fixture + never exercises, each with expected output derived independently (by + reading `instantiations.rs`'s `walk`, not by running the code first): + - `qa_a_multi_instance_statement_is_one_site_not_two` — `sub u1 (), u2 + ();` is **one** `Instantiation` node with two `Instance` entries, and + reads "1 instantiation", one `Location`. Matches + `hierarchy/README.md`'s stated policy exactly (it names this exact + source shape). Not a finding — a confirmed, disclosed design decision — + but it was untested at the code-lens layer, where a user is more likely + to notice the number than in a hierarchy view. + - `qa_a_module_that_instantiates_itself_counts_its_own_instantiation` — + self-recursion reads "1 instantiation", one site, no hang. Consistent + with `hierarchy.rs`'s own self-instantiation and cycle handling (each + request answers one hop). + - `qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both` + — two files each declaring `module m`, one real instantiation of `m` + elsewhere: opening *either* declaration reads "1 instantiation" — the + workspace-wide total, not zero and not partitioned. Matches the + documented "census is by name" Assumption; confirms it holds in both + directions (the fixture I found only tried one file, not the other). + - `qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count` + — described above under the hierarchy refactor; also a code-lens-level + consequence of the same policy: **two lenses**, same count on both, in + one buffer. + - `qa_a_generate_replicated_instantiation_counts_the_written_statement_once` + — a `generate for` loop wrapping one instantiation reads "1 + instantiation" regardless of the genvar's range (textual, not + elaborated), matching `hierarchy.rs`'s own precedent for the identical + shape. + - `qa_an_ifdef_guarded_instantiation_counts_both_arms` — `` `ifdef``/`` + `else`` both arms read "2 instantiations". This is `hierarchy.rs`'s + disclosed `ifdef` policy (2026-08-25 finding, fixed by documentation + then) surfacing on a second, more visible feature. Not re-litigated here + since the underlying behavior was already reviewed and accepted by the + lead; pinned so a change to it is visible from `lens.rs` too, not only + `hierarchy.rs`. + + None of the six disagreed with `hierarchy::incoming` (they structurally + cannot), and none exposed a new corruption or miscount — every number + above is the intentional, already-documented arithmetic. The value added is + regression coverage at the layer users actually read the number from. + + **3. Cost / request amplification.** Traced `code_lenses` in `lens.rs`: + one call to `hierarchy::callers_of_each(ws, &names)` with the *whole* + buffer's declared names, which itself calls `ws.sources()` exactly once + inside its single `for (path, text) in ws.sources()` loop — confirmed by + reading the loop body, not by profiling. No per-lens or per-module + `sources()` call exists anywhere in the path from `CodeLensRequest` to the + answer. The **index-table follow-up**: filed in Status/TODO ("an + instantiation-edge table in `WorkspaceIndex`... request recorded here, not + made"), in the same style as `hierarchy/README.md`'s own equivalent backlog + bullet from the prior round — consistent with house precedent, but neither + one is written as a *concrete* Handshake (a proposed `vlog_semantic` + function signature and contract) the way CLAUDE.md's Handshakes section is + meant to capture a cross-module request. **Minor, LOW severity, not fixed**: + recommend the lead decide whether a backlog TODO bullet is sufficient here + (matching existing house style) or whether, now that *two* features would + benefit from the same index change, it is worth promoting to an actual + Handshakes-section proposal with a named function shape. Not fixed + unilaterally — this is a documentation-structure judgment call, not a typo. + + **4. `showDocument` push.** Read `show_instantiations` and `deliver` side + by side: `deliver` is the only function that inserts into `self.applying`; + `show_instantiations` calls `send_request(ShowDocument::METHOD, ...)` + directly and never touches `applying`, so its response id always falls + through `response()`'s `let Some(command) = self.applying.remove(...) else + { return }` — exactly the mechanism the doc comment claims. Confirmed via + the dev's own tests that the gate (`self.abilities.show_document`) is + checked before the push, that a client without it still gets the full + location list, and that the pushed request's shape (`uri` of the first + site, `takeFocus: true`, `selection` = that site's range) is correct. + **New test** + `qa_a_showdocument_push_and_an_applyedit_push_stay_independent_when_both_are_outstanding` + (`server.rs`) — one `PROPAGATE_PORTS` command outstanding (an `applyEdit` + push, tracked in `applying`) and one `SHOW_INSTANTIATIONS` command + outstanding (a `showDocument` push, not tracked) at the same time, + answered in reverse send order. The showDocument answer produces no + message (correctly ignored even though it carries no `applied` field at + all, which would be a type-mismatch panic risk if `response()` ever tried + to interpret it as an `ApplyWorkspaceEditResponse`); the applyEdit answer + is still routed to its own command correctly afterward. This was asked for + explicitly in the brief and had no existing test — ids are allocated by a + strictly increasing counter (`send_request`), so collision was never + actually possible, but the mechanism is now pinned rather than just argued. + Also confirmed by reading the `ExecuteCommand` dispatch arm: + `lucisv.showInstantiations` returns from inside the `if` before + `ports::execute`'s `Ok((edit, warnings)) => self.deliver(...)` branch is + ever reached, so `deliver()` cannot fire for it — no test needed beyond the + existing `the_show_instantiations_command_answers_every_site` asserting + `session.requests().is_empty()` for a client without `apply_edit` either. + + **5. Refresh discipline.** Verified independently: `refresh_code_lenses` + gates only on `self.abilities.code_lens_refresh`, never on + `work_done_progress` — the dev's own + `a_rescan_asks_a_capable_client_to_refresh_its_code_lenses` already uses + `ClientAbilities { code_lens_refresh: true, ..Default::default() }` (so + `work_done_progress` is `false`) and gets three refreshes, which is the + independent-gates case the brief asked about, already covered. Never at + startup (`reindex` is not called there). **New test** + `qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh` + (`server.rs`) — two open buffers, one save: exactly one + `workspace/codeLens/refresh`, confirming the call sits before the + per-buffer republish loop in `reindex()` rather than inside it (the dev's + existing test only ever opened one buffer, so this distinction was + argued from reading the code, not from a test, before now). Order-pinned + by the dev's own `the_refresh_rides_after_the_indexing_bar_comes_down`; + re-verified by hand against `reindex()`'s body. Response ignored: same + `applying`-lookup mechanism as `showDocument`, covered by the new + interleaving test's reasoning (refresh never inserts into `applying` + either). + + **6. Command surface.** `execute_command_provider.commands` is `commands()` + = `ports::commands()` ++ `lens::commands()`; `main.rs`'s own + `every_advertised_command_is_one_the_server_runs` now checks both halves + are contained, not just equality with the concatenation (equality alone + would not have caught one list silently dropping an entry the other + didn't add back). `git diff --stat -- crates/lucisv_server/src/ports.rs` + confirms it is untouched. Confirmed by reading the `ExecuteCommand` arm + (see point 4) that `lucisv.showInstantiations` never reaches `deliver()`. + + **7. CLAUDE.md compliance.** `grep` for `unwrap()`/`expect(`/`panic!` in + `lens.rs` and `hierarchy.rs` outside `#[cfg(test)]`: none. Same check + against the added lines in `server.rs`/`main.rs`: every hit is inside + `mod tests`. No `#[allow(...)]`, no `unsafe`, anywhere in the diff. Every + public item in `lens.rs` carries a one-line doc comment. `TODO.md`'s §9c + item text is untouched — only the checkbox flipped to `[x]`, with a + "→ delivered" paragraph appended below it, matching the rule ("leave the + item text intact"). This README's seven sections are each present exactly + once. + + **C. Corpus, machine-checked.** New test + `qa_corpus_counts_agree_with_grep_derived_ground_truth` (`lens.rs`), + against `corpus/common_cells/src/cdc_fifo_gray.sv` (three module + declarations, same file the dev's own perf test already uses). Ground + truth built by hand with `grep -rnE '\bNAME\b' corpus --include='*.sv' + --include='*.svh'`, read line by line to exclude the declaration itself + and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has several, e.g. + "In contrast to the cdc_fifo_gray version..." — a real risk if the walk + ever matched comment text, which `instantiations::sites` structurally + cannot): + | module | grep-derived instantiation sites | lens read | + |---|---|---| + | `cdc_fifo_gray` | 1 (`common_cells/test/cdc_fifo_tb.sv:49`, `i_dut`) | "1 instantiation" | + | `cdc_fifo_gray_src` | 1 (`cdc_fifo_gray.sv:130`, inside `cdc_fifo_gray` itself) | "1 instantiation" | + | `cdc_fifo_gray_dst` | 1 (`cdc_fifo_gray.sv:145`, inside `cdc_fifo_gray` itself) | "1 instantiation" | + All three agree. Run in release (`cargo test -p lucisv_server --release + qa_corpus_counts_agree_with_grep_derived_ground_truth -- --nocapture`); + skips cleanly when `corpus/` is not checked out, matching the dev's own + corpus test's pattern. + + **Everything else tried to break, and did not:** + - A workspace root fixture helper (`Tree::write` in `lens.rs`'s tests) did + not create parent directories, so a nested relative path (`"a/m.sv"`) + failed with `NotFound` the first time this round's cross-file-collision + test tried to use one. **Fixed directly** (`fs::create_dir_all` on the + parent before `fs::write`) — an unambiguous test-infrastructure gap, not + a behavior change, and it was blocking test C's fixture from being + written at all. + - Malformed `executeCommand` arguments (missing, non-string, empty string) + for `lucisv.showInstantiations`: all three still answer `RequestFailed` + with a message naming "module name" — re-verified against the dev's own + `the_command_declines_arguments_it_cannot_read` and + `the_show_instantiations_command_declines_arguments_it_cannot_read`. + - A name the workspace does not declare (`"never-heard-of-it"`): `[]`, not + an error, as documented and tested by the dev. + - `resolveProvider: false` and every lens carrying a complete `Command` + with no `data`: re-verified against `no_lens_is_ever_left_for_a_resolve_to_fill_in`. + + **Verdict: committable as-is.** No corruption, no idempotency risk (this + feature touches no formatter output), no dropped comments — none of those + invariants are in this feature's blast radius at all, since it only reads + and answers LSP requests. The one open item (point 3, the index-table + request's concreteness) is a documentation-polish question for the lead, + not a defect, and does not block shipping. 9 new tests added, all green; + gates re-run clean before and after. No commits made. + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself, +clean. The round's two judgment calls were both right. Building the real +jump instead of the display-only fallback cost ~15 lines because the +locations already existed — exactly the "check what the code makes clean" +outcome the brief asked for — and the zero-count lens staying display-only +matches rust-analyzer's precedent. The hierarchy.rs refactor is the +correct shape: one census with the batch as the primitive, `incoming` as a +one-element batch, and the corpus ratio test making the amortization a +tested property instead of a hope. I read the refactor diff myself and +concur with QA's function-by-function verdict — same parse mode, same +filters, the empty-name guard equivalent in its new position. + +QA's count-honesty tests were the right instinct: the agreement test +alone cannot catch semantic drift when both paths share one function, so +pinning the absolute policies (multi-instance = one site, textual +recursion, both ifdef arms) at the lens layer is what actually holds the +numbers still. On QA's LOW finding, I agreed and promoted the +index-table request to a concrete Handshakes entry with a named shape — +two features now pay the sources() walk, which is exactly when a backlog +bullet stops being enough. Accepted as shipped. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index ad0d7a6..4ecef74 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -41,8 +41,11 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README | | `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` | | `textDocument/prepareCallHierarchy` | `instantiations::{sites,declarations}`, `WorkspaceIndex::units` | The module under the cursor as a hierarchy node (`SymbolKind::Module`), from its own declaration or from any instantiation of it. Every other position answers `null`; an ambiguous name returns every declaration, as `definition` does. See `docs/features/hierarchy/README.md` | -| `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Same feature README | +| `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README | | `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README | +| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same walk asked about every module in the file at once, so the two can never disagree. `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` | +| `workspace/executeCommand` → `lucisv.showInstantiations` | `hierarchy::callers_of_each` | The code lens's own jump: `["module-name"]` in, every site as a `Location` out — one per site, file-then-position order. For a client that advertised `window.showDocument`, the server also pushes a `window/showDocument` for the **first** site, which is what makes the click navigate; LSP has no server-initiated peek-references, and this repo's extension declares no client-side command. A name with no sites answers `[]`; a missing or empty name is `RequestFailed`. Same feature README | +| `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README | | `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits | | `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` | | `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` |