Files
lucisv/crates/lucisv_server/src/hierarchy.rs
T
lucioandClaude Fable 5 311551f232 Interface semantics: interfaces, modports and clocking blocks become symbols; vif.sig crosses files
coverage_gaps C2/H2, topo 2.9-7 delivered. SymbolKind::{Interface,
Modport, Clocking}; is_instantiable() (Module | Interface) is the one
predicate every 'is this a module' filter reads, pinned in place, so
interfaces stay in the module table, the ghost, the hierarchies and the
refactorings while the card finally says 'interface'. An interface
exports its signals - they ARE its surface - where a module still exports
ports and params only, which is what lets virtual my_if vif; vif.sig
resolve across files. Modport and clocking-internal names bind as
scope-local references (nothing on a miss - a lexical walk would land a
modport port on a file-scope lure); the modport half of bus_if.mp in a
type position is Target::TypeMember, resolved through type_here; a
clocking block carries type_name = its enclosing unit so vif.cb.data
hops through round-2 machinery unchanged. FACTS_FORMAT 7 -> 8.

Unresolved fell 1256 -> 1203 on the corpus, the first movement in three
rounds: the @(cb) / cb.data names that had nothing to bind. Store +1.2
percent. A modport now renames from its type-position use (the refactor
pin flipped at review). QA: 17 opentitan probes, zero wrong answers, all
sub-millisecond; vif.cb.scl_i lands on i2c_if.sv's own signal.

docs/features/interface-semantics/README.md; TODO.md section 16.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 22:53:27 -07:00

1065 lines
45 KiB
Rust

//! `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::instantiations::{self, Decl};
use vlog_semantic::{DeclSite, InstantiationEdge};
use crate::convert::Positions;
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<Vec<CallHierarchyItem>> {
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.
///
/// One name asked of the batch below, which is the only census in this server
/// — the code lens counts what this lists.
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
}
/// Who instantiates each of `names`, answered one list per name in the order
/// asked.
///
/// **A lookup in the workspace index's instantiation-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The census is unchanged — the table is built by the same
/// [`instantiations::sites`] walk this function used to run, at index time
/// (`docs/features/incremental-index/README.md`) — and so is the answer's
/// shape and order. What changed is the cost: only the files that really do
/// instantiate one of the names are read, to turn the recorded byte spans into
/// the protocol's line/character ranges.
///
/// The **batch** stays the primitive: `lens.rs` asks about every module
/// declared in a buffer at once, and one file that instantiates three of them
/// is read once for the batch rather than once per name.
///
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyIncomingCall>> {
let index = ws.index();
let mut answers: Vec<Vec<CallHierarchyIncomingCall>> =
names.iter().map(|_| Vec::new()).collect();
// Every file holding an edge for any of the names, once, in path order.
let mut files: Vec<vlog_semantic::FileId> = names
.iter()
.filter(|name| !name.is_empty())
.flat_map(|name| index.instantiations_of(name).iter().map(|edge| edge.file))
.collect();
files.sort();
files.dedup();
for file in files {
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
// The spans were recorded against the text the index was built from;
// this is the text now. The two differ only for a buffer edited since
// the last rebuild, which is the same staleness `item_in_file` has
// always carried.
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for (at, name) in names.iter().enumerate() {
if name.is_empty() {
continue;
}
let edges = index.instantiations_of(name).iter().filter(|edge| edge.file == file);
answers[at].extend(callers_in(&uri, &positions, edges));
}
}
for answer in &mut answers {
answer.sort_by(|a, b| {
(a.from.uri.as_str(), key(a.from.selection_range))
.cmp(&(b.from.uri.as_str(), key(b.from.selection_range)))
});
}
answers
}
/// What this module instantiates: one call per **distinct instantiated
/// 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<CallHierarchyOutgoingCall> {
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<TextRange>)> = 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()
}
/// One file's edges for one module, as incoming calls: one call per
/// instantiating module, with every site inside it.
///
/// Sites are grouped by the declaration they sit in rather than by adjacency,
/// because a module written inside another can put its own sites between two
/// of the outer module's.
fn callers_in<'a>(
uri: &Uri,
positions: &Positions,
edges: impl Iterator<Item = &'a InstantiationEdge>,
) -> Vec<CallHierarchyIncomingCall> {
let mut callers: Vec<(&DeclSite, Vec<TextRange>)> = Vec::new();
for edge in edges {
match callers.iter_mut().find(|(owner, _)| owner.span == edge.owner.span) {
Some((_, spans)) => spans.push(edge.site_span),
None => callers.push((&edge.owner, vec![edge.site_span])),
}
}
callers
.into_iter()
.filter_map(|(owner, spans)| {
Some(CallHierarchyIncomingCall {
from: item_of(uri.clone(), positions, &owner.name, owner.name_span, owner.span)?,
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<CallHierarchyItem> {
item_of(uri, positions, &decl.module.name, decl.module.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's edge
/// table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<CallHierarchyItem> {
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 span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(CallHierarchyItem {
name: name.to_string(),
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<CallHierarchyItem> {
ws.index()
.units(name)
.iter()
.filter(|def| def.kind.is_instantiable())
.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<CallHierarchyItem> {
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<TextRange>,
) -> Option<CallHierarchyItem> {
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<TextRange>) -> Option<Decl<'a>> {
let decls: Vec<Decl> =
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<String> {
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!("lucisv_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_whole_workspace(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<u32> {
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`");
}
/// An interface is instantiated exactly as a module is, so the call
/// hierarchy still finds its declaration from an instantiation site
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn the_cursor_on_an_interface_instantiation_prepares_the_interface() {
const IFACE: &str = "interface bus_if;\nendinterface\n";
const USER: &str = "module top;\n bus_if u_bus ();\nendmodule\n";
let (_tree, ws, uri) = workspace("ifaceprepare", &[("top.sv", USER), ("bus_if.sv", IFACE)]);
let items = prepare(&ws, &uri, at(USER, "bus_if")).expect("the interface");
assert_eq!(items.len(), 1);
assert_eq!(shape(&items[0]), ("bus_if".to_string(), "bus_if.sv".to_string(), 0));
}
#[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<String> = 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::<Vec<_>>(),
[
("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("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(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_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the
// census reading `Workspace::sources()` on every request, so a
// keystroke in *another* buffer moved the count before anything
// rebuilt. The census is the index's edge table now, and an index is
// only ever as of its last build or update — which does fold every
// open buffer in, so a save (or any other rescan trigger) makes the
// edit count. The rule the test pins is the new one, from both sides.
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(),
2,
"the buffer alone does not move the census — the index has not seen it"
);
// What a save does, and what the incremental path does with it.
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert_eq!(incoming(&ws, &root).len(), 1, "the edit 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::<Vec<_>>(),
[
("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<String> {
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 — lucisv 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<String> = 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 used to be the worst case there was: it
// is a substring of nearly every file, so the prefilter over
// `Workspace::sources()` admitted nearly everything. There is no
// prefilter and no walk since 2026-08-27 — the census is a lookup in
// the index's edge table, and a name nothing instantiates is an empty
// slice — so this probe is kept for what it now measures: that the
// shape which used to be the worst case is not a case at all.
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_whole_workspace(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_whole_workspace(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:?}");
}
}