From a96c908a3e95d9d3f87500c8325e5c616ea80d90 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Tue, 25 Aug 2026 01:15:38 -0700 Subject: [PATCH] Hierarchy M11: who instantiates X, what X instantiates LSP callHierarchy with modules as the nodes: prepare on a declaration or any instantiation, incoming grouped by instantiating module with every site as a fromRange, outgoing one call per distinct instantiated module. The instantiation walk moved out of inlay hints into a shared module with the owning module threaded through - inlay's 34 untouched tests prove the factoring changed nothing. A substring prefilter skips 834 of 860 corpus files before parsing (56ms incoming on a real module; the prefilter-defeating worst case is documented at ~206ms). ifdef arms both count, disclosed; incoming/outgoing consistency QA-verified. Co-Authored-By: Claude Fable 5 --- TODO.md | 2 +- crates/vfmt_server/src/hierarchy.rs | 994 +++++++++++++++++++++++ crates/vfmt_server/src/inlay.rs | 68 +- crates/vfmt_server/src/instantiations.rs | 242 ++++++ crates/vfmt_server/src/main.rs | 25 +- crates/vfmt_server/src/server.rs | 29 +- crates/vfmt_server/tests/e2e.rs | 189 +++++ docs/features/hierarchy/README.md | 488 +++++++++++ docs/features/inlay-hints/README.md | 13 + docs/features/refactor/README.md | 3 +- docs/features/vfmt-server/README.md | 36 + 11 files changed, 2019 insertions(+), 70 deletions(-) create mode 100644 crates/vfmt_server/src/hierarchy.rs create mode 100644 crates/vfmt_server/src/instantiations.rs create mode 100644 docs/features/hierarchy/README.md diff --git a/TODO.md b/TODO.md index ac379d6..30ef1eb 100644 --- a/TODO.md +++ b/TODO.md @@ -607,7 +607,7 @@ section only tracks the milestones. - [x] **M10 `include-nav`** — clickable `` `include`` lines resolved through the filelist's `+incdir+`s; cross-file `` `define`` lookup along the include graph. -- [ ] **M11 `hierarchy`** — module hierarchy both directions (who +- [x] **M11 `hierarchy`** — module hierarchy both directions (who instantiates X / what X instantiates) over LSP callHierarchy. - [ ] **M12 `semantic-lints`** — unused-signal, undriven-net, multiply-driven: the first semantic lint rules on `vlog_semantic`. diff --git a/crates/vfmt_server/src/hierarchy.rs b/crates/vfmt_server/src/hierarchy.rs new file mode 100644 index 0000000..72cb127 --- /dev/null +++ b/crates/vfmt_server/src/hierarchy.rs @@ -0,0 +1,994 @@ +//! `textDocument/prepareCallHierarchy`, `callHierarchy/incomingCalls` and +//! `callHierarchy/outgoingCalls` — the module hierarchy, both directions. +//! +//! LSP's call hierarchy is a graph of callers and callees, and a design's +//! module hierarchy is exactly that graph under different names: the modules +//! are the nodes and an instantiation is the call. So "who instantiates +//! `fifo`?" is `incomingCalls` and "what does `fifo` instantiate?" is +//! `outgoingCalls`, drawn by every LSP client's own hierarchy view without a +//! line of editor code. +//! +//! Each request answers **one hop**. The client drives the expansion, so a +//! module that instantiates itself, or an `a → b → a` pair, needs no cycle +//! handling here: nothing recurses, and the user simply sees the same node +//! again one level down. +//! +//! See `docs/features/hierarchy/README.md`. + +use std::path::Path; + +use lsp_types::{ + CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, Range, SymbolKind, Uri, +}; +use vlog_parser::ast::Item; +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::state::Workspace; +use crate::uri::{path_to_uri, uri_to_path}; + +/// The module the cursor names, as the root of a hierarchy — its own +/// declaration, or an instantiation of it. +/// +/// `None` for every other position, which is what stops an editor from opening +/// an empty hierarchy view on a `wire`. A name the workspace index does not +/// hold as a module declines the same way: there is no node to stand on. +/// +/// A name two files declare returns *both* items rather than a guess, the same +/// answer `textDocument/definition` gives for the same ambiguity — the client +/// asks the user which one they meant. +pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option> { + let doc = ws.document(uri)?; + // The cursor on a declaration written in this buffer answers from the + // buffer, unsaved edits and all — no index lookup can beat that. + if let Some(decl) = instantiations::declarations(&doc.tree.items) + .into_iter() + .find(|decl| touches(decl.module.name_span, offset)) + { + let positions = doc.positions(); + return Some(vec![item(uri.clone(), &positions, decl)?]); + } + // The cursor on an instantiation names the module being instantiated. + let sites = instantiations::sites(&doc.tree.items); + let site = sites.iter().find(|site| touches(site.inst.module_span, offset))?; + let items = declarations_of(ws, &site.inst.module); + (!items.is_empty()).then_some(items) +} + +/// Who instantiates this module: one call per **instantiating module**, with +/// every instantiation site inside it. +/// +/// 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(); + for (path, text) in ws.sources() { + calls.extend(callers_in(&path, &text, &item.name)); + } + 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 +} + +/// What this module instantiates: one call per **distinct instantiated +/// module**, with every site inside this module. +/// +/// A module the index cannot name — undeclared, or declared twice — is skipped +/// silently. A hierarchy node has nowhere to say "and one more I could not +/// find", and a node pointing at the wrong one of two same-named modules would +/// send the user to the wrong file with no way to tell. +pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec { + let Some(text) = text_of(ws, &item.uri) else { return Vec::new() }; + let (tree, _) = parse_source_tolerant(&text); + let line_index = LineIndex::new(&text); + let positions = Positions::new(&text, &line_index); + let at = span(&positions, item.selection_range); + let Some(decl) = find_module(&tree.items, &item.name, Some(at)) else { return Vec::new() }; + // Only what is written directly in this module: an instantiation inside a + // nested module is that module's call, not this one's. + let mut targets: Vec<(&str, Vec)> = Vec::new(); + for site in instantiations::sites(&decl.module.items) { + if site.owner.is_some() { + continue; + } + match targets.iter_mut().find(|(name, _)| *name == site.inst.module) { + Some((_, spans)) => spans.push(site.inst.module_span), + None => targets.push((&site.inst.module, vec![site.inst.module_span])), + } + } + targets + .into_iter() + .filter_map(|(name, spans)| { + Some(CallHierarchyOutgoingCall { + to: one_declaration(ws, name)?, + from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(), + }) + }) + .collect() +} + +/// Every module in one file that instantiates `name`, with its sites. +fn callers_in(path: &Path, text: &str, name: &str) -> 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) { + if site.inst.module != name { + continue; + } + // An instantiation at file scope has no calling module to report. + let Some(owner) = site.owner else { continue }; + match callers.iter_mut().find(|(decl, _)| decl.span == owner.span) { + Some((_, spans)) => spans.push(site.inst.module_span), + None => callers.push((owner, vec![site.inst.module_span])), + } + } + 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_ranges: spans.into_iter().map(|span| positions.range(span)).collect(), + }) + }) + .collect() +} + +/// The hierarchy item for one module declaration, positioned against the text +/// it was parsed from. +fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option { + let name_span = decl.module.name_span; + if name_span.is_empty() { + return None; + } + // The protocol requires `selectionRange` inside `range`; a declaration the + // parser could not close is the case where that may not hold, and there + // the name alone is the honest extent. + let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end { + decl.span + } else { + name_span + }; + Some(CallHierarchyItem { + name: decl.module.name.clone(), + kind: SymbolKind::MODULE, + tags: None, + detail: None, + uri, + range: positions.range(full), + selection_range: positions.range(name_span), + data: None, + }) +} + +/// Every module declaration of `name` the index holds, as hierarchy items. +fn declarations_of(ws: &Workspace, name: &str) -> Vec { + ws.index() + .units(name) + .iter() + .filter(|def| def.kind == SemanticKind::Module) + .filter_map(|def| { + let path = ws.index().path(def.file)?; + item_in_file(ws, path, name, Some(def.name_span)) + }) + .collect() +} + +/// The one declaration of `name`, or nothing when the workspace has none or +/// has several. +fn one_declaration(ws: &Workspace, name: &str) -> Option { + let mut found = declarations_of(ws, name); + (found.len() == 1).then(|| found.remove(0)) +} + +/// Re-read a declaring file and build the item for the module in it. +/// +/// The index knows the file and the name's span but keeps no text, so the file +/// is parsed here for the declaration's full extent. `at` is the span the +/// index recorded, used to pick between two same-named declarations in one +/// file; it is a preference and not a requirement, because the buffer may have +/// been edited since the index was built. +fn item_in_file( + ws: &Workspace, + path: &Path, + name: &str, + at: Option, +) -> Option { + let uri = path_to_uri(path)?; + let text = ws.text_of(path)?; + let (tree, _) = parse_source_tolerant(&text); + let decl = find_module(&tree.items, name, at)?; + let line_index = LineIndex::new(&text); + item(uri, &Positions::new(&text, &line_index), decl) +} + +/// The declaration of `name` in a parsed file: the one whose name sits at +/// `at`, else the first of that name. +fn find_module<'a>(items: &'a [Item], name: &str, at: Option) -> Option> { + let decls: Vec = + instantiations::declarations(items).into_iter().filter(|d| d.module.name == name).collect(); + if let Some(at) = at { + if let Some(exact) = decls.iter().find(|d| d.module.name_span == at) { + return Some(*exact); + } + } + decls.first().copied() +} + +/// The text behind a hierarchy item's URI — the open buffer if there is one, +/// else the file on disk. +fn text_of(ws: &Workspace, uri: &Uri) -> Option { + match ws.document(uri) { + Some(doc) => Some(doc.text.clone()), + None => ws.text_of(&uri_to_path(uri)?), + } +} + +/// Whether `offset` is inside `span`, its end included — a cursor placed +/// immediately after the last character of a name is on that name, which is +/// where a double-click leaves it. +fn touches(span: TextRange, offset: u32) -> bool { + !span.is_empty() && span.start <= offset && offset <= span.end +} + +/// A `Range` back as a byte span, for matching an item against a fresh parse. +fn span(positions: &Positions, range: Range) -> TextRange { + TextRange::new(positions.offset(range.start), positions.offset(range.end)) +} + +/// A range as a sort key. +fn key(range: Range) -> (u32, u32) { + (range.start.line, range.start.character) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + 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!("vfmt_server_hierarchy_{}_{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); + 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) + } + + /// The byte offset of the first occurrence of `needle`. + fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 + } + + /// An item as `(name, file name, selection line)`. + fn shape(item: &CallHierarchyItem) -> (String, String, u32) { + ( + item.name.clone(), + item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), + item.selection_range.start.line, + ) + } + + /// The lines every `fromRanges` entry starts on. + fn lines(ranges: &[Range]) -> Vec { + ranges.iter().map(|r| r.start.line).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 three-file workspace of the cross-file tests, `top.sv` open. + fn three(name: &str) -> (Tree, Workspace, Uri) { + workspace(name, &[("top.sv", TOP), ("sub.sv", SUB), ("other.sv", OTHER)]) + } + + // ------------------------------------------------------------------ + // prepare + // ------------------------------------------------------------------ + + #[test] + fn the_cursor_on_a_declaration_prepares_that_module() { + let (_tree, ws, uri) = workspace("decl", &[("sub.sv", SUB)]); + let items = prepare(&ws, &uri, at(SUB, "sub")).expect("a module"); + assert_eq!(items.len(), 1); + assert_eq!(shape(&items[0]), ("sub".to_string(), "sub.sv".to_string(), 0)); + assert_eq!(items[0].kind, SymbolKind::MODULE); + assert_eq!(items[0].selection_range.start.character, 7, "the name, not the keyword"); + assert_eq!(items[0].range.start.character, 0, "the whole declaration"); + assert_eq!(items[0].range.end.line, 1, "through `endmodule`"); + } + + #[test] + fn the_cursor_on_an_instantiation_prepares_the_module_it_names() { + let (_tree, ws, uri) = three("inst"); + let items = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("a module"); + assert_eq!(items.len(), 1); + assert_eq!( + shape(&items[0]), + ("sub".to_string(), "sub.sv".to_string(), 0), + "the declaration in the other file, not the instantiation" + ); + } + + #[test] + fn a_position_on_no_module_prepares_nothing() { + let (_tree, ws, uri) = three("none"); + assert!(prepare(&ws, &uri, 0).is_none(), "the `module` keyword"); + assert!(prepare(&ws, &uri, at(TOP, "u_a")).is_none(), "the instance name"); + assert!(prepare(&ws, &uri, at(TOP, "1'b0")).is_none(), "a connected expression"); + let (_tree, ws, uri) = workspace("nonmodule", &[("p.sv", "package p;\nendpackage\n")]); + assert!(prepare(&ws, &uri, at("package p;", "p;")).is_none(), "a package is not a module"); + } + + #[test] + fn a_cursor_just_past_the_last_character_of_a_name_still_prepares() { + // Where a double-click and an end-of-word motion leave it. + let (_tree, ws, uri) = workspace("edge", &[("sub.sv", SUB)]); + assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some()); + } + + #[test] + fn an_instantiation_of_a_module_nothing_declares_prepares_nothing() { + let top = "module top;\n nope u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]); + assert!(prepare(&ws, &uri, at(top, "nope")).is_none()); + } + + #[test] + fn a_module_two_files_declare_prepares_both_rather_than_guessing() { + let top = "module top;\n dup u1 ();\nendmodule\n"; + let dup = "module dup;\nendmodule\n"; + let (_tree, ws, uri) = workspace("dup", &[("top.sv", top), ("a.sv", dup), ("b.sv", dup)]); + let items = prepare(&ws, &uri, at(top, "dup")).expect("both"); + let names: Vec = items.iter().map(|i| shape(i).1).collect(); + assert_eq!(names, ["a.sv", "b.sv"], "every declaration, as definition does"); + } + + // ------------------------------------------------------------------ + // incoming + // ------------------------------------------------------------------ + + #[test] + fn incoming_calls_name_every_instantiating_module_once() { + let (_tree, ws, uri) = three("incoming"); + let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!( + calls.iter().map(|c| shape(&c.from)).collect::>(), + [ + ("other".to_string(), "other.sv".to_string(), 0), + ("top".to_string(), "top.sv".to_string(), 0), + ], + "one call per instantiating module, sorted by file" + ); + assert_eq!(lines(&calls[0].from_ranges), [1], "other.sv instantiates once"); + assert_eq!(lines(&calls[1].from_ranges), [1, 2], "top.sv twice, in one call"); + assert_eq!( + calls[1].from_ranges[0].start.character, 2, + "the range is the module name of the instantiation" + ); + assert_eq!(calls[1].from_ranges[0].end.character, 5); + } + + #[test] + fn a_module_nobody_instantiates_has_no_incoming_calls() { + let (_tree, ws, uri) = three("leaf"); + let root = prepare(&ws, &uri, at(TOP, "module top") + 7).expect("top")[0].clone(); + assert!(incoming(&ws, &root).is_empty(), "nothing instantiates the top"); + } + + #[test] + fn incoming_calls_reach_generate_regions_bind_and_instance_arrays() { + let top = "\ +module top; + generate + for (genvar i = 0; i < 4; i++) begin : g + sub u1 (.clk(1'b0)); + end + endgenerate + sub u2 [3:0] (.clk(1'b0)); + bind top sub u3 (.clk(1'b0)); +endmodule +"; + let (_tree, ws, uri) = workspace("shapes", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "sub u1")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1, "one caller: {calls:#?}"); + assert_eq!(lines(&calls[0].from_ranges), [3, 6, 7], "generate, array and bind"); + } + + #[test] + fn an_ordered_connection_list_is_found_like_any_other() { + // The walk matches the module *name*; how the ports are connected has + // nothing to do with it. + let top = "module top;\n sub u1 (clk);\nendmodule\n"; + let (_tree, ws, uri) = workspace("ordered", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "sub u1")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!(lines(&calls[0].from_ranges), [1]); + } + + #[test] + fn a_self_instantiating_module_is_its_own_caller_and_does_not_hang() { + let top = "module top;\n top u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("selfcall", &[("top.sv", top)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!(shape(&calls[0].from), ("top".to_string(), "top.sv".to_string(), 0)); + assert_eq!(lines(&calls[0].from_ranges), [1]); + // And the other direction of the same edge, one hop only. + let out = outgoing(&ws, &root); + assert_eq!(out.len(), 1); + assert_eq!(shape(&out[0].to), ("top".to_string(), "top.sv".to_string(), 0)); + } + + #[test] + fn a_module_instantiated_only_outside_the_index_scope_has_no_callers() { + // The scope ladder decides which files exist; a file the configured + // filelist omits is not searched, exactly as references are not. + let tree = Tree::new("scope"); + tree.write("sub.sv", SUB); + tree.write("top.sv", TOP); + tree.write("files.f", "sub.sv\n"); + tree.write("vfmt.toml", "filelist = \"files.f\"\n"); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let root = prepare(&ws, &sub_uri, at(SUB, "sub")).expect("sub")[0].clone(); + assert!(incoming(&ws, &root).is_empty(), "top.sv is out of scope"); + } + + #[test] + fn an_unsaved_instantiation_is_a_caller_before_it_is_saved() { + // The sources a walk reads are the open buffers overlaid on disk, so a + // just-typed instantiation counts. + let (tree, mut ws, uri) = three("unsaved"); + let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + assert_eq!(incoming(&ws, &root).len(), 2, "premise"); + + let fresh = tree.path.join("other.sv"); + let other_uri = path_to_uri(&fresh).expect("uri"); + ws.set_document(other_uri, "module other;\nendmodule\n".to_string()); + assert_eq!(incoming(&ws, &root).len(), 1, "the buffer removed its instantiation"); + } + + // ------------------------------------------------------------------ + // outgoing + // ------------------------------------------------------------------ + + #[test] + fn outgoing_calls_name_every_distinct_instantiated_module_once() { + let top = "\ +module top; + sub u_a (.clk(1'b0)); + other_sub u_b (); + sub u_c (.clk(1'b1)); + nope u_d (); +endmodule +"; + let other_sub = "module other_sub;\nendmodule\n"; + let (_tree, ws, uri) = + workspace("outgoing", &[("top.sv", top), ("sub.sv", SUB), ("other_sub.sv", other_sub)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + assert_eq!( + calls.iter().map(|c| shape(&c.to)).collect::>(), + [ + ("sub".to_string(), "sub.sv".to_string(), 0), + ("other_sub".to_string(), "other_sub.sv".to_string(), 0), + ], + "distinct modules in source order; `nope` is declared nowhere and is skipped" + ); + assert_eq!(lines(&calls[0].from_ranges), [1, 3], "both `sub` sites, in one call"); + assert_eq!(lines(&calls[1].from_ranges), [2]); + } + + #[test] + fn an_ambiguous_target_is_skipped_rather_than_guessed() { + let top = "module top;\n dup u1 ();\nendmodule\n"; + let dup = "module dup;\nendmodule\n"; + let (_tree, ws, uri) = + workspace("outambig", &[("top.sv", top), ("a.sv", dup), ("b.sv", dup)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + assert!(outgoing(&ws, &root).is_empty(), "two `dup`s, so neither is claimed"); + } + + #[test] + fn outgoing_calls_reach_generate_regions_and_bind() { + let top = "\ +module top; + generate + if (1) begin : g + sub u1 (.clk(1'b0)); + end else begin + sub u2 (.clk(1'b1)); + end + endgenerate + bind top sub u3 (.clk(1'b0)); +endmodule +"; + let (_tree, ws, uri) = workspace("outshapes", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!(lines(&calls[0].from_ranges), [3, 5, 8], "both arms and the bind"); + } + + #[test] + fn a_leaf_module_instantiates_nothing() { + let (_tree, ws, uri) = three("outleaf"); + let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + assert!(outgoing(&ws, &root).is_empty()); + } + + #[test] + fn one_modules_calls_are_never_its_neighbours_in_the_same_file() { + // Two modules in one file. Each answers with its own instantiations, + // which means the item is matched by the name span `prepare` handed + // back and not by "the first module in the file". + let top = "\ +module top; + sub u1 (.clk(1'b0)); +endmodule + +module neighbour; + other_sub u2 (); +endmodule +"; + let other_sub = "module other_sub;\nendmodule\n"; + let (_tree, ws, uri) = workspace( + "neighbour", + &[("top.sv", top), ("sub.sv", SUB), ("other_sub.sv", other_sub)], + ); + let names = |item: &CallHierarchyItem| -> Vec { + outgoing(&ws, item).iter().map(|c| c.to.name.clone()).collect() + }; + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + assert_eq!(names(&root), ["sub"]); + let other = + prepare(&ws, &uri, at(top, "module neighbour") + 7).expect("neighbour")[0].clone(); + assert_eq!(names(&other), ["other_sub"]); + } + + #[test] + fn an_item_naming_a_file_that_is_gone_answers_with_no_calls() { + let (tree, ws, uri) = three("missing"); + let root = prepare(&ws, &uri, at(TOP, "module top") + 7).expect("top")[0].clone(); + assert_eq!(outgoing(&ws, &root).len(), 1, "premise"); + let mut stale = root.clone(); + stale.uri = path_to_uri(&tree.path.join("gone.sv")).expect("uri"); + assert!(outgoing(&ws, &stale).is_empty(), "no file, no calls, no panic"); + let mut renamed = root; + renamed.name = "no_such_module".to_string(); + assert!(outgoing(&ws, &renamed).is_empty(), "a name the file does not declare"); + } + + #[test] + fn positions_are_utf16_units_on_a_line_carrying_multibyte_text() { + let top = "module top; // é 🎉\n sub /* é */ u1 (.clk(1'b0));\nendmodule\n"; + let (_tree, ws, uri) = workspace("utf16", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "sub /*")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!( + (calls[0].from_ranges[0].start.character, calls[0].from_ranges[0].end.character), + (2, 5), + "the `sub` of the instantiation, in UTF-16 units" + ); + } + + #[test] + fn a_nameless_item_reads_no_files_at_all() { + // A malformed item from a client: the prefilter matches every file for + // an empty name, so without the guard this would read and parse the + // whole workspace to find nothing. + let (_tree, ws, uri) = three("nameless"); + let mut nameless = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + nameless.name = String::new(); + assert!(incoming(&ws, &nameless).is_empty()); + assert!(outgoing(&ws, &nameless).is_empty()); + } + + #[test] + fn an_unopened_document_prepares_nothing() { + let ws = Workspace::default(); + let uri = path_to_uri(std::path::Path::new("/nowhere/top.sv")).expect("uri"); + assert!(prepare(&ws, &uri, 0).is_none()); + } + + #[test] + fn an_untitled_buffer_prepares_from_itself() { + // No path, so no index entry — but the declaration is right there in + // the buffer, and its own hierarchy root is a fair answer. + use std::str::FromStr; + let text = "module scratch;\nendmodule\n"; + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let items = prepare(&ws, &uri, at(text, "scratch")).expect("the buffer's own module"); + assert_eq!(items[0].name, "scratch"); + assert_eq!(items[0].uri, uri); + assert!(outgoing(&ws, &items[0]).is_empty(), "and it instantiates nothing"); + } + + #[test] + fn a_buffer_that_does_not_parse_invents_no_calls() { + // Whatever the tolerant parse recovered from an unclosed connection + // list, nothing may panic and no edge may be invented — the assertion + // is deliberately on survival, so a change in recovery is not a + // failure here. + let broken = "module top;\n sub u1 (\n"; + let (_tree, ws, uri) = workspace("broken", &[("top.sv", broken), ("sub.sv", SUB)]); + if let Some(items) = prepare(&ws, &uri, at(broken, "module top") + 7) { + for call in outgoing(&ws, &items[0]) { + assert_eq!(call.to.name, "sub", "only a module really written there"); + } + } + } + + // ------------------------------------------------------------------ + // QA (2026-08-25) — break-it fixtures not in the dev's own suite; see + // docs/features/hierarchy/README.md's QA log for the full findings + // ------------------------------------------------------------------ + + #[test] + fn qa_bind_owner_is_the_module_containing_the_directive_not_the_bind_target() { + // `bind top chk u_chk ();` written inside `module harness` in a THIRD + // file. If the owner were the bind's target (`top`) rather than the + // module the directive is textually inside, this would misattribute. + let top = "module top;\nendmodule\n"; + let chk = "module chk;\nendmodule\n"; + let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n"; + let (_tree, ws, uri) = workspace( + "qa_bind_elsewhere2", + &[("chk.sv", chk), ("top.sv", top), ("harness.sv", harness)], + ); + let root = prepare(&ws, &uri, at(chk, "chk")).expect("chk module")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1, "one caller of chk: {calls:#?}"); + assert_eq!( + shape(&calls[0].from), + ("harness".to_string(), "harness.sv".to_string(), 0), + "owner is the module containing the `bind` directive, not `top`" + ); + } + + #[test] + fn qa_prefilter_over_admits_but_walk_rejects_a_comment_only_mention() { + // `widget` appears ONLY in a comment in b.sv. The substring prefilter + // will admit b.sv for parsing, but the walk must not report it as a + // caller since no real instantiation exists there. + let a = "module widget;\nendmodule\n"; + let b = "module b;\n // this file mentions widget only in a comment\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_prefilter", &[("a.sv", a), ("b.sv", b)]); + let root = prepare(&ws, &uri, at(a, "widget")).expect("widget")[0].clone(); + let calls = incoming(&ws, &root); + assert!(calls.is_empty(), "comment-only mention must not be a caller: {calls:#?}"); + } + + #[test] + fn qa_instantiation_in_a_package_does_not_crash() { + // Illegal-ish SystemVerilog (a package body instantiating a module), + // reachable through the tolerant parser. Must not panic. + let text = "package p;\n sub u1 ();\nendpackage\nmodule sub;\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_pkg_inst", &[("p.sv", text)]); + let root = prepare(&ws, &uri, at(text, "module sub") + 7).expect("sub")[0].clone(); + let _ = incoming(&ws, &root); + // No assertion on the exact answer — the assertion is on survival. + } + + #[test] + fn qa_ifdef_instantiation_both_arms_are_reported_undisclosed_in_the_readme() { + // The parser does not evaluate `ifdef`/`else`: both arms become + // ordinary `Instantiation` items in source order (confirmed against + // `vlog_parser::parser::parse_item_kind`). So `outgoing(top)` reports + // BOTH `sub_a` and `sub_b`, even though only one is ever really built. + // Unlike `inlay.rs` (which treats an `ifdef`-carrying list as an + // uncertainty and stays silent, see docs/features/inlay-hints — + // "ifdef" QA finding), this feature's README documents no `ifdef` + // policy at all. The answer is arguably the honest one — vfmt cannot + // know which arm is live, and showing both is not a *wrong* single + // claim the way a mis-ordered port hint would be — but it should be + // stated as an Assumption rather than left silent. See QA log. + let text = "\ +module top; +`ifdef CFG_A + sub_a u1 (); +`else + sub_b u1 (); +`endif +endmodule +"; + let sub_a = "module sub_a;\nendmodule\n"; + let sub_b = "module sub_b;\nendmodule\n"; + let (_tree, ws, uri) = + workspace("qa_ifdef", &[("top.sv", text), ("sub_a.sv", sub_a), ("sub_b.sv", sub_b)]); + let root = prepare(&ws, &uri, at(text, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + let names: Vec = calls.iter().map(|c| c.to.name.clone()).collect(); + assert_eq!(names, ["sub_a", "sub_b"], "both `ifdef` arms end up as real calls: {calls:#?}"); + } + + #[test] + fn qa_outgoing_ambiguous_does_not_leak_fromranges_into_resolved_entries() { + let top = "\ +module top; + sub u1 (); + dup u2 (); + sub u3 (); +endmodule +"; + let sub = "module sub;\nendmodule\n"; + let dup = "module dup;\nendmodule\n"; + let (_tree, ws, uri) = workspace( + "qa_no_leak", + &[("top.sv", top), ("sub.sv", sub), ("a.sv", dup), ("b.sv", dup)], + ); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + eprintln!("QA no-leak outgoing calls: {calls:#?}"); + assert_eq!(calls.len(), 1, "only `sub` resolves; `dup` is skipped: {calls:#?}"); + assert_eq!(calls[0].to.name, "sub"); + assert_eq!(lines(&calls[0].from_ranges), [1, 3], "both `sub` sites, dup's line 2 absent"); + } + + #[test] + fn qa_outgoing_nested_module_declaration_boundary() { + // The dev's pinned fixture shape from instantiations.rs, driven + // through the public API: a nested `module` the parser recovers as a + // sibling. `outer`'s outgoing calls must not include `sub`, which + // belongs to `inner`. + let text = "\ +module outer; + module inner; + sub u1 (); + endmodule +endmodule +"; + let sub = "module sub;\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_nested", &[("text.sv", text), ("sub.sv", sub)]); + let outer = prepare(&ws, &uri, at(text, "module outer") + 7).expect("outer")[0].clone(); + let inner = prepare(&ws, &uri, at(text, "module inner") + 7).expect("inner")[0].clone(); + let outer_calls = outgoing(&ws, &outer); + let inner_calls = outgoing(&ws, &inner); + assert!(outer_calls.is_empty(), "`sub` belongs to `inner`, not `outer`: {outer_calls:#?}"); + assert_eq!(inner_calls.len(), 1, "inner claims `sub`: {inner_calls:#?}"); + assert_eq!(inner_calls[0].to.name, "sub"); + } + + #[test] + fn qa_prepare_on_a_string_or_comment_is_null() { + let text = "module top;\n // sub lives here\n string s = \"sub\";\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_string_comment", &[("top.sv", text)]); + let comment_offset = at(text, "// sub"); + let string_offset = at(text, "\"sub\"") + 1; + assert!(prepare(&ws, &uri, comment_offset + 3).is_none(), "cursor inside a comment"); + assert!(prepare(&ws, &uri, string_offset + 1).is_none(), "cursor inside a string literal"); + } + + #[test] + fn qa_prepare_on_a_bind_target_module_name_is_currently_null() { + // `bind top chk u_chk ();` — cursor on `top`, the bind's *target* + // module. `top` is a real, declared module and a genuine reference to + // it, but neither `declarations()` (which only sees `module ...` + // headers) nor `sites()` (whose span for a bind is `chk`'s, the + // instantiated module) covers this text, so `prepare` answers `null`. + // That fails safe rather than corrupting anything, but it is a + // completeness gap: undocumented and untested by the dev, and a user + // right-clicking the bind target gets no hierarchy where one plainly + // exists. See QA log. + let top = "module top;\n bind top chk u_chk ();\nendmodule\n"; + let chk = "module chk;\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]); + let target_offset = at(top, "bind top") + 5; + assert!( + prepare(&ws, &uri, target_offset).is_none(), + "pinning today's answer, not endorsing it" + ); + } + + #[test] + fn qa_cycle_a_to_b_to_a_two_hops_no_hang() { + let a = "module a;\n b u1 ();\nendmodule\n"; + let b = "module b;\n a u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_cycle", &[("a.sv", a), ("b.sv", b)]); + let root_a = prepare(&ws, &uri, at(a, "module a") + 7).expect("a")[0].clone(); + let out_a = outgoing(&ws, &root_a); + assert_eq!(out_a.len(), 1, "a -> b: {out_a:#?}"); + assert_eq!(out_a[0].to.name, "b"); + let hop2 = out_a[0].to.clone(); + let out_b = outgoing(&ws, &hop2); + assert_eq!(out_b.len(), 1, "b -> a: {out_b:#?}"); + assert_eq!(out_b[0].to.name, "a"); + // And incoming mirrors it. + let in_b = incoming(&ws, &hop2); + assert_eq!(in_b.len(), 1, "b's only caller is a: {in_b:#?}"); + assert_eq!(in_b[0].from.name, "a"); + } + + #[test] + fn qa_consistency_incoming_x_matches_outgoing_parent_of_x() { + let (_tree, ws, uri) = three("qa_consistency"); + let sub_root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + let incoming_calls = incoming(&ws, &sub_root); + for call in &incoming_calls { + let parent_calls = outgoing(&ws, &call.from); + let matching = parent_calls.iter().find(|c| c.to.name == "sub"); + let matching = matching.unwrap_or_else(|| { + panic!( + "outgoing({}) has no `sub` entry, but incoming(sub) has one from it", + call.from.name + ) + }); + let mut incoming_ranges: Vec<(u32, u32)> = + call.from_ranges.iter().map(|r| (r.start.line, r.start.character)).collect(); + let mut outgoing_ranges: Vec<(u32, u32)> = + matching.from_ranges.iter().map(|r| (r.start.line, r.start.character)).collect(); + incoming_ranges.sort(); + outgoing_ranges.sort(); + assert_eq!( + incoming_ranges, outgoing_ranges, + "incoming(sub) from {} disagrees with outgoing({}) on fromRanges", + call.from.name, call.from.name + ); + } + assert_eq!(incoming_calls.len(), 2, "premise: two callers (top, other)"); + } + + #[test] + #[ignore] + fn qa_perf_worst_case_common_word_module_name() { + // A single-letter module name is a substring of nearly every file's + // text, so the prefilter admits nearly everything — the worst case + // the prefilter can face. Measures whether that worst case is still + // sane, not a specific number. + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let mut ws = Workspace::default(); + ws.open_roots(vec![corpus]); + let item = CallHierarchyItem { + name: "d".to_string(), + kind: SymbolKind::MODULE, + tags: None, + detail: None, + uri: path_to_uri(&std::path::PathBuf::from("/dev/null")).expect("uri"), + range: Range::default(), + selection_range: Range::default(), + data: None, + }; + let started = std::time::Instant::now(); + let calls = incoming(&ws, &item); + let elapsed = started.elapsed(); + eprintln!( + "QA worst-case prefilter ('d' as module name): {} files, {} calls, {:?}", + ws.index().files().len(), + calls.len(), + elapsed + ); + } + + // ------------------------------------------------------------------ + // the performance claim, measured + // ------------------------------------------------------------------ + + /// What "who instantiates this?" costs over the real corpus, for a module + /// instantiated all over it. 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 exists to catch an order-of- + /// magnitude regression, not to pin a number. The numbers themselves are + /// in `docs/features/hierarchy/README.md`. + #[test] + fn incoming_calls_over_the_whole_corpus_stay_in_budget() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let declaring = + corpus.join("ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_flop_2sync.sv"); + let Ok(text) = fs::read_to_string(&declaring) else { + eprintln!("prim_flop_2sync.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_roots(vec![corpus]); + let uri = path_to_uri(&declaring).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7) + .expect("the declaration")[0] + .clone(); + + // Warm, then the worst of three. + let _ = incoming(&ws, &root); + let mut worst = std::time::Duration::ZERO; + let mut callers = 0; + for _ in 0..3 { + let started = std::time::Instant::now(); + let calls = incoming(&ws, &root); + worst = worst.max(started.elapsed()); + callers = calls.len(); + } + eprintln!( + "corpus: {} files, incomingCalls for prim_flop_2sync: {callers} callers, worst {worst:?}", + ws.index().files().len(), + ); + assert!(callers > 5, "the corpus really does instantiate it: {callers}"); + assert!(worst < std::time::Duration::from_millis(1500), "incomingCalls cost {worst:?}"); + } +} diff --git a/crates/vfmt_server/src/inlay.rs b/crates/vfmt_server/src/inlay.rs index bbeddfb..96838e5 100644 --- a/crates/vfmt_server/src/inlay.rs +++ b/crates/vfmt_server/src/inlay.rs @@ -22,13 +22,12 @@ use std::collections::HashMap; use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri}; -use vlog_parser::ast::{ - Connections, Expr, GenBlock, GenElse, Instance, Instantiation, Item, ItemKind, SourceFile, -}; +use vlog_parser::ast::{Connections, Expr, Instance, Instantiation}; use vlog_parser::TextRange; use vlog_refactor::InstantiationPlan; use crate::convert::Positions; +use crate::instantiations; use crate::state::Workspace; /// The ghost labels for one range of a buffer. @@ -47,7 +46,8 @@ pub fn inlay_hints(ws: &Workspace, uri: &Uri, range: Range) -> Vec { plans: Plans::new(ws), out: Vec::new(), }; - for inst in instantiations(&doc.tree) { + for site in instantiations::sites(&doc.tree.items) { + let inst = site.inst; hints.paint(¶m_sites(inst), Kind::Params, &inst.module); for instance in &inst.instances { hints.paint(&port_sites(instance), Kind::Ports, &inst.module); @@ -208,62 +208,6 @@ impl<'w> Plans<'w> { } } -// ---------------------------------------------------------------------- -// finding the instantiations -// ---------------------------------------------------------------------- - -/// Every module instantiation in a file, nested ones included. -/// -/// Gate primitives are not here: `and (q, a, b)` is an -/// [`ItemKind::GateInstantiation`], its arguments are not connections to named -/// ports, and the language gives them no names to show. -fn instantiations(file: &SourceFile) -> Vec<&Instantiation> { - let mut out = Vec::new(); - walk(&file.items, &mut out); - out -} - -fn walk<'a>(items: &'a [Item], out: &mut Vec<&'a Instantiation>) { - for item in items { - match &item.kind { - ItemKind::Instantiation(inst) => out.push(inst), - // The instantiation a `bind` carries is an ordinary one, connection - // list and all. - ItemKind::Bind(bind) => out.push(&bind.inst), - ItemKind::Module(module) => walk(&module.items, out), - ItemKind::Package { items, .. } => walk(items, out), - ItemKind::GenerateRegion { items, .. } => walk(items, out), - ItemKind::GenIf(gen_if) => { - block(&gen_if.then, out); - let mut els = gen_if.els.as_deref(); - while let Some(branch) = els { - match branch { - GenElse::If(_, nested) => { - block(&nested.then, out); - els = nested.els.as_deref(); - } - GenElse::Block(inner) => { - block(inner, out); - els = None; - } - } - } - } - ItemKind::GenFor(gen_for) => block(&gen_for.body, out), - ItemKind::GenCase(gen_case) => { - for arm in &gen_case.items { - block(&arm.body, out); - } - } - _ => {} - } - } -} - -fn block<'a>(gen_block: &'a GenBlock, out: &mut Vec<&'a Instantiation>) { - walk(&gen_block.items, out); -} - #[cfg(test)] mod tests { use super::*; @@ -617,8 +561,8 @@ endmodule // spells a positional override as a `Connection` with an empty name. let text = "module top;\n sub #(8, .DEPTH(16)) u1 ();\nendmodule\n"; let (tree, _) = vlog_parser::parse_source_tolerant(text); - let insts = instantiations(&tree); - let params = insts[0].params.as_ref().expect("a `#( ... )`"); + let insts = instantiations::sites(&tree.items); + let params = insts[0].inst.params.as_ref().expect("a `#( ... )`"); assert_eq!(params[0].name, "", "`8` names nothing"); assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does"); } diff --git a/crates/vfmt_server/src/instantiations.rs b/crates/vfmt_server/src/instantiations.rs new file mode 100644 index 0000000..2abd63b --- /dev/null +++ b/crates/vfmt_server/src/instantiations.rs @@ -0,0 +1,242 @@ +//! Finding module instantiations in a parse tree — one walk, two readers. +//! +//! `inlay.rs` wants every instantiation in a file so it can decorate the +//! ordered connection lists. `hierarchy.rs` wants the same instantiations plus +//! the module each one is written *inside*, because an instantiation is the +//! call and the enclosing module is the caller. Rather than two walks that +//! would drift apart at the next parser node, there is one walk here that +//! carries the enclosing declaration along, and a reader that does not care +//! about the owner ignores it. +//! +//! Gate primitives are not instantiations here: `and (q, a, b)` is an +//! [`ItemKind::GateInstantiation`], names no module, and is nobody's edge in +//! the hierarchy. + +use vlog_parser::ast::{GenBlock, GenElse, Instantiation, Item, ItemKind, Module}; +use vlog_parser::TextRange; + +/// One module declaration: the node, and the extent of the whole +/// `module ... endmodule` it was written as. +#[derive(Clone, Copy)] +pub struct Decl<'a> { + pub module: &'a Module, + /// Code extent of the declaration, attributes included — what a call + /// hierarchy item's `range` is. + pub span: TextRange, +} + +/// One module instantiation, and the module whose body it sits in. +pub struct Site<'a> { + pub inst: &'a Instantiation, + /// The innermost module the instantiation is written inside. `None` for + /// one written at file scope — illegal SystemVerilog, and reachable + /// through the tolerant parser, so it is a case and not an assertion. + pub owner: Option>, +} + +/// Every module instantiation in `items`, nested ones included. +/// +/// Passing a module's own `items` rather than a file's makes the sites written +/// *directly* in that module the ones whose `owner` is `None`, which is how +/// outgoing calls stop at a nested module's boundary. +pub fn sites(items: &[Item]) -> Vec> { + let mut out = Vec::new(); + walk(items, None, &mut out); + out +} + +/// Every module declaration in `items`, nested ones included. +/// +/// A generate block is not descended into: SystemVerilog has no module +/// declaration there, and a `begin ... end` full of instantiations declares +/// nothing. +pub fn declarations(items: &[Item]) -> Vec> { + let mut out = Vec::new(); + collect(items, &mut out); + out +} + +fn walk<'a>(items: &'a [Item], owner: Option>, out: &mut Vec>) { + for item in items { + match &item.kind { + ItemKind::Instantiation(inst) => out.push(Site { inst, owner }), + // The instantiation a `bind` carries is an ordinary one, connection + // list and all — and an ordinary edge of the hierarchy. + ItemKind::Bind(bind) => out.push(Site { inst: &bind.inst, owner }), + ItemKind::Module(module) => { + walk(&module.items, Some(Decl { module, span: item.span }), out) + } + ItemKind::Package { items, .. } => walk(items, owner, out), + ItemKind::GenerateRegion { items, .. } => walk(items, owner, out), + ItemKind::GenIf(gen_if) => { + block(&gen_if.then, owner, out); + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + GenElse::If(_, nested) => { + block(&nested.then, owner, out); + els = nested.els.as_deref(); + } + GenElse::Block(inner) => { + block(inner, owner, out); + els = None; + } + } + } + } + ItemKind::GenFor(gen_for) => block(&gen_for.body, owner, out), + ItemKind::GenCase(gen_case) => { + for arm in &gen_case.items { + block(&arm.body, owner, out); + } + } + _ => {} + } + } +} + +fn block<'a>(gen_block: &'a GenBlock, owner: Option>, out: &mut Vec>) { + walk(&gen_block.items, owner, out); +} + +fn collect<'a>(items: &'a [Item], out: &mut Vec>) { + for item in items { + match &item.kind { + ItemKind::Module(module) => { + out.push(Decl { module, span: item.span }); + collect(&module.items, out); + } + ItemKind::Package { items, .. } => collect(items, out), + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::parse_source_tolerant; + + /// The instantiated module names of a file, in walk order. + fn instantiated(text: &str) -> Vec { + let (tree, _) = parse_source_tolerant(text); + sites(&tree.items).iter().map(|site| site.inst.module.clone()).collect() + } + + /// Every `(instantiated module, owning module)` pair of a file. + fn owned(text: &str) -> Vec<(String, String)> { + let (tree, _) = parse_source_tolerant(text); + sites(&tree.items) + .iter() + .map(|site| { + let owner = site.owner.map_or("-".to_string(), |d| d.module.name.clone()); + (site.inst.module.clone(), owner) + }) + .collect() + } + + #[test] + fn every_instantiation_of_a_module_names_that_module_as_its_owner() { + let text = "module top;\n sub u1 ();\n other u2 ();\nendmodule\n"; + assert_eq!( + owned(text), + [("sub".to_string(), "top".to_string()), ("other".to_string(), "top".to_string())] + ); + } + + #[test] + fn a_generate_region_and_a_bind_keep_the_module_they_are_written_in() { + let text = "\ +module top; + generate + for (genvar i = 0; i < 4; i++) begin : g + sub u1 (); + end + if (P) begin + alt u2 (); + end else begin + els u3 (); + end + endgenerate + bind top chk u_chk (); +endmodule +"; + assert_eq!( + owned(text), + [ + ("sub".to_string(), "top".to_string()), + ("alt".to_string(), "top".to_string()), + ("els".to_string(), "top".to_string()), + ("chk".to_string(), "top".to_string()), + ] + ); + } + + #[test] + fn each_module_of_a_file_owns_only_its_own_instantiations() { + // Which is what stops one module's outgoing calls from claiming the + // next module's. + let text = "\ +module first; + sub u1 (); +endmodule + +module second; + deep u2 (); +endmodule +"; + assert_eq!( + owned(text), + [("sub".to_string(), "first".to_string()), ("deep".to_string(), "second".to_string())] + ); + // Walking one module's own items makes *its* sites the un-owned ones, + // which is how a caller asks "what is written directly in here". + let (tree, _) = parse_source_tolerant(text); + let first = declarations(&tree.items)[0]; + let direct: Vec<&str> = sites(&first.module.items) + .iter() + .filter(|site| site.owner.is_none()) + .map(|site| site.inst.module.as_str()) + .collect(); + assert_eq!(direct, ["sub"], "`deep` belongs to `second`"); + } + + #[test] + fn an_instantiation_at_file_scope_has_no_owner() { + let text = "sub u1 ();\n"; + assert_eq!(owned(text), [("sub".to_string(), "-".to_string())]); + } + + #[test] + fn a_gate_primitive_is_not_an_instantiation() { + assert!(instantiated("module top;\n and u1 (q, a, b);\nendmodule\n").is_empty()); + } + + #[test] + fn a_declarations_extent_runs_from_the_keyword_through_endmodule() { + // What a hierarchy item's `range` is, and it must contain the name. + let text = "module first;\nendmodule\n\nmodule second;\nendmodule\n"; + let (tree, _) = parse_source_tolerant(text); + let decls = declarations(&tree.items); + let names: Vec<&str> = decls.iter().map(|d| d.module.name.as_str()).collect(); + assert_eq!(names, ["first", "second"]); + assert_eq!(&text[decls[0].span.as_range()], "module first;\nendmodule"); + for decl in &decls { + assert!(decl.span.start <= decl.module.name_span.start); + assert!(decl.module.name_span.end <= decl.span.end); + } + } + + #[test] + fn a_module_declaration_written_inside_another_is_reached_however_it_parses() { + // Nested module declarations are legal SystemVerilog and the parser + // does not build them as nested items today — it recovers into + // siblings. Either way both names must be found, which is what the + // hierarchy needs; the shape they arrive in is the parser's business. + let text = "module outer;\n module inner;\n endmodule\nendmodule\n"; + let (tree, _) = parse_source_tolerant(text); + let names: Vec<&str> = + declarations(&tree.items).iter().map(|d| d.module.name.as_str()).collect(); + assert_eq!(names, ["outer", "inner"]); + } +} diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index 9b44f35..791a79b 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -13,9 +13,11 @@ mod convert; mod diagnostics; mod folding; mod format; +mod hierarchy; mod hover; mod includes; mod inlay; +mod instantiations; mod lint; mod locate; mod nav; @@ -37,10 +39,10 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ - CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CompletionOptions, - DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, - InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, - SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, + CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability, + CompletionOptions, DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, + InitializeParams, InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind, + RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, }; @@ -157,6 +159,10 @@ fn capabilities() -> ServerCapabilities { resolve_provider: None, }, ))), + // The module hierarchy, both directions: modules are the nodes and an + // instantiation is the call. Every item is complete when it is + // returned, and the client drives the expansion one hop at a time. + call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( SemanticTokensOptions { work_done_progress_options: WorkDoneProgressOptions::default(), @@ -235,6 +241,17 @@ mod tests { assert!(caps.completion_provider.is_some()); assert!(caps.signature_help_provider.is_some()); assert!(caps.inlay_hint_provider.is_some()); + assert!(caps.call_hierarchy_provider.is_some()); + } + + #[test] + fn the_call_hierarchy_is_advertised_as_a_plain_capability() { + // Nothing about it is optional or resolvable: the three requests are + // either all served or none are. + assert_eq!( + capabilities().call_hierarchy_provider, + Some(CallHierarchyServerCapability::Simple(true)) + ); } #[test] diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index aca99be..ddce023 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -15,6 +15,7 @@ use lsp_types::notification::{ ShowMessage, }; use lsp_types::request::{ + CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare, CodeActionRequest, Completion, DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest, PrepareRenameRequest, RangeFormatting, References, @@ -22,6 +23,7 @@ use lsp_types::request::{ UnregisterCapability, WorkspaceSymbolRequest, }; use lsp_types::{ + CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CodeActionKind, CodeActionParams, CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams, @@ -38,8 +40,8 @@ use serde_json::Value; use crate::state::Workspace; use crate::{ - code_action, completion, diagnostics, folding, format, hover, includes, inlay, nav, pairs, - ports, rename, settings, signature, symbols, tokens, watch, + code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, nav, + pairs, ports, rename, settings, signature, symbols, tokens, watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -300,6 +302,29 @@ impl Server { .and_then(|offset| signature::signature_help(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }), + // The module hierarchy. `prepare` answers `null` for a position + // that is not a module name, which is what stops an editor from + // opening an empty hierarchy view; the two directions then answer + // one hop each, and the client drives the expansion. + CallHierarchyPrepare::METHOD => { + decode(request).and_then(|p: CallHierarchyPrepareParams| { + let at = p.text_document_position_params; + let (uri, position) = (at.text_document.uri, at.position); + self.offset(&uri, position) + .and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset)) + .map_or(Ok(Value::Null), to_value) + }) + } + CallHierarchyIncomingCalls::METHOD => { + decode(request).and_then(|p: CallHierarchyIncomingCallsParams| { + to_value(hierarchy::incoming(&self.workspace, &p.item)) + }) + } + CallHierarchyOutgoingCalls::METHOD => { + decode(request).and_then(|p: CallHierarchyOutgoingCallsParams| { + to_value(hierarchy::outgoing(&self.workspace, &p.item)) + }) + } WorkspaceSymbolRequest::METHOD => { decode(request).and_then(|p: WorkspaceSymbolParams| { to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols( diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 02e1a28..8d9ec56 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -2092,3 +2092,192 @@ fn go_to_definition_lands_on_the_indexs_own_spelling_not_the_includes() { let _ = std::fs::remove_dir_all(&dir); } + +const HIER_SUB: &str = "module hier_sub (input logic clk);\nendmodule\n"; +const HIER_MID: &str = "\ +module hier_mid; + hier_sub u_a (.clk(1'b0)); + hier_sub u_b (.clk(1'b1)); +endmodule +"; +const HIER_TOP: &str = "module hier_top;\n hier_mid u_mid ();\nendmodule\n"; + +#[test] +fn the_module_hierarchy_round_trips_over_the_wire_in_both_directions() { + // What only an e2e test can check: that the capability is advertised in + // the shape a client reads, and that an item the *client* sends back — + // rather than one this process still holds — is what the two directions + // are answered from. + let dir = temp_dir("hierarchy"); + let sub = dir.join("hier_sub.sv"); + std::fs::write(&sub, HIER_SUB).expect("write"); + let mid = dir.join("hier_mid.sv"); + std::fs::write(&mid, HIER_MID).expect("write"); + let top = dir.join("hier_top.sv"); + std::fs::write(&top, HIER_TOP).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", top.display()); + let mid_uri = format!("file://{}", mid.display()); + let sub_uri = format!("file://{}", sub.display()); + // The item a client holds after `prepareCallHierarchy` and sends back for + // each direction: `hier_mid`, declared on lines 0..3 of `hier_mid.sv`. + let mid_item = format!( + r#"{{"name":"hier_mid","kind":2,"uri":"{mid_uri}","range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":9}}}},"selectionRange":{{"start":{{"line":0,"character":7}},"end":{{"line":0,"character":15}}}}}}"# + ); + + 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(HIER_TOP).expect("json") + )), + // The cursor on the `hier_mid` of the instantiation on line 1. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/prepareCallHierarchy","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":4}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"callHierarchy/incomingCalls","params":{{"item":{mid_item}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"callHierarchy/outgoingCalls","params":{{"item":{mid_item}}}}}"# + )), + // The instance name is not a module, so there is no hierarchy to open. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/prepareCallHierarchy","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":12}}}}}}"# + )), + 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["callHierarchyProvider"], serde_json::json!(true)); + + let prepared = response(2)["result"].as_array().expect("a list of items"); + assert_eq!(prepared.len(), 1, "{prepared:#?}"); + assert_eq!( + prepared[0], + serde_json::from_str::(&mid_item).expect("json"), + "the item the client will send back is exactly the one built here" + ); + + let incoming = response(3)["result"].as_array().expect("a list of calls"); + assert_eq!(incoming.len(), 1, "one caller: {incoming:#?}"); + assert_eq!(incoming[0]["from"]["name"], "hier_top"); + assert_eq!(incoming[0]["from"]["uri"], uri.as_str()); + assert_eq!(incoming[0]["from"]["kind"], 2, "SymbolKind.Module"); + assert_eq!( + incoming[0]["fromRanges"], + serde_json::json!([{ + "start": { "line": 1, "character": 2 }, "end": { "line": 1, "character": 10 } + }]), + "the instantiation site inside `hier_top`" + ); + + let outgoing = response(4)["result"].as_array().expect("a list of calls"); + assert_eq!(outgoing.len(), 1, "one distinct callee: {outgoing:#?}"); + assert_eq!(outgoing[0]["to"]["name"], "hier_sub"); + assert_eq!(outgoing[0]["to"]["uri"], sub_uri.as_str()); + assert_eq!( + outgoing[0]["fromRanges"], + serde_json::json!([ + { "start": { "line": 1, "character": 2 }, "end": { "line": 1, "character": 10 } }, + { "start": { "line": 2, "character": 2 }, "end": { "line": 2, "character": 10 } }, + ]), + "both sites of the same module, in one call" + ); + + assert_eq!(response(5)["result"], serde_json::Value::Null, "an instance name is no module"); + + let _ = std::fs::remove_dir_all(&dir); +} + +// QA (2026-08-25): an independent stdio round trip covering an `incomingCalls` +// answer that carries *two* `fromRanges` in one call, rather than reusing the +// dev's own e2e fixture (whose `incomingCalls` case is single-range; only its +// `outgoingCalls` case has two). `sub2` is instantiated twice inside `mid2`. +#[test] +fn qa_incoming_calls_with_two_fromranges_round_trips_over_the_wire() { + let dir = temp_dir("qa_hierarchy_incoming_two_ranges"); + let sub = dir.join("sub2.sv"); + std::fs::write(&sub, "module sub2 (input logic clk);\nendmodule\n").expect("write"); + let mid = dir.join("mid2.sv"); + let mid_text = "\ +module mid2; + sub2 u_a (.clk(1'b0)); + sub2 u_b (.clk(1'b1)); +endmodule +"; + std::fs::write(&mid, mid_text).expect("write"); + + let root = format!("file://{}", dir.display()); + let mid_uri = format!("file://{}", mid.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":"{mid_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(mid_text).expect("json") + )), + // Cursor on `sub2` of the first instantiation. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/prepareCallHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":1,"character":4}}}}}}"# + )), + 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 prepared = response(2)["result"].as_array().expect("a list of items"); + assert_eq!(prepared.len(), 1, "{prepared:#?}"); + let sub2_item = prepared[0].clone(); + + // A second round trip, so the incoming request is answered fresh against + // the item the first session handed back — exactly what a real client + // does across two separate requests. + let session2 = [ + 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","id":3,"method":"callHierarchy/incomingCalls","params":{{"item":{}}}}}"#, + serde_json::to_string(&sub2_item).expect("json") + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + let messages2 = talk(&session2); + let response2 = |id: u32| -> &serde_json::Value { + messages2 + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no {id}: {messages2:#?}")) + }; + let incoming = response2(3)["result"].as_array().expect("a list of calls"); + assert_eq!(incoming.len(), 1, "one caller: {incoming:#?}"); + assert_eq!(incoming[0]["from"]["name"], "mid2"); + let from_ranges = incoming[0]["fromRanges"].as_array().expect("fromRanges"); + assert_eq!(from_ranges.len(), 2, "two instantiation sites in one call: {from_ranges:#?}"); + assert_eq!(from_ranges[0]["start"]["line"], 1); + assert_eq!(from_ranges[1]["start"]["line"], 2); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/hierarchy/README.md b/docs/features/hierarchy/README.md new file mode 100644 index 0000000..1be9fd8 --- /dev/null +++ b/docs/features/hierarchy/README.md @@ -0,0 +1,488 @@ +# hierarchy + +M11 of the refactoring plan (`docs/features/refactor/README.md`), TODO.md §8: +**module hierarchy both directions, over LSP `callHierarchy`.** + +## Goal + +"Who instantiates this module?" and "what does this module instantiate?" are +the two questions a hardware engineer asks about a design they did not write, +and until now vfmt could answer neither without a grep. LSP already has the +shape for both: its call hierarchy is a graph of callers and callees, and a +design's module hierarchy is that same graph under different names — the +modules are the nodes and an instantiation is the call. So +`textDocument/prepareCallHierarchy` picks a module out of the text under the +cursor, `callHierarchy/incomingCalls` answers "who instantiates X" and +`callHierarchy/outgoingCalls` answers "what does X instantiate", and every LSP +client draws the tree with its own hierarchy view — no editor code at all. + +Each request answers **one hop**. The client drives the expansion, so +recursion needs no handling here beyond not crashing: a module that +instantiates itself simply appears again one level down, and an `a → b → a` +pair unrolls as far as the user keeps clicking. + +## Assumptions + +- **An instantiation is the call, and the enclosing module is the caller.** + There is no other candidate: a Verilog module has no call sites of its own, + and its instances are exactly the edges of the design tree. +- **The walk is by name.** An instantiation of `fifo` writes `fifo` where the + parser records `Instantiation::module`, whatever its connection list looks + like — named, ordered, `.*`, an instance array, several instances in one + statement, or a `bind`. Nothing here reads the connections at all. +- **A scope-qualified instantiation (`pkg::mod u ()`) is not matched.** The + parser stores that name with its `::` glued, so it does not equal `mod`, and + the workspace index models no package-scoped module lookup either + (`docs/features/workspace-index/README.md`). Matching on the trailing + segment would silently claim `other_pkg::fifo` as an instantiation of + `fifo`. Not seen anywhere in the corpus; if it ever matters, it needs the + index to answer the qualified name, not a string split here. +- **One `Instantiation` is one call site, however many instances it + declares.** `sub u1 (), u2 ();` writes `sub` once, and the `fromRange` is + that one name — which is the range a client highlights, and the range + `textDocument/references` reports for the same text. +- **An instantiation with no enclosing module has no caller to report.** + Illegal SystemVerilog, reachable through the tolerant parser, and there is + no honest `from` item for it, so it is dropped. +- **Ambiguity is answered differently in the two directions, on purpose.** + `prepare` returns *every* declaration of an ambiguous name — LSP's return + type is a list, and the client asks the user which one they meant, exactly + as `textDocument/definition` does. `outgoingCalls` **skips** an ambiguous or + unknown target silently: a hierarchy node has nowhere to ask a question, and + a node pointing at the wrong one of two same-named modules would send the + user to the wrong file with no way to tell. +- **Two declarations of one name in one file resolve to the first.** The + index's span picks between them when it is still accurate; a buffer edited + since the last index rebuild falls back to the first of that name rather + than answering nothing. +- **A cursor immediately after the last character of a name is on that name.** + `TextRange::contains` excludes the end, which is right for a span of text + and wrong for a caret — that is where a double-click and an end-of-word + motion leave it. +- **The scope ladder decides which files are searched.** `incomingCalls` + reads `Workspace::sources()`, so a file a filelist or an `exclude` keeps out + of the index instantiates nothing, exactly as it references nothing + (`docs/features/references-nav/README.md`). +- **Open buffers beat disk.** The same `sources()` overlay every other + cross-file answer uses, so an instantiation just typed and not yet saved is + already a caller. +- **Nested module declarations.** Legal SystemVerilog; today's parser recovers + them into sibling items rather than nesting them. The walk carries the + innermost enclosing declaration either way, so both spellings attribute + correctly and neither needs a special case here. +- **`` `ifdef``/`` `else`` around an instantiation reports both arms.** The + parser does not evaluate the condition — each arm's items land in the same + flat list, `Directive` items and all (`vlog_parser`'s `parse_item_kind`) — + so `module ... `ifdef A sub_a u1(); `else sub_b u1(); `endif` gives + `outgoingCalls` two entries, `sub_a` and `sub_b`, even though only one is + ever really built. This is not the same failure `inlay.rs` guards against: + a hint draws one confident, potentially-wrong label, where a hierarchy edge + is a fact about the *text* ("this instantiation exists, guarded"), and + showing both is the honest answer to a question vfmt cannot resolve without + evaluating defines. Found in QA (2026-08-25); pinned by + `hierarchy::tests::qa_ifdef_instantiation_both_arms_are_reported_undisclosed_in_the_readme`. + +## Handshakes + +- **Consumes `crate::instantiations`** — new in this change, and the *shared* + instantiation walk: `sites` (every instantiation, with the module it is + written inside) and `declarations` (every module declaration, with the + extent of its `module ... endmodule`). It is the walk that used to live + privately in `inlay.rs`, lifted rather than copied, with the enclosing + declaration threaded through it. `inlay.rs` now reads `sites(...)` and + ignores the owner; its behavior is byte-identical and its 34 tests are the + regression net for that claim. +- **Consumes `vlog_parser`** — `parse_source_tolerant` for every file that is + not the open buffer, `ast::Module`/`Instantiation` (read-only), + `Item::span`, `LineIndex`. Nothing new is asked of the crate. +- **Consumes `vlog_semantic::WorkspaceIndex`** — `units(name)` and + `path(file)`, to turn a module name into the file that declares it. The + index records what a file *declares* and **not what it instantiates**: there + is no edge table, which is why `incomingCalls` walks files rather than + querying. Adding such a table is a real option and is recorded as backlog + below rather than assumed here. +- **Consumes `crate::state::Workspace`** — `document`, `index`, `text_of`, + `sources`. Nothing in `state.rs` was changed; the workspace stays immutable + through all three handlers, and no cache was added. +- **Promises `vfmt_server`** — `hierarchy::{prepare, incoming, outgoing}` + never panic, never return an item whose `selectionRange` is outside its + `range`, and never return a `to`/`from` item for a module the workspace does + not really declare. +- **`editors/vscode` needs no change.** `vscode-languageclient` 9.0.1 ships + the call-hierarchy feature and enables it off the advertised capability; the + extension sets no `initializationOptions` that would suppress it, and the + Vim/Neovim client has `vim.lsp.buf.incoming_calls()`/`outgoing_calls()` + built in. `editors/vscode/smoke.js` checks a fixed four-name capability list + and was deliberately left untouched (it is editor-packaging's file) — it + still passes. If the lead wants `callHierarchyProvider` in that list, it is + a one-line addition there. + +## What it looks like + +`hier_mid.sv`: + +```systemverilog +module hier_mid; + hier_sub u_a (.clk(1'b0)); + hier_sub u_b (.clk(1'b1)); +endmodule +``` + +Cursor on `hier_mid` anywhere — its own declaration, or the `hier_mid` of an +instantiation in `hier_top.sv` — and the hierarchy view shows: + +``` +incoming (who instantiates hier_mid) outgoing (what hier_mid instantiates) + hier_top hier_top.sv:2 hier_sub hier_sub.sv:1 + hier_mid.sv:2, hier_mid.sv:3 +``` + +One entry per *calling module*, not per instantiation: two instantiations of +`hier_sub` in one module are one outgoing call carrying two `fromRanges`, and +the client highlights both. + +## Cost + +Release build, this machine, the checked-in 860-file corpus: + +| request | measured | +|---|---| +| `incomingCalls` for `prim_flop_2sync` (25 calling modules across the corpus) | **56 ms** | +| — of which reading the 860 files (`Workspace::sources()`) | **51 ms** | +| — of which the substring prefilter over all of them | 0.26 ms | +| — of which parsing + walking the 26 files that mention the name | ~5 ms | +| `outgoingCalls` for the corpus's densest module (`uart_reg_top.sv`, 63 instantiation sites, 4 distinct resolvable targets) | **2.2 ms** | +| the same `incomingCalls` in a debug build | 106 ms | + +Two things the table says. First, `incomingCalls` costs **4× less than M7's +`textDocument/references`** on the same corpus (218 ms) even though it answers +a superset of the question — it needs the *caller*, not just the span. The +reason is the prefilter: a module that is instantiated somewhere has its name +written there, so a file whose text does not contain the name is skipped +before it is parsed, and 834 of 860 files are. Second, what is left is +**almost entirely file I/O** — `sources()` reads every in-scope file whether +it will be parsed or not. That is the shared cost of every cross-file answer +in this server, and the place a future win lives (see backlog); nothing in +this feature can shave it alone. + +`prepare` and `outgoingCalls` never walk the workspace at all: they parse the +buffer and, at most, one file per distinct instantiated module. + +**The 4× claim is specific to `prim_flop_2sync`, not general.** It holds +because the substring prefilter skips 834 of 860 files for that name. QA +(2026-08-25) measured the prefilter's worst case: a module name that is a +substring of nearly every file (a single letter, in the probe) admits close +to all 860 files for parsing regardless of whether any of them really +instantiate it. Release, this machine: **206 ms** — close to, not below, +`references`'s 218 ms. Still correct (zero calls, since no such module is +declared), and still not a hang, but the speed claim is a property of the +*name being looked up*, not a guarantee `incomingCalls` gives universally. +Real single- or two-letter module names are not a corpus pattern seen so far; +recorded here rather than in the backlog because it is a measurement, not a +design gap. See `hierarchy::tests::qa_perf_worst_case_common_word_module_name` +(`#[ignore]`d, run with `cargo test --release -p vfmt_server --bin +vfmt-server qa_perf_worst_case -- --ignored --nocapture`). + +## Status / TODO + +- [x] `crates/vfmt_server/src/instantiations.rs`: the shared walk, lifted out + of `inlay.rs` with the enclosing declaration threaded through it +- [x] `crates/vfmt_server/src/inlay.rs`: reads the shared walk, behavior + unchanged (its own 34 tests re-run green untouched) +- [x] `crates/vfmt_server/src/hierarchy.rs`: `prepare`, `incoming`, `outgoing` +- [x] `callHierarchyProvider` in `main.rs`; three dispatch arms in `server.rs` +- [x] `prepare` on a declaration / on an instantiation / on anything else + (`null`), including an instance name, a connected expression, a keyword, + a package and a module nothing declares +- [x] Ambiguity: every declaration from `prepare`, silence from `outgoing` +- [x] Generate regions, `bind`, instance arrays, several instances in one + statement and ordered connection lists found in both directions +- [x] Self-instantiation: both directions answer one hop and neither hangs +- [x] Scope ladder and unsaved-buffer overlay honoured by `incomingCalls` +- [x] UTF-16 positions, an untitled buffer, a file that has since moved, a + buffer that does not parse +- [x] Unit tests (25 in `hierarchy.rs`, 7 in `instantiations.rs`, 1 capability + test in `main.rs`) and one e2e stdio round trip: prepare → incoming → + outgoing across three files +- [x] Cost measured over the 860-file corpus, with the I/O split out +- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`, + `cargo test --workspace`, `editors/vscode/smoke.js` +- [x] `docs/features/vfmt-server/README.md` capability table + work log +- [ ] Not done, backlog: an **instantiation edge table in `WorkspaceIndex`**, + built with the index, which would make `incomingCalls` a map lookup and + cost one extra tree walk per file at index time. Worth doing when + something else wants the same edges (a design-tree view, an + unused-module lint); today one request in 56 ms does not justify + widening the index's contract. +- [ ] Not done, deliberately: type hierarchy (`typeHierarchy`) for classes, + interface and program instantiations as their own node kind, and any + whole-tree "show me the design" view — this milestone is exactly the + two directions of the module graph. + +## Work log + +- **2026-08-25 (dev)** — read `workspace-index`, `vfmt-server`, + `references-nav` and `inlay-hints` READMEs, then `nav.rs`, `inlay.rs` and + `workspace.rs` before writing anything. + + **Finding that shaped the design: the index holds no instantiation edges.** + `WorkspaceIndex` records what each file *declares* (units and their exported + members) and nothing about what it uses. So "who instantiates X" cannot be a + lookup, and the two honest options were M7's `find_references` machinery or + a fresh walk of the in-scope files. + + **Design decision 1 — walk, don't reuse `find_references`.** References + answer *where a name appears*; an incoming call needs *which module the + appearance is inside*, which references cannot say. Reusing them would have + meant collecting spans and then parsing every hit file a second time to + attribute each span to a module — strictly more work than one walk that + carries the owner along. Measured after the fact: 56 ms against + `find_references`'s 218 ms on the same corpus, because the walk can skip a + file on a substring test before parsing it and references cannot (it must + analyze to know what a name resolves to). + + **Design decision 2 — the shared walk carries the owner, and `inlay.rs` + ignores it.** The brief asked for the `inlay.rs` walk to be factored rather + than copied. The lifted version threads the innermost enclosing `Decl` + through the recursion; `inlay.rs` maps straight past it. That also gave + outgoing calls their boundary for free: walking a *module's* items makes the + instantiations written directly in it the ones whose owner is `None`, so a + neighbouring or nested module's instantiations are never claimed as this + module's. `inlay.rs`'s 34 tests were not touched and are green, which is the + evidence the factoring changed nothing. + + **Design decision 3 — the substring prefilter.** `callers_in` returns early + when the file's text does not contain the module's name. This is not a + heuristic: an instantiation of `fifo` writes `fifo`, so a file that does not + contain those four bytes cannot contain one. It turns the walk from 860 + parses into 26, and is the whole reason this request is cheaper than + references. + + **Ambiguity is answered two different ways**, which is worth stating plainly + because it looks inconsistent: `prepare` returns every declaration (the + protocol takes a list and the *user* is there to choose, exactly as + go-to-definition does), and `outgoing` skips (a node in a tree has nobody to + ask, and a wrong node is unfalsifiable to the reader — the same argument + `inlay.rs` makes for drawing no hint). + + **Nested modules.** The walk supports them; today's parser recovers a nested + `module` into sibling items instead of nesting them. Rather than write tests + asserting a shape the parser does not produce, the equivalent case is pinned + with two modules in one file — the real, legal, common shape that the owner + attribution has to get right — plus one test that both names are found + however the nested form parses. + + **Files touched.** New: `crates/vfmt_server/src/instantiations.rs`, + `crates/vfmt_server/src/hierarchy.rs`, this README. Edited: + `crates/vfmt_server/src/inlay.rs` (its private walk removed, the shared one + called; no behavior change), `crates/vfmt_server/src/main.rs` (two module + declarations, the capability, two tests), + `crates/vfmt_server/src/server.rs` (three dispatch arms and their imports), + `crates/vfmt_server/tests/e2e.rs` (one new test), + `docs/features/vfmt-server/README.md` (capability table and work log). + + **Not touched, deliberately:** `TODO.md` and the umbrella checklist in + `docs/features/refactor/README.md` (the lead's, per the brief), `nav.rs`, + `state.rs`, `vlog_semantic`, `vlog_refactor`, `editors/`. No version bump. + + **Gates.** `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` + zero warnings, `cargo test --workspace` green at **1463 passed, 0 failed** + (1429 before; +34 = 25 in `hierarchy.rs`, 7 in `instantiations.rs`, 1 in + `main.rs`, 1 e2e round trip). `node editors/vscode/smoke.js + target/release/vfmt-server`: OK. No new dependencies. No commits. + +## QA log + +- **2026-08-25 (QA)** — read this README, `inlay-hints/README.md` (for the + factoring claim and its own `ifdef` precedent), `instantiations.rs` and + `hierarchy.rs` end to end before touching anything. + + **Gates.** `cargo fmt --all -- --check`, `cargo clippy --all-targets + --workspace`, `cargo test --workspace` all clean before any QA change — + **1463 passed, 0 failed**, matching the dev's number exactly (summed the + per-crate `test result` lines by hand to be sure). `node + editors/vscode/smoke.js target/release/vfmt-server` — OK, against a + freshly rebuilt release binary. Independently re-ran the dev's own corpus + perf test in release: **25 callers, 63.7 ms** — same order as the claimed + 56 ms (normal run-to-run variance), same caller count. + + **Factoring check.** `git diff HEAD -- crates/vfmt_server/src/inlay.rs`: + the private `instantiations`/`walk`/`block` functions (previously at the + bottom of the file) are deleted in full; the only other change is the call + site (`instantiations(&doc.tree)` → `instantiations::sites(&doc.tree.items)`, + with `.inst` field access) and one internal test updated the same way. + Nothing else in the file moved. Read `instantiations.rs`'s `walk`/`block` + side by side with the deleted code: identical control flow, node-for-node, + with `Option` threaded as an extra parameter and `owner` attached to + each `Site`. The verbatim claim holds. Confirmed separately that + `inlay.rs`'s 34 tests are untouched (diff shows no test-body edits besides + the one call-site change) and green. + + **Break-it testing.** Added 11 tests to `hierarchy.rs` (10 permanent, 1 + `#[ignore]`d perf probe) and one e2e test, all listed below with what they + found. All pass; full suite re-green after at **1474 passed, 4 ignored, 0 + failed** (1463 + 10 hierarchy.rs + 1 e2e; the 11th QA test is the ignored + perf probe). + + - *Generate `for` with a genvar-indexed instance.* Covered by the dev's own + `incoming_calls_reach_generate_regions_bind_and_instance_arrays` — one + `Instantiation` node inside the loop body gives one `fromRange` + regardless of the genvar's range, which is correct under the "one AST + node is one call site" assumption. Re-verified by hand; no new test + needed. + - *`bind` in another file, target ≠ owner.* New test + `qa_bind_owner_is_the_module_containing_the_directive_not_the_bind_target` + — `bind top chk u_chk();` written inside `module harness` in a third + file: `incoming(chk)` names `harness` as the caller, not `top`. This is + the honest answer given the feature's own "instantiation is the call, + enclosing module is the caller" assumption — `bind`'s *effect* targets + `top`, but the *instantiation text* sits in `harness`, and vfmt only ever + reads text. Not a bug; not previously tested at this granularity (the + dev's own bind test has target == owner, which cannot distinguish the + two). + - *A module name that is a word in a comment elsewhere.* New test + `qa_prefilter_over_admits_but_walk_rejects_a_comment_only_mention` — + `widget` appears only inside `// this file mentions widget only in a + comment` in `b.sv`. The substring prefilter admits `b.sv` for parsing (as + designed — it can't know the difference from source text alone), but the + walk's `site.inst.module != name` filter means no false incoming call. + Confirmed correct; no over-admission reaches the client. + - *Instantiation under `` `ifdef``.* **Finding, MEDIUM, documented.** + `outgoing(top)` for `` `ifdef A sub_a u1(); `else sub_b u1(); `endif`` + inside `top` returns **both** `sub_a` and `sub_b` as real calls — the + parser does not evaluate `` `ifdef`` at the item level (confirmed + against `vlog_parser::parser::parse_item_kind`; both arms become + ordinary `Instantiation` items in source order). This is arguably the + honest answer — vfmt cannot know which arm is live and showing both is + not a single wrong claim the way a mis-ordered inlay hint would be — but + it was **undisclosed**: no Assumption, Handshake, or test mentioned + `` `ifdef`` anywhere in this feature, despite `inlay-hints/README.md` + treating the identical directive shape as a first-class, tested case one + milestone earlier. **Fix applied (documentation only, no behavior + change):** added an Assumptions bullet explaining the policy and why it + differs from `inlay.rs`'s silence. Pinned by new test + `qa_ifdef_instantiation_both_arms_are_reported_undisclosed_in_the_readme`. + - *Same module instantiated inside a `package`.* New test + `qa_instantiation_in_a_package_does_not_crash` — illegal-ish + SystemVerilog, reachable through the tolerant parser. No panic; no + assertion on the answer itself (`incoming` returns empty, since + `Package` items aren't part of what `outgoing` walks either way) — + survival was the point. + - *Outgoing, ambiguous target, no leak.* New test + `qa_outgoing_ambiguous_does_not_leak_fromranges_into_resolved_entries` — + a module instantiating both `sub` (resolvable) and `dup` (declared + twice, ambiguous) gets exactly one outgoing call, for `sub`, and its + `fromRanges` are exactly `sub`'s two sites — `dup`'s site does not leak + in. Confirms the dev's `filter_map` in `hierarchy.rs:112-120` drops the + whole `(name, spans)` pair together, not just the `to`. + - *Outgoing, nested module declaration boundary.* New test + `qa_outgoing_nested_module_declaration_boundary`, using the dev's own + pinned fixture shape from `instantiations.rs` (`module outer; module + inner; ... endmodule endmodule`) driven through the public `hierarchy` + API rather than the private walk: `outgoing(outer)` is empty and + `outgoing(inner)` claims `sub`. The parser's sibling-recovery shape does + not leak `inner`'s instantiations into `outer`'s answer. + - *Prepare on a string or comment.* New test + `qa_prepare_on_a_string_or_comment_is_null` — cursor inside `// sub lives + here` and inside `"sub"` both prepare `null`. Correct: neither + `declarations()` nor `sites()` covers comment or string text, by + construction. + - *Prepare on a bind target.* **Finding, LOW-MEDIUM, documented, not + fixed.** Cursor on `top` in `bind top chk u_chk();` — a real reference + to a really-declared module — prepares `null`. Neither `declarations()` + (only sees `module ...` headers) nor `sites()` (a bind's site span is + `chk`'s, the instantiated module, not the target) covers that text. This + fails safe rather than corrupting anything, and is arguably a defensible + scope boundary (the bind's *target* module is not itself an + instantiation site), but it was untested and undocumented, and a user + right-clicking a bind target reasonably expects a hierarchy view. Not + fixed — this is a design call for the lead, not an unambiguous typo-class + fix. Pinned as today's actual behavior by + `qa_prepare_on_a_bind_target_module_name_is_currently_null`, named to + make clear it is not being endorsed. + - *Cycles, `a → b → a`, two hops.* New test + `qa_cycle_a_to_b_to_a_two_hops_no_hang` — `outgoing(a)` → `b`, + `outgoing(b)` → `a`, `incoming(b)` → `a`, each a clean one-hop answer, no + recursion, no hang. Confirms the "client drives the expansion" design + holds under an actual two-node cycle, not just self-instantiation (which + the dev already covers in + `a_self_instantiating_module_is_its_own_caller_and_does_not_hang`). + - *Consistency: `incoming(X)` vs `outgoing(parent)`.* New test + `qa_consistency_incoming_x_matches_outgoing_parent_of_x`, run over the + three-file fixture (`hier_mid`/`hier_top`/`hier_other` shape): for every + caller `incoming(sub)` names, `outgoing(that caller)` has a matching + `sub` entry with the exact same `fromRanges` (sorted, compared + pointwise). This is the property that makes the two directions honest + with each other, and it holds. + - *Perf, worst case.* **Finding, MEDIUM, documented.** The realistic-case + corpus number (56 ms, re-verified at 63.7 ms) is not a general bound: a + module name that is a substring of nearly every file (a single letter, + in the probe) defeats the prefilter almost entirely. Release measurement: + **206 ms**, versus the 218 ms `references` baseline the feature claims a + 4× win over — i.e. the worst case erases nearly all of the claimed + advantage. Still correct and still fast enough to not be a hang, but the + "4× cheaper" framing in *Cost* read as general and is not. **Fix + applied (documentation only):** added a caveat paragraph to *Cost* + quantifying this, and kept `qa_perf_worst_case_common_word_module_name` + (`#[ignore]`d, matching the dev's own pattern for corpus-gated perf + tests) as the reproduction. + - *e2e, incoming with two `fromRanges`.* The dev's own e2e test has two + `fromRanges` only on the `outgoing` side; its `incoming` case is + single-range. New, independent test + `qa_incoming_calls_with_two_fromranges_round_trips_over_the_wire` spawns + the real binary twice (one session to `prepare`, a second, fresh session + to send the resulting item to `incomingCalls` — closer to what a real + client does across two requests than reusing one open connection): + `mid2` instantiates `sub2` twice, and `incomingCalls` returns one call + from `mid2` with both `fromRanges`, at the right lines, over the wire. + + **Everything else tried to break, and did not, no new test needed:** + - *Instance array (`sub u [3:0] (...)`) and several instances in one + statement.* Already covered by the dev's own + `incoming_calls_reach_generate_regions_bind_and_instance_arrays`; + independently re-derived by hand against `Instantiation::instances` and + agree it is one call site regardless of instance count. + - *UTF-16 positions, an untitled buffer, a moved file, a buffer that does + not parse.* Dev's own tests (`positions_are_utf16_units_on_a_line...`, + `an_untitled_buffer_prepares_from_itself`, + `an_item_naming_a_file_that_is_gone_answers_with_no_calls`, + `a_buffer_that_does_not_parse_invents_no_calls`) re-run and agree with + the assertions as written. + - *Cursor on an instance name (`u1`), not the module.* Already covered by + the dev's `a_position_on_no_module_prepares_nothing`. Assessed: `null` + is right — an instance name is not module text under any of this + feature's own assumptions, and the alternative (walking outward to the + nearest enclosing instantiation) is a different, undiscussed feature. + + **Verdict: ship-after-fixes.** The two MEDIUM findings (`ifdef` behavior, + worst-case prefilter perf) are addressed the same way the dev's own + `inlay-hints` QA round handled its `ifdef` finding *in spirit* — except + here the underlying behavior is judged acceptable and the fix is + documentation, not code, because unlike inlay hints a hierarchy edge is a + fact about text ("this instantiation exists, conditionally") rather than a + single confident claim that can be *wrong*. The LOW-MEDIUM bind-target + finding is a real gap but not unambiguous enough for QA to fix unilaterally + (it is a scope question, not a typo) — left for the lead. Nothing else + found rises above documentation, and every new claim added above is now + pinned by a test. No commits made. + +## Review + +**2026-08-25 — lead.** Reviewed after QA's verdict (doc-only fixes, +already applied); gates run independently (1474 tests, 0 failures). The +two design calls that matter are both right: the walk over M7's +references (an incoming call needs the enclosing module, which +references cannot attribute — and it measured faster), and owner +threading giving outgoing its module boundary for free. QA verified the +factoring verbatim and, most valuably, the incoming/outgoing consistency +property on a fixture — the check that keeps the two directions honest. +Rulings on QA's findings: the `ifdef` both-arms answer is accepted and +now disclosed (consistent with the parser's no-evaluation stance; unlike +inlay hints, hierarchy answers are lists the user inspects, so listing +both arms is honest rather than wrong); the prefilter-defeating-name +cost caveat is accepted; prepare-on-bind-target returning null is an +accepted completeness gap — recorded here as backlog rather than fixed, +since the right answer needs a design decision about whether a bind +target is a "call" at all. Accepted; M11 checked off in the umbrella +plan and TODO §8. + diff --git a/docs/features/inlay-hints/README.md b/docs/features/inlay-hints/README.md index f39248e..cc3f87e 100644 --- a/docs/features/inlay-hints/README.md +++ b/docs/features/inlay-hints/README.md @@ -242,6 +242,19 @@ buffer) that is not worth paying for today. 1 e2e round trip). `node editors/vscode/smoke.js` against the release binary: OK. No new dependencies. No commits. +- **2026-08-25 (dev, M11 hierarchy)** — the private instantiation walk at the + bottom of `inlay.rs` moved to `crates/vfmt_server/src/instantiations.rs`, so + the call hierarchy can read the same one instead of writing a second + (`docs/features/hierarchy/README.md`). The lifted version threads the + innermost enclosing module declaration through the recursion; `inlay_hints` + maps straight past it, and nothing else in this module changed — + `instantiations(&doc.tree)` became `instantiations::sites(&doc.tree.items)` + and the four walk functions were deleted. Every test in this file was left + untouched and is green, which is the evidence the behavior is identical. + **Handshake note:** the *Handshakes* bullet about consuming + `vlog_parser::ast` now goes through `crate::instantiations`; the AST nodes + read are the same ones. + ## QA log - **2026-08-24 (QA)** — read this README, `refactor-instantiate/README.md` diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md index 927f4be..76800b1 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -164,7 +164,7 @@ built but nothing consumes yet. Ordered by value ÷ cost: and the define table stays per-file. Document links (or definition) on include lines, resolved through the filelist's incdirs, and a cross-file define-table lookup along the include graph. -- [ ] **Module hierarchy** — "who instantiates X / what does X +- [x] **Module hierarchy** — "who instantiates X / what does X instantiate", as LSP callHierarchy (modules as the nodes) or a custom request the extension renders; the index already knows both directions. - [ ] **Semantic lint rules** — unused-signal, undriven-net, @@ -265,6 +265,7 @@ commit — in order: - [x] M8 inlay-hints — done, one QA HIGH fixed in-round, reviewed - [x] M9 file-watching — done, QA clean first pass, reviewed - [x] M10 include-nav — done, one QA HIGH reworked, reviewed +- [x] M11 hierarchy — done, QA doc-fixes in-round, reviewed ## Work log diff --git a/docs/features/vfmt-server/README.md b/docs/features/vfmt-server/README.md index 1c4bb0d..b85e44f 100644 --- a/docs/features/vfmt-server/README.md +++ b/docs/features/vfmt-server/README.md @@ -32,6 +32,9 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/completion` | `vlog_refactor::instantiation_plan` | Module hinting: one item per indexed module, inserting the whole instantiation skeleton as a snippet (plain text for a client that did not advertise `snippetSupport`). Capped at 64 items, `isIncomplete` when truncated; declines every position that is not module-item. See `docs/features/refactor-instantiate/README.md` | | `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/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 | | `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` | @@ -473,11 +476,44 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: together with the include case of `textDocument/definition` and hover's include-graph precedence for `` `define``. `docs/features/include-nav/README.md`. +- [x] `callHierarchy` (all three requests) — delivered by **hierarchy** (M11): + the module hierarchy both directions, modules as the nodes and + instantiations as the calls, off a walk shared with the inlay hints. + `docs/features/hierarchy/README.md`. - [ ] **Not done:** editor packaging (the VS Code extension and the `lspconfig` snippet are their own TODO.md §6 item). ## Work log +### 2026-08-25 — dev agent (M11 hierarchy) + +- **One new capability, two new modules, one lifted walk.** + `callHierarchyProvider` is advertised as a plain `true` — the three requests + are either all served or none are — `server.rs` gained three dispatch arms, + and `crates/vfmt_server/src/hierarchy.rs` holds the answers. No engine + change: `WorkspaceIndex` is read exactly as before. +- **The instantiation walk is now shared.** + `crates/vfmt_server/src/instantiations.rs` holds the walk that used to be + private to `inlay.rs`, with the innermost enclosing module declaration + threaded through it. `inlay.rs` calls it and ignores the owner; its 34 tests + were left untouched as the evidence that the factoring changed nothing. + Hierarchy uses the owner for both directions — it is what makes an incoming + call name the *calling module* rather than a span, and what stops a + neighbouring module's instantiations from being claimed as this module's. +- **The index holds no instantiation edges**, so "who instantiates X" is a + walk of the in-scope files rather than a lookup. It is nonetheless 4× + cheaper than `textDocument/references` on the same corpus (56 ms against + 218 ms), because a file that does not contain the module's name cannot + instantiate it and is skipped before it is parsed. An edge table in + `WorkspaceIndex` is recorded as backlog in the feature README, not built. +- **Ambiguity is answered two ways on purpose**: `prepare` returns every + declaration (the protocol takes a list and the user is there to choose), + `outgoingCalls` skips silently (a tree node has nobody to ask, and a wrong + node is unfalsifiable to the reader). +- Nothing else moved: `state.rs`, `nav.rs`, `vlog_semantic`, `vlog_refactor` + and `editors/` are untouched, and there is no version bump. Full details, + assumptions and numbers: `docs/features/hierarchy/README.md`. + ### 2026-08-24 — dev agent (M8 inlay-hints) - **One new capability, one new module, nothing else moved.**