LSP: call and type hierarchy answer from anywhere in a body; functions and tasks are call-hierarchy nodes
Show Call Hierarchy was empty in VS Code unless the cursor sat on a module
name. prepareCallHierarchy now answers on an instance name (its module),
on a function/task declaration, call or end label (a FUNCTION/METHOD item
with data {kind,name,offset}), inside a function/task body (that one), and
inside a module/interface/program (the enclosing module). Function/task
items: incomingCalls = call sites grouped by the enclosing function/task or
unit, over the same files references reads; outgoingCalls = resolved
callees (system tasks and unresolved names skipped). A function's bare name
in its own body is its result variable, not recursion. Module items keep
instantiation edges, byte-identical. prepareTypeHierarchy answers the
enclosing class inside a class body and the base on `super`.
QA (Opus): old module answers identical at 3 137 positions; outline,
definition, references, hover unchanged at 1 340 queries; findings fixed in
a rework (outgoing over a closed 300-function package 3.0 s -> 18 ms). Two
e2e assertions that pinned the old null flipped (lead's handshake).
lucisv_server 1 862 passed, 0 failed; fmt, clippy -D warnings clean.
docs/features/call-hierarchy-everywhere.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
5e4af0be3d
commit
31b7db16a3
10 files changed
+2387
-40
No files matched your search
@@ -30,12 +30,18 @@ use crate::convert::Positions;
|
|||||||
use crate::state::Workspace;
|
use crate::state::Workspace;
|
||||||
use crate::uri::{path_to_uri, uri_to_path};
|
use crate::uri::{path_to_uri, uri_to_path};
|
||||||
|
|
||||||
/// The module the cursor names, as the root of a hierarchy — its own
|
mod calls;
|
||||||
/// declaration, or an instantiation of it.
|
mod tf;
|
||||||
|
|
||||||
|
/// The root of a hierarchy at the cursor.
|
||||||
///
|
///
|
||||||
/// `None` for every other position, which is what stops an editor from opening
|
/// In order: a module's own declaration name, or the module name of an
|
||||||
/// an empty hierarchy view on a `wire`. A name the workspace index does not
|
/// instantiation (both unchanged since M11); an instance name, which stands
|
||||||
/// hold as a module declines the same way: there is no node to stand on.
|
/// for the instantiated module; a function or task the cursor names — its
|
||||||
|
/// declaration, a call, its end label; the function or task whose body holds
|
||||||
|
/// the cursor; and the module, interface or program whose body holds it.
|
||||||
|
/// `None` only where nothing encloses the cursor, which is what stops an
|
||||||
|
/// editor from opening an empty view.
|
||||||
///
|
///
|
||||||
/// A name two files declare returns *both* items rather than a guess, the same
|
/// A name two files declare returns *both* items rather than a guess, the same
|
||||||
/// answer `textDocument/definition` gives for the same ambiguity — the client
|
/// answer `textDocument/definition` gives for the same ambiguity — the client
|
||||||
@@ -51,11 +57,27 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
|
|||||||
let positions = doc.positions();
|
let positions = doc.positions();
|
||||||
return Some(vec![item(uri.clone(), &positions, decl)?]);
|
return Some(vec![item(uri.clone(), &positions, decl)?]);
|
||||||
}
|
}
|
||||||
// The cursor on an instantiation names the module being instantiated.
|
// The cursor on an instantiation names the module being instantiated —
|
||||||
|
// through its module name or through one of its instance names.
|
||||||
let sites = instantiations::sites(&doc.tree.items);
|
let sites = instantiations::sites(&doc.tree.items);
|
||||||
let site = sites.iter().find(|site| touches(site.inst.module_span, offset))?;
|
let on_module = sites.iter().find(|site| touches(site.inst.module_span, offset));
|
||||||
let items = declarations_of(ws, &site.inst.module);
|
let on_instance = || {
|
||||||
(!items.is_empty()).then_some(items)
|
sites.iter().find(|site| site.inst.instances.iter().any(|i| touches(i.name_span, offset)))
|
||||||
|
};
|
||||||
|
if let Some(site) = on_module.or_else(on_instance) {
|
||||||
|
let items = declarations_of(ws, &site.inst.module);
|
||||||
|
if !items.is_empty() {
|
||||||
|
return Some(items);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(items) = tf::prepare(ws, doc, uri, offset) {
|
||||||
|
return Some(items);
|
||||||
|
}
|
||||||
|
let decl = instantiations::declarations(&doc.tree.items)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|decl| tf::holds(decl.span, offset))
|
||||||
|
.min_by_key(|decl| decl.span.end - decl.span.start)?;
|
||||||
|
Some(vec![item(uri.clone(), &doc.positions(), decl)?])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Who instantiates this module: one call per **instantiating module**, with
|
/// Who instantiates this module: one call per **instantiating module**, with
|
||||||
@@ -63,7 +85,14 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
|
|||||||
///
|
///
|
||||||
/// One name asked of the batch below, which is the only census in this server
|
/// One name asked of the batch below, which is the only census in this server
|
||||||
/// — the code lens counts what this lists.
|
/// — the code lens counts what this lists.
|
||||||
|
///
|
||||||
|
/// A function or task item (one carrying `data`) is answered by its call
|
||||||
|
/// sites instead (`hierarchy/calls.rs`); a package or class caller item has
|
||||||
|
/// no incoming calls.
|
||||||
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
||||||
|
if let Some(data) = tf::Data::of(item) {
|
||||||
|
return calls::incoming(ws, item, &data);
|
||||||
|
}
|
||||||
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
|
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +160,13 @@ pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyI
|
|||||||
/// silently. A hierarchy node has nowhere to say "and one more I could not
|
/// 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
|
/// 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.
|
/// send the user to the wrong file with no way to tell.
|
||||||
|
///
|
||||||
|
/// A function or task item is answered by the calls in its body instead
|
||||||
|
/// (`hierarchy/calls.rs`). A module item never lists function calls.
|
||||||
pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
|
pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
|
||||||
|
if let Some(data) = tf::Data::of(item) {
|
||||||
|
return calls::outgoing(ws, item, &data);
|
||||||
|
}
|
||||||
let Some(text) = text_of(ws, &item.uri) else { return Vec::new() };
|
let Some(text) = text_of(ws, &item.uri) else { return Vec::new() };
|
||||||
let (tree, _) = parse_source_tolerant(&text);
|
let (tree, _) = parse_source_tolerant(&text);
|
||||||
let line_index = LineIndex::new(&text);
|
let line_index = LineIndex::new(&text);
|
||||||
@@ -431,12 +466,17 @@ endmodule
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reversed by call-hierarchy-everywhere (2026-10-14): the `module`
|
||||||
|
/// keyword and a connected expression are inside `top` and prepare it,
|
||||||
|
/// and an instance name stands for the instantiated module. Only a
|
||||||
|
/// position no module encloses still prepares nothing.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_position_on_no_module_prepares_nothing() {
|
fn a_position_on_no_module_prepares_the_enclosing_one_or_nothing() {
|
||||||
let (_tree, ws, uri) = three("none");
|
let (_tree, ws, uri) = three("none");
|
||||||
assert!(prepare(&ws, &uri, 0).is_none(), "the `module` keyword");
|
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
|
||||||
assert!(prepare(&ws, &uri, at(TOP, "u_a")).is_none(), "the instance name");
|
assert_eq!(name(0), "top", "the `module` keyword is inside `top`");
|
||||||
assert!(prepare(&ws, &uri, at(TOP, "1'b0")).is_none(), "a connected expression");
|
assert_eq!(name(at(TOP, "u_a")), "sub", "the instance name stands for its module");
|
||||||
|
assert_eq!(name(at(TOP, "1'b0")), "top", "a connected expression is inside `top`");
|
||||||
let (_tree, ws, uri) = workspace("nonmodule", &[("p.sv", "package p;\nendpackage\n")]);
|
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");
|
assert!(prepare(&ws, &uri, at("package p;", "p;")).is_none(), "a package is not a module");
|
||||||
}
|
}
|
||||||
@@ -448,11 +488,14 @@ endmodule
|
|||||||
assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some());
|
assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reversed by call-hierarchy-everywhere (2026-10-14): no item for
|
||||||
|
/// `nope`, which nothing declares, but the module the cursor is inside.
|
||||||
#[test]
|
#[test]
|
||||||
fn an_instantiation_of_a_module_nothing_declares_prepares_nothing() {
|
fn an_instantiation_of_a_module_nothing_declares_prepares_the_enclosing_module() {
|
||||||
let top = "module top;\n nope u1 ();\nendmodule\n";
|
let top = "module top;\n nope u1 ();\nendmodule\n";
|
||||||
let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]);
|
let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]);
|
||||||
assert!(prepare(&ws, &uri, at(top, "nope")).is_none());
|
let items = prepare(&ws, &uri, at(top, "nope")).expect("the enclosing module");
|
||||||
|
assert_eq!(shape(&items[0]), ("top".to_string(), "top.sv".to_string(), 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -894,18 +937,38 @@ endmodule
|
|||||||
assert_eq!(inner_calls[0].to.name, "sub");
|
assert_eq!(inner_calls[0].to.name, "sub");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reversed by call-hierarchy-everywhere (2026-10-14): a comment or a
|
||||||
|
/// string inside `top` prepares `top` — never the `sub` its text spells.
|
||||||
#[test]
|
#[test]
|
||||||
fn qa_prepare_on_a_string_or_comment_is_null() {
|
fn qa_prepare_on_a_string_or_comment_is_the_enclosing_module_not_the_text() {
|
||||||
let text = "module top;\n // sub lives here\n string s = \"sub\";\nendmodule\n";
|
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 (_tree, ws, uri) = workspace("qa_string_comment", &[("top.sv", text)]);
|
||||||
let comment_offset = at(text, "// sub");
|
let comment_offset = at(text, "// sub");
|
||||||
let string_offset = at(text, "\"sub\"") + 1;
|
let string_offset = at(text, "\"sub\"") + 1;
|
||||||
assert!(prepare(&ws, &uri, comment_offset + 3).is_none(), "cursor inside a comment");
|
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
|
||||||
assert!(prepare(&ws, &uri, string_offset + 1).is_none(), "cursor inside a string literal");
|
assert_eq!(name(comment_offset + 3), "top", "cursor inside a comment");
|
||||||
|
assert_eq!(name(string_offset + 1), "top", "cursor inside a string literal");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reversed by call-hierarchy-everywhere (2026-10-14): the bind target
|
||||||
|
/// is still not read as a module name, but the cursor is inside the
|
||||||
|
/// module the `bind` is written in, and that is what it prepares. The
|
||||||
|
/// fixture moves the `bind` into `harness` so the two cannot coincide.
|
||||||
#[test]
|
#[test]
|
||||||
fn qa_prepare_on_a_bind_target_module_name_is_currently_null() {
|
fn qa_prepare_on_a_bind_target_module_name_is_the_enclosing_module() {
|
||||||
|
let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n";
|
||||||
|
let top = "module top;\nendmodule\n";
|
||||||
|
let chk = "module chk;\nendmodule\n";
|
||||||
|
let files = [("harness.sv", harness), ("top.sv", top), ("chk.sv", chk)];
|
||||||
|
let (_tree, ws, uri) = workspace("qa_bind_target2", &files);
|
||||||
|
let items = prepare(&ws, &uri, at(harness, "bind top") + 5).expect("the enclosing module");
|
||||||
|
assert_eq!(shape(&items[0]).0, "harness", "not the bind target `top`");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The M11 QA pin, kept for its history: the answer it pinned is the
|
||||||
|
/// enclosing module now, which in this fixture is `top` itself.
|
||||||
|
#[test]
|
||||||
|
fn qa_prepare_on_a_bind_target_module_name_was_null() {
|
||||||
// `bind top chk u_chk ();` — cursor on `top`, the bind's *target*
|
// `bind top chk u_chk ();` — cursor on `top`, the bind's *target*
|
||||||
// module. `top` is a real, declared module and a genuine reference to
|
// module. `top` is a real, declared module and a genuine reference to
|
||||||
// it, but neither `declarations()` (which only sees `module ...`
|
// it, but neither `declarations()` (which only sees `module ...`
|
||||||
@@ -919,10 +982,8 @@ endmodule
|
|||||||
let chk = "module chk;\nendmodule\n";
|
let chk = "module chk;\nendmodule\n";
|
||||||
let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]);
|
let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]);
|
||||||
let target_offset = at(top, "bind top") + 5;
|
let target_offset = at(top, "bind top") + 5;
|
||||||
assert!(
|
let items = prepare(&ws, &uri, target_offset).expect("the enclosing module");
|
||||||
prepare(&ws, &uri, target_offset).is_none(),
|
assert_eq!(shape(&items[0]).0, "top", "the module the bind is written in");
|
||||||
"pinning today's answer, not endorsing it"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -0,0 +1,512 @@
|
|||||||
|
//! `incomingCalls` and `outgoingCalls` for a function or task item.
|
||||||
|
//!
|
||||||
|
//! A call is a *use* of the function's name that the semantic layer resolved
|
||||||
|
//! to its declaration — in this file through the symbol table, in another
|
||||||
|
//! file through the workspace overlay — and that is not one of the three
|
||||||
|
//! uses of a name that are not calls: the `endfunction : f` label, the name
|
||||||
|
//! of an out-of-body definition (`function void c::f();`), and the Verilog
|
||||||
|
//! result variable (`f = f + 1;` inside `f`).
|
||||||
|
//!
|
||||||
|
//! **Incoming** reads the same files `textDocument/references` reads: the
|
||||||
|
//! declaring file, every open buffer, and every closed file the index holds a
|
||||||
|
//! reference posting for. An ambiguous target falls back to the declaring
|
||||||
|
//! file alone, as references falls back to the cursor's file. Each call is
|
||||||
|
//! credited to its caller: the enclosing function or task, else the enclosing
|
||||||
|
//! module, interface, program, package or class.
|
||||||
|
//!
|
||||||
|
//! **Outgoing** reads the item's own body and resolves every call in it; a
|
||||||
|
//! system task, an unresolved name and an ambiguous one are skipped, as an
|
||||||
|
//! ambiguous instantiation is for a module.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, Uri};
|
||||||
|
use vlog_parser::TextRange;
|
||||||
|
use vlog_semantic::{
|
||||||
|
Def, ExternalTarget, Reference, ReferenceId, ScopeId, ScopeKind, Semantics, SymbolId,
|
||||||
|
SymbolKind as Kind,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::tf::{self, Analysis, Data};
|
||||||
|
use crate::nav::indexed_def_for_symbol;
|
||||||
|
use crate::state::{first_token_from, Document, Workspace};
|
||||||
|
use crate::uri::path_to_uri;
|
||||||
|
|
||||||
|
/// Every call of the function or task an item names, one entry per caller.
|
||||||
|
pub(super) fn incoming(
|
||||||
|
ws: &Workspace,
|
||||||
|
item: &CallHierarchyItem,
|
||||||
|
data: &Data,
|
||||||
|
) -> Vec<CallHierarchyIncomingCall> {
|
||||||
|
let Some((decl, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
|
||||||
|
let Some(name) = decl.semantics.symbol(symbol).map(|s| s.name.clone()) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
// Only a declaration the index holds — a package or class member — can be
|
||||||
|
// named through the workspace overlay, from another file or from its own
|
||||||
|
// (`super.f()` reaches a base class's method that way).
|
||||||
|
let def = decl
|
||||||
|
.path
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|_| indexed_def_for_symbol(ws, &decl, decl.semantics.symbol(symbol)?));
|
||||||
|
let mut calls = callers(&item.uri, &decl, &name, |reference, id| {
|
||||||
|
reference.resolved() == Some(symbol) || def.is_some_and(|def| names_def(&decl, id, def))
|
||||||
|
});
|
||||||
|
if let Some(elsewhere) = def.and_then(|def| other_files(ws, &decl, def, &name)) {
|
||||||
|
calls.extend(elsewhere);
|
||||||
|
}
|
||||||
|
calls.sort_by(|a, b| {
|
||||||
|
(a.from.uri.as_str(), super::key(a.from.selection_range))
|
||||||
|
.cmp(&(b.from.uri.as_str(), super::key(b.from.selection_range)))
|
||||||
|
});
|
||||||
|
calls
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The calls written in every file but the declaring one, or `None` when the
|
||||||
|
/// workspace cannot say which declaration a use names.
|
||||||
|
///
|
||||||
|
/// The same files `textDocument/references` reads for an indexed
|
||||||
|
/// declaration: every open buffer, and every closed file holding a reference
|
||||||
|
/// posting for it.
|
||||||
|
fn other_files(
|
||||||
|
ws: &Workspace,
|
||||||
|
decl: &Document,
|
||||||
|
def: &Def,
|
||||||
|
name: &str,
|
||||||
|
) -> Option<Vec<CallHierarchyIncomingCall>> {
|
||||||
|
let declaring = decl.path.as_deref()?;
|
||||||
|
if declined(ws, def, name, declaring) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let index = ws.index();
|
||||||
|
let is_call_of_def = |doc: &Document, id: ReferenceId| names_def(doc, id, def);
|
||||||
|
let mut calls = Vec::new();
|
||||||
|
for (_, doc) in ws.open_documents() {
|
||||||
|
let Some(path) = doc.path.as_deref().filter(|path| *path != declaring) else { continue };
|
||||||
|
let Some(uri) = path_to_uri(path) else { continue };
|
||||||
|
calls.extend(callers(&uri, doc, name, |_, id| is_call_of_def(doc, id)));
|
||||||
|
}
|
||||||
|
let mut closed: Vec<PathBuf> = index
|
||||||
|
.references_to(def)
|
||||||
|
.iter()
|
||||||
|
.filter_map(|site| index.path(site.file))
|
||||||
|
.filter(|path| *path != declaring && ws.document_for_path(path).is_none())
|
||||||
|
.map(Path::to_path_buf)
|
||||||
|
.collect();
|
||||||
|
closed.sort();
|
||||||
|
closed.dedup();
|
||||||
|
for path in closed {
|
||||||
|
let (Some(uri), Some(doc)) = (path_to_uri(&path), tf::load_path(ws, &path)) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
calls.extend(callers(&uri, &doc, name, |_, id| is_call_of_def(&doc, id)));
|
||||||
|
}
|
||||||
|
Some(calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the workspace cannot say which declaration a use of `def` names —
|
||||||
|
/// the index marks its uses ambiguous, or an open buffer other than the
|
||||||
|
/// declaring file holds a use that could be `def` or another declaration.
|
||||||
|
/// References declines in exactly these two cases.
|
||||||
|
///
|
||||||
|
/// In a consistent workspace neither can hold for a `def` that
|
||||||
|
/// `indexed_def_for_symbol` accepted (it demands a single record under the
|
||||||
|
/// very key every use's lookup reads), so this is the defensive half of the
|
||||||
|
/// contract; the tests reach it with a buffer the index does not hold and
|
||||||
|
/// with a lookup asked directly.
|
||||||
|
fn declined(ws: &Workspace, def: &Def, name: &str, declaring: &Path) -> bool {
|
||||||
|
ws.index().references_are_ambiguous(def)
|
||||||
|
|| ws.open_documents().any(|(_, doc)| {
|
||||||
|
doc.path.as_deref().is_some_and(|path| path != declaring)
|
||||||
|
&& names_it_ambiguously(doc, name, def)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the workspace overlay answered one use with exactly `def`.
|
||||||
|
fn names_def(doc: &Document, id: ReferenceId, def: &Def) -> bool {
|
||||||
|
matches!(doc.external.get(id), Some(ExternalTarget::Resolved(found)) if found == def)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an open buffer holds a use of `name` that could be `def` or
|
||||||
|
/// another declaration equally — the case references declines.
|
||||||
|
fn names_it_ambiguously(doc: &Document, name: &str, def: &Def) -> bool {
|
||||||
|
doc.semantics.references().iter().enumerate().any(|(at, reference)| {
|
||||||
|
reference.name == name
|
||||||
|
&& matches!(
|
||||||
|
doc.external.get(ReferenceId(at as u32)),
|
||||||
|
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(def)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One file's calls, grouped by caller, for the uses `names_target` accepts.
|
||||||
|
fn callers(
|
||||||
|
uri: &Uri,
|
||||||
|
doc: &Document,
|
||||||
|
name: &str,
|
||||||
|
names_target: impl Fn(&Reference, ReferenceId) -> bool,
|
||||||
|
) -> Vec<CallHierarchyIncomingCall> {
|
||||||
|
let semantics = &doc.semantics;
|
||||||
|
let mut groups: Vec<(SymbolId, Vec<TextRange>)> = Vec::new();
|
||||||
|
for (at, reference) in semantics.references().iter().enumerate() {
|
||||||
|
if reference.name != name || !names_target(reference, ReferenceId(at as u32)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !is_call(doc, reference) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(caller) = caller_of(semantics, reference.scope) else { continue };
|
||||||
|
match groups.iter_mut().find(|(held, _)| *held == caller) {
|
||||||
|
Some((_, spans)) => spans.push(reference.name_span),
|
||||||
|
None => groups.push((caller, vec![reference.name_span])),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let positions = doc.positions();
|
||||||
|
groups
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(caller, spans)| {
|
||||||
|
Some(CallHierarchyIncomingCall {
|
||||||
|
from: caller_item(uri, doc, caller)?,
|
||||||
|
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The declaration a call written in `scope` is credited to: the innermost
|
||||||
|
/// function or task, else the module, interface, program, package or class.
|
||||||
|
/// `None` for a call at file scope, which has no honest caller.
|
||||||
|
fn caller_of(semantics: &Semantics, mut scope: ScopeId) -> Option<SymbolId> {
|
||||||
|
loop {
|
||||||
|
let held = semantics.scope(scope)?;
|
||||||
|
let owner = held.owner;
|
||||||
|
match held.kind {
|
||||||
|
ScopeKind::Function
|
||||||
|
| ScopeKind::Task
|
||||||
|
| ScopeKind::Module
|
||||||
|
| ScopeKind::Package
|
||||||
|
| ScopeKind::Class
|
||||||
|
if owner.is_some() =>
|
||||||
|
{
|
||||||
|
return owner;
|
||||||
|
}
|
||||||
|
ScopeKind::File => return None,
|
||||||
|
_ => scope = held.parent?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The item a caller is shown as. A module caller is the very item the
|
||||||
|
/// module hierarchy hands out — no `data` — so expanding it walks
|
||||||
|
/// instantiations, one level up the design.
|
||||||
|
fn caller_item(uri: &Uri, doc: &Document, caller: SymbolId) -> Option<CallHierarchyItem> {
|
||||||
|
let symbol = doc.semantics.symbol(caller)?;
|
||||||
|
match symbol.kind {
|
||||||
|
Kind::Function | Kind::Task => tf::item(uri.clone(), doc, symbol),
|
||||||
|
Kind::Package | Kind::Class => tf::container_item(uri.clone(), doc, symbol),
|
||||||
|
_ => super::item_of(
|
||||||
|
uri.clone(),
|
||||||
|
&doc.positions(),
|
||||||
|
&symbol.name,
|
||||||
|
symbol.name_span,
|
||||||
|
symbol.decl_span,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a use of a function or task's name is a call of it.
|
||||||
|
///
|
||||||
|
/// Three uses are not: an end label (`endfunction : f`, recorded in the
|
||||||
|
/// scope *around* the function although written inside its extent), the name
|
||||||
|
/// of an out-of-body definition (recorded as a redeclaration), and the
|
||||||
|
/// Verilog result variable — a function's own name inside its own body with
|
||||||
|
/// no `(` after it, written (`f = a;`) or read (`f = f + 1;`).
|
||||||
|
fn is_call(doc: &Document, reference: &Reference) -> bool {
|
||||||
|
let semantics = &doc.semantics;
|
||||||
|
if semantics.duplicates().iter().any(|dup| dup.name_span == reference.name_span) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(id) = reference.resolved() else { return true };
|
||||||
|
let Some(symbol) = semantics.symbol(id) else { return true };
|
||||||
|
if let Some(body) = symbol.child_scope {
|
||||||
|
let inside = semantics.scope(body).is_some_and(|scope| {
|
||||||
|
tf::holds(scope.span, reference.name_span.start)
|
||||||
|
&& tf::holds(scope.span, reference.name_span.end)
|
||||||
|
});
|
||||||
|
if inside && !within(semantics, reference.scope, &[body]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
!(symbol.kind == Kind::Function
|
||||||
|
&& in_own_body(semantics, reference.scope, id)
|
||||||
|
&& !followed_by_paren(doc, reference.name_span))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `scope` is, or is nested in, a function body `function` owns — the
|
||||||
|
/// prototype's own scope or an out-of-body definition's.
|
||||||
|
fn in_own_body(semantics: &Semantics, mut scope: ScopeId, function: SymbolId) -> bool {
|
||||||
|
loop {
|
||||||
|
let Some(held) = semantics.scope(scope) else { return false };
|
||||||
|
if held.kind == ScopeKind::Function && held.owner == Some(function) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
match held.parent {
|
||||||
|
Some(parent) => scope = parent,
|
||||||
|
None => return false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the token after `span` is `(` — what makes a function's own name
|
||||||
|
/// inside its body a recursive call rather than its result variable.
|
||||||
|
fn followed_by_paren(doc: &Document, span: TextRange) -> bool {
|
||||||
|
let next = first_token_from(&doc.tokens, span.end);
|
||||||
|
doc.tokens.get(next).is_some_and(|token| token.is_sym("("))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `scope` is one of `bodies` or nested inside one.
|
||||||
|
fn within(semantics: &Semantics, mut scope: ScopeId, bodies: &[ScopeId]) -> bool {
|
||||||
|
loop {
|
||||||
|
if bodies.contains(&scope) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
match semantics.scope(scope).and_then(|held| held.parent) {
|
||||||
|
Some(parent) => scope = parent,
|
||||||
|
None => return false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a callee is, before its item is built: a declaration in the same
|
||||||
|
/// file, or one the workspace index answered.
|
||||||
|
#[derive(PartialEq)]
|
||||||
|
enum Callee {
|
||||||
|
Local(SymbolId),
|
||||||
|
Indexed(Def),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every function and task the item's body calls, one entry per callee.
|
||||||
|
pub(super) fn outgoing(
|
||||||
|
ws: &Workspace,
|
||||||
|
item: &CallHierarchyItem,
|
||||||
|
data: &Data,
|
||||||
|
) -> Vec<CallHierarchyOutgoingCall> {
|
||||||
|
let Some((doc, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
|
||||||
|
let groups = callees(&doc, symbol);
|
||||||
|
let positions = doc.positions();
|
||||||
|
// Three hundred callees in one closed package are one parse, not three
|
||||||
|
// hundred.
|
||||||
|
let mut loaded = tf::Loaded::new(ws);
|
||||||
|
groups
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(callee, spans)| {
|
||||||
|
let to = match callee {
|
||||||
|
Callee::Local(id) => tf::item(item.uri.clone(), &doc, doc.semantics.symbol(id)?),
|
||||||
|
Callee::Indexed(def) => loaded.item(&def),
|
||||||
|
}?;
|
||||||
|
let from_ranges = spans.into_iter().map(|span| positions.range(span)).collect();
|
||||||
|
Some(CallHierarchyOutgoingCall { to, from_ranges })
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The calls written in `symbol`'s bodies, grouped by what they resolve to.
|
||||||
|
///
|
||||||
|
/// "Bodies", plural: an `extern` prototype and its out-of-body definition are
|
||||||
|
/// two scopes owned by one symbol, and the definition is where the calls are.
|
||||||
|
fn callees(doc: &Analysis, symbol: SymbolId) -> Vec<(Callee, Vec<TextRange>)> {
|
||||||
|
let semantics = &doc.semantics;
|
||||||
|
let bodies: Vec<ScopeId> = semantics
|
||||||
|
.scopes()
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, scope)| scope.owner == Some(symbol))
|
||||||
|
.filter(|(_, scope)| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
|
||||||
|
.map(|(at, _)| ScopeId(at as u32))
|
||||||
|
.collect();
|
||||||
|
let mut groups: Vec<(Callee, Vec<TextRange>)> = Vec::new();
|
||||||
|
for (at, reference) in semantics.references().iter().enumerate() {
|
||||||
|
if !within(semantics, reference.scope, &bodies) || !is_call(doc, reference) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(callee) = callee_of(doc, reference, ReferenceId(at as u32)) else { continue };
|
||||||
|
match groups.iter_mut().find(|(held, _)| *held == callee) {
|
||||||
|
Some((_, spans)) => spans.push(reference.name_span),
|
||||||
|
None => groups.push((callee, vec![reference.name_span])),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groups
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The function or task one use resolves to, or `None` for anything else —
|
||||||
|
/// a variable, an unresolved name, a name two files declare.
|
||||||
|
fn callee_of(doc: &Document, reference: &Reference, id: ReferenceId) -> Option<Callee> {
|
||||||
|
if let Some(local) = reference.resolved() {
|
||||||
|
let symbol = doc.semantics.symbol(local)?;
|
||||||
|
return tf::is_tf(symbol.kind).then_some(Callee::Local(local));
|
||||||
|
}
|
||||||
|
match doc.external.get(id)? {
|
||||||
|
ExternalTarget::Resolved(def) if tf::is_tf(def.kind) => Some(Callee::Indexed(def.clone())),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Every use of `name` in `text`, as `(line, is a call)`.
|
||||||
|
fn classified(text: &str, name: &str) -> Vec<(usize, bool)> {
|
||||||
|
let doc = Document::new(None, text.to_string(), &vlog_semantic::WorkspaceIndex::default());
|
||||||
|
doc.semantics
|
||||||
|
.references()
|
||||||
|
.iter()
|
||||||
|
.filter(|reference| reference.name == name)
|
||||||
|
.map(|r| (text[..r.name_span.start as usize].matches('\n').count(), is_call(&doc, r)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_end_label_a_result_assignment_and_a_redeclaration_are_not_calls() {
|
||||||
|
let text = "\
|
||||||
|
class c;
|
||||||
|
extern function int f(int a);
|
||||||
|
endclass
|
||||||
|
function int c::f(int a);
|
||||||
|
f = a;
|
||||||
|
f += 1;
|
||||||
|
return f(a - 1) + f;
|
||||||
|
endfunction : f
|
||||||
|
";
|
||||||
|
assert_eq!(
|
||||||
|
classified(text, "f"),
|
||||||
|
[(3, false), (4, false), (5, false), (6, true), (6, false)],
|
||||||
|
"the out-of-body name, two result writes, a recursive call, a result read (the \
|
||||||
|
binder records no use for an out-of-body definition's end label)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_result_variable_read_in_its_own_body_is_not_a_call() {
|
||||||
|
// QA finding 1: the classic Verilog-2001 `clog2`.
|
||||||
|
let text = "\
|
||||||
|
module lg;
|
||||||
|
function integer clog2(input integer v);
|
||||||
|
begin
|
||||||
|
clog2 = 0;
|
||||||
|
while (v > 1) begin
|
||||||
|
clog2 = clog2 + 1;
|
||||||
|
v = v >> 1;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
endfunction
|
||||||
|
initial $display(clog2(16));
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
assert_eq!(
|
||||||
|
classified(text, "clog2"),
|
||||||
|
[(3, false), (5, false), (5, false), (10, true)],
|
||||||
|
"written, written, read inside its own body; called from the module"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bare_function_name_in_another_body_is_a_call() {
|
||||||
|
// A function with no arguments may be called without parentheses.
|
||||||
|
let text = "\
|
||||||
|
module m;
|
||||||
|
function int g(); return 1; endfunction
|
||||||
|
function int h(); return g + 1; endfunction
|
||||||
|
function int k(); k = g; endfunction
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
assert_eq!(classified(text, "g"), [(2, true), (3, true)]);
|
||||||
|
assert_eq!(classified(text, "k"), [(3, false)], "`k`'s own result, beside the call");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_end_label_is_not_a_call_but_a_recursive_call_is() {
|
||||||
|
let text =
|
||||||
|
"module m;\n function int f(int a);\n return f(a);\n endfunction : f\nendmodule\n";
|
||||||
|
assert_eq!(classified(text, "f"), [(2, true), (3, false)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_task_enable_without_parentheses_is_a_call() {
|
||||||
|
let text = "module m;\n task t; endtask\n initial t;\nendmodule\n";
|
||||||
|
assert_eq!(classified(text, "t"), [(2, true)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// The two ambiguity fallbacks (QA finding 4)
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Package `p` declared twice, each with `f`; the caller writes `p::f()`.
|
||||||
|
const Z: &str = "package p;\n function int f(); return 1; endfunction\nendpackage\n";
|
||||||
|
const USER: &str = "module user;\n int k = p::f();\nendmodule\n";
|
||||||
|
|
||||||
|
/// A workspace over `root` holding the two `p`s and, if `user` is set,
|
||||||
|
/// a closed `user.sv`; plus `z1.f`'s indexed record and `z1.sv`'s path.
|
||||||
|
fn ambiguous(name: &str, user: bool) -> (std::path::PathBuf, Workspace, Def, PathBuf) {
|
||||||
|
let root =
|
||||||
|
std::env::temp_dir().join(format!("lucisv_server_calls_{}_{name}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
std::fs::create_dir_all(root.join("src")).expect("dir");
|
||||||
|
std::fs::write(root.join("src/z1.sv"), Z).expect("z1");
|
||||||
|
std::fs::write(root.join("src/z2.sv"), Z).expect("z2");
|
||||||
|
if user {
|
||||||
|
std::fs::write(root.join("src/user.sv"), USER).expect("user");
|
||||||
|
}
|
||||||
|
let mut ws = Workspace::default();
|
||||||
|
ws.open_whole_workspace(vec![root.join("src")]);
|
||||||
|
let z1 = root.join("src/z1.sv");
|
||||||
|
let def = ws
|
||||||
|
.index()
|
||||||
|
.member_in("p", "f", vlog_semantic::Surface::Connection)
|
||||||
|
.iter()
|
||||||
|
.find(|def| ws.index().path(def.file) == Some(z1.as_path()))
|
||||||
|
.cloned()
|
||||||
|
.expect("z1's f");
|
||||||
|
(root, ws, def, z1)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_index_that_marks_the_uses_ambiguous_declines() {
|
||||||
|
let (root, ws, def, z1) = ambiguous("index", true);
|
||||||
|
assert!(ws.index().references_are_ambiguous(&def), "premise: user.sv is indexed");
|
||||||
|
assert_eq!(ws.open_documents().count(), 0, "premise: no buffer is open");
|
||||||
|
assert!(declined(&ws, &def, "f", &z1));
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_open_buffer_holding_an_ambiguous_use_declines() {
|
||||||
|
// The buffer lives outside the indexed folder, so only its own
|
||||||
|
// overlay — not the index — knows the use is ambiguous.
|
||||||
|
let (root, mut ws, def, z1) = ambiguous("buffer", false);
|
||||||
|
assert!(!ws.index().references_are_ambiguous(&def), "premise: nothing indexed uses it");
|
||||||
|
assert!(!declined(&ws, &def, "f", &z1), "nothing ambiguous yet");
|
||||||
|
let outside = root.join("user.sv");
|
||||||
|
let uri = path_to_uri(&outside).expect("uri");
|
||||||
|
ws.set_document(uri, USER.to_string());
|
||||||
|
assert!(declined(&ws, &def, "f", &z1));
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_ambiguous_use_in_the_declaring_file_itself_does_not_decline() {
|
||||||
|
let (root, mut ws, def, z1) = ambiguous("declaring", false);
|
||||||
|
ws.set_document(path_to_uri(&z1).expect("uri"), format!("{Z}{USER}"));
|
||||||
|
assert!(!declined(&ws, &def, "f", &z1), "the declaring file answers for itself");
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_call_at_file_scope_has_no_caller() {
|
||||||
|
let text = "function int f(); return 1; endfunction\nlocalparam int P = f();\n";
|
||||||
|
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||||
|
let semantics = vlog_semantic::analyze(&tree, text);
|
||||||
|
let call = semantics.references().iter().find(|r| r.name == "f").expect("the call");
|
||||||
|
assert_eq!(caller_of(&semantics, call.scope), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
//! Function and task items for the call hierarchy: what the cursor names,
|
||||||
|
//! what encloses it, and how an item handed back by the client is found
|
||||||
|
//! again.
|
||||||
|
//!
|
||||||
|
//! A module item carries no `data` and is re-found by name, exactly as it
|
||||||
|
//! always was. A function or task item carries a small [`Data`] object — its
|
||||||
|
//! kind, its name and the byte offset of its name — because two functions of
|
||||||
|
//! one name are ordinary (every module may declare its own `log2`) and the
|
||||||
|
//! name alone cannot tell them apart.
|
||||||
|
//!
|
||||||
|
//! See `docs/features/call-hierarchy-everywhere/README.md`.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use lsp_types::{CallHierarchyItem, SymbolKind, Uri};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use vlog_parser::TextRange;
|
||||||
|
use vlog_semantic::{Def, Definition, ScopeKind, Semantics, Symbol, SymbolId, SymbolKind as Kind};
|
||||||
|
|
||||||
|
use crate::nav::indexed_def_for_symbol;
|
||||||
|
use crate::state::{Document, Workspace};
|
||||||
|
use crate::uri::{path_to_uri, uri_to_path};
|
||||||
|
|
||||||
|
/// What a non-module item carries in `CallHierarchyItem.data`.
|
||||||
|
///
|
||||||
|
/// Serialized as `{"kind": "function"|"task"|"package"|"class", "name": …,
|
||||||
|
/// "offset": …}`, where `offset` is the byte offset of the declared name in
|
||||||
|
/// the item's file when the item was built.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(super) struct Data {
|
||||||
|
pub kind: ItemKind,
|
||||||
|
pub name: String,
|
||||||
|
pub offset: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which declaration a [`Data`] item stands for.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub(super) enum ItemKind {
|
||||||
|
Function,
|
||||||
|
Task,
|
||||||
|
/// A package caller: the body of a package called a function outside any
|
||||||
|
/// function of its own. It has no calls of its own to expand.
|
||||||
|
Package,
|
||||||
|
/// A class caller, for a call written in a class body outside a method.
|
||||||
|
Class,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ItemKind {
|
||||||
|
fn tag(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
ItemKind::Function => "function",
|
||||||
|
ItemKind::Task => "task",
|
||||||
|
ItemKind::Package => "package",
|
||||||
|
ItemKind::Class => "class",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn of_tag(tag: &str) -> Option<ItemKind> {
|
||||||
|
match tag {
|
||||||
|
"function" => Some(ItemKind::Function),
|
||||||
|
"task" => Some(ItemKind::Task),
|
||||||
|
"package" => Some(ItemKind::Package),
|
||||||
|
"class" => Some(ItemKind::Class),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The semantic kind a function or task item re-finds; `None` for the
|
||||||
|
/// container kinds, which are never re-found.
|
||||||
|
fn semantic(self) -> Option<Kind> {
|
||||||
|
match self {
|
||||||
|
ItemKind::Function => Some(Kind::Function),
|
||||||
|
ItemKind::Task => Some(Kind::Task),
|
||||||
|
ItemKind::Package | ItemKind::Class => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Data {
|
||||||
|
/// The JSON object the item carries.
|
||||||
|
fn to_value(&self) -> Value {
|
||||||
|
json!({ "kind": self.kind.tag(), "name": self.name, "offset": self.offset })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The data of an item this server built, or `None` for a module item
|
||||||
|
/// (which carries none) and for anything it does not recognise.
|
||||||
|
pub fn of(item: &CallHierarchyItem) -> Option<Data> {
|
||||||
|
let data = item.data.as_ref()?;
|
||||||
|
let kind = ItemKind::of_tag(data.get("kind")?.as_str()?)?;
|
||||||
|
let name = data.get("name")?.as_str()?.to_string();
|
||||||
|
let offset = u32::try_from(data.get("offset")?.as_u64()?).ok()?;
|
||||||
|
Some(Data { kind, name, offset })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a declaration is something a call hierarchy can stand on as a
|
||||||
|
/// function or task.
|
||||||
|
pub(super) fn is_tf(kind: Kind) -> bool {
|
||||||
|
matches!(kind, Kind::Function | Kind::Task)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One file's analysis: the open buffer's own, or one built from the text on
|
||||||
|
/// disk for a file no editor has open.
|
||||||
|
pub(super) enum Analysis<'a> {
|
||||||
|
Open(&'a Document),
|
||||||
|
Fresh(Box<Document>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for Analysis<'_> {
|
||||||
|
type Target = Document;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Document {
|
||||||
|
match self {
|
||||||
|
Analysis::Open(doc) => doc,
|
||||||
|
Analysis::Fresh(doc) => doc,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The analysis behind an item's URI: the open buffer, else the file on disk.
|
||||||
|
pub(super) fn load<'a>(ws: &'a Workspace, uri: &Uri) -> Option<Analysis<'a>> {
|
||||||
|
match ws.document(uri) {
|
||||||
|
Some(doc) => Some(Analysis::Open(doc)),
|
||||||
|
None => load_path(ws, &uri_to_path(uri)?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The analysis of one path: the open buffer for it, else a fresh analysis
|
||||||
|
/// of the text on disk against the current index.
|
||||||
|
pub(super) fn load_path<'a>(ws: &'a Workspace, path: &Path) -> Option<Analysis<'a>> {
|
||||||
|
if let Some(doc) = ws.document_for_path(path) {
|
||||||
|
return Some(Analysis::Open(doc));
|
||||||
|
}
|
||||||
|
let text = ws.text_of(path)?;
|
||||||
|
Some(Analysis::Fresh(Box::new(Document::new(Some(path.to_path_buf()), text, ws.index()))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The analyses one request has loaded, one per path, so a request that
|
||||||
|
/// builds items in one closed file many times — `outgoingCalls` on a function
|
||||||
|
/// calling three hundred functions of one package — parses it once.
|
||||||
|
///
|
||||||
|
/// Lives for one request and no longer: nothing here may outlast a change to
|
||||||
|
/// the text it was built from.
|
||||||
|
pub(super) struct Loaded<'a> {
|
||||||
|
ws: &'a Workspace,
|
||||||
|
held: HashMap<PathBuf, Option<Analysis<'a>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Loaded<'a> {
|
||||||
|
pub fn new(ws: &'a Workspace) -> Loaded<'a> {
|
||||||
|
Loaded { ws, held: HashMap::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The analysis of `path`, loaded on first ask.
|
||||||
|
pub fn get(&mut self, path: &Path) -> Option<&Analysis<'a>> {
|
||||||
|
let ws = self.ws;
|
||||||
|
self.held.entry(path.to_path_buf()).or_insert_with(|| load_path(ws, path)).as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The function or task the cursor names — its declaration, a call, an end
|
||||||
|
/// label — or, failing that, the one whose body encloses the cursor.
|
||||||
|
///
|
||||||
|
/// A call two files could answer returns both declarations, as
|
||||||
|
/// `textDocument/definition` does; the client asks the user which one.
|
||||||
|
pub(super) fn prepare(
|
||||||
|
ws: &Workspace,
|
||||||
|
doc: &Document,
|
||||||
|
uri: &Uri,
|
||||||
|
offset: u32,
|
||||||
|
) -> Option<Vec<CallHierarchyItem>> {
|
||||||
|
let named = doc
|
||||||
|
.external
|
||||||
|
.definition_of(&doc.semantics, offset)
|
||||||
|
.or_else(|| doc.external.definition_of(&doc.semantics, offset.checked_sub(1)?));
|
||||||
|
let items: Vec<CallHierarchyItem> = match named {
|
||||||
|
Some(Definition::Local(symbol)) if is_tf(symbol.kind) => {
|
||||||
|
item(uri.clone(), doc, symbol).into_iter().collect()
|
||||||
|
}
|
||||||
|
Some(Definition::External(defs)) => {
|
||||||
|
let mut loaded = Loaded::new(ws);
|
||||||
|
defs.iter().filter(|def| is_tf(def.kind)).filter_map(|def| loaded.item(def)).collect()
|
||||||
|
}
|
||||||
|
_ => Vec::new(),
|
||||||
|
};
|
||||||
|
if !items.is_empty() {
|
||||||
|
return Some(items);
|
||||||
|
}
|
||||||
|
let symbol = enclosing(&doc.semantics, offset)?;
|
||||||
|
Some(vec![item(uri.clone(), doc, doc.semantics.symbol(symbol)?)?])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The function or task whose body holds `offset`, innermost first.
|
||||||
|
///
|
||||||
|
/// An out-of-body method definition (`function void c::f(); … endfunction`)
|
||||||
|
/// is a scope owned by the prototype's symbol, so its body answers the
|
||||||
|
/// prototype.
|
||||||
|
fn enclosing(semantics: &Semantics, offset: u32) -> Option<SymbolId> {
|
||||||
|
semantics
|
||||||
|
.scopes()
|
||||||
|
.iter()
|
||||||
|
.filter(|scope| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
|
||||||
|
.filter(|scope| holds(scope.span, offset))
|
||||||
|
.filter(|scope| {
|
||||||
|
scope.owner.and_then(|id| semantics.symbol(id)).is_some_and(|s| is_tf(s.kind))
|
||||||
|
})
|
||||||
|
.min_by_key(|scope| scope.span.end - scope.span.start)
|
||||||
|
.and_then(|scope| scope.owner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The item for a function or task declared in `doc`, reported against `uri`.
|
||||||
|
pub(super) fn item(uri: Uri, doc: &Document, symbol: &Symbol) -> Option<CallHierarchyItem> {
|
||||||
|
let kind = if symbol.kind == Kind::Task { ItemKind::Task } else { ItemKind::Function };
|
||||||
|
let in_class = scope_kind(&doc.semantics, symbol) == Some(ScopeKind::Class);
|
||||||
|
let lsp_kind = if in_class { SymbolKind::METHOD } else { SymbolKind::FUNCTION };
|
||||||
|
built(uri, doc, symbol, kind, lsp_kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The item for a package or class that is a caller.
|
||||||
|
pub(super) fn container_item(
|
||||||
|
uri: Uri,
|
||||||
|
doc: &Document,
|
||||||
|
symbol: &Symbol,
|
||||||
|
) -> Option<CallHierarchyItem> {
|
||||||
|
match symbol.kind {
|
||||||
|
Kind::Package => built(uri, doc, symbol, ItemKind::Package, SymbolKind::PACKAGE),
|
||||||
|
Kind::Class => built(uri, doc, symbol, ItemKind::Class, SymbolKind::CLASS),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An item with [`Data`], framed against `doc`'s text.
|
||||||
|
fn built(
|
||||||
|
uri: Uri,
|
||||||
|
doc: &Document,
|
||||||
|
symbol: &Symbol,
|
||||||
|
kind: ItemKind,
|
||||||
|
lsp_kind: SymbolKind,
|
||||||
|
) -> Option<CallHierarchyItem> {
|
||||||
|
let mut item =
|
||||||
|
super::item_of(uri, &doc.positions(), &symbol.name, symbol.name_span, symbol.decl_span)?;
|
||||||
|
item.kind = lsp_kind;
|
||||||
|
item.detail = container_name(&doc.semantics, symbol);
|
||||||
|
let data = Data { kind, name: symbol.name.clone(), offset: symbol.name_span.start };
|
||||||
|
item.data = Some(data.to_value());
|
||||||
|
Some(item)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kind of the scope a declaration is bound in.
|
||||||
|
fn scope_kind(semantics: &Semantics, symbol: &Symbol) -> Option<ScopeKind> {
|
||||||
|
semantics.scope(symbol.scope).map(|scope| scope.kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name of the module, package or class a function is declared in —
|
||||||
|
/// shown beside the name, so two `log2`s in one list can be told apart.
|
||||||
|
fn container_name(semantics: &Semantics, symbol: &Symbol) -> Option<String> {
|
||||||
|
let owner = semantics.scope(symbol.scope)?.owner?;
|
||||||
|
Some(semantics.symbol(owner)?.name.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Loaded<'_> {
|
||||||
|
/// The item for a function or task another file declares, re-found in
|
||||||
|
/// that file's live analysis so its ranges are the text's as it is now.
|
||||||
|
pub fn item(&mut self, def: &Def) -> Option<CallHierarchyItem> {
|
||||||
|
let ws = self.ws;
|
||||||
|
let path = ws.index().path(def.file)?;
|
||||||
|
let uri = path_to_uri(path)?;
|
||||||
|
let doc = self.get(path)?;
|
||||||
|
let symbol = live_symbol(ws, doc, def)?;
|
||||||
|
item(uri, doc, doc.semantics.symbol(symbol)?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The symbol in `doc` that is the indexed declaration `def`: by identity —
|
||||||
|
/// asked first of the symbol still at the recorded position, which is the
|
||||||
|
/// answer unless the file moved — and by position as a last resort.
|
||||||
|
fn live_symbol(ws: &Workspace, doc: &Document, def: &Def) -> Option<SymbolId> {
|
||||||
|
let candidates: Vec<SymbolId> = doc
|
||||||
|
.semantics
|
||||||
|
.symbols()
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, symbol)| symbol.kind == def.kind)
|
||||||
|
.map(|(at, _)| SymbolId(at as u32))
|
||||||
|
.collect();
|
||||||
|
let symbol = |id: &SymbolId| doc.semantics.symbol(*id);
|
||||||
|
let is_def =
|
||||||
|
|id: &&SymbolId| symbol(id).and_then(|s| indexed_def_for_symbol(ws, doc, s)) == Some(def);
|
||||||
|
let at_position = |id: &&SymbolId| symbol(id).is_some_and(|s| s.name_span == def.name_span);
|
||||||
|
let positioned = candidates.iter().find(at_position);
|
||||||
|
positioned.filter(is_def).or_else(|| candidates.iter().find(is_def)).or(positioned).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The declaration a function or task item stands for, in its file's live
|
||||||
|
/// analysis.
|
||||||
|
///
|
||||||
|
/// The recorded offset wins; an edit since the item was built moves it, and
|
||||||
|
/// then the item's own selection range is tried. Failing both, the name
|
||||||
|
/// decides only when it is unambiguous: the one declaration of that name and
|
||||||
|
/// kind whose container is the item's `detail`.
|
||||||
|
/// Otherwise nothing — two `log2`s in two modules are ordinary, and answering
|
||||||
|
/// for the wrong one would be a confident wrong hierarchy.
|
||||||
|
pub(super) fn target<'a>(
|
||||||
|
ws: &'a Workspace,
|
||||||
|
item: &CallHierarchyItem,
|
||||||
|
data: &Data,
|
||||||
|
) -> Option<(Analysis<'a>, SymbolId)> {
|
||||||
|
let kind = data.kind.semantic()?;
|
||||||
|
let doc = load(ws, &item.uri)?;
|
||||||
|
let candidates: Vec<SymbolId> = doc
|
||||||
|
.semantics
|
||||||
|
.symbols_named(&data.name)
|
||||||
|
.filter(|id| doc.semantics.symbol(*id).is_some_and(|s| s.kind == kind))
|
||||||
|
.collect();
|
||||||
|
let starts_at = |offset: u32| {
|
||||||
|
candidates
|
||||||
|
.iter()
|
||||||
|
.find(|id| doc.semantics.symbol(**id).is_some_and(|s| s.name_span.start == offset))
|
||||||
|
.copied()
|
||||||
|
};
|
||||||
|
let selected = doc.positions().offset(item.selection_range.start);
|
||||||
|
let found = starts_at(data.offset)
|
||||||
|
.or_else(|| starts_at(selected))
|
||||||
|
.or_else(|| by_name(&doc.semantics, &candidates, item.detail.as_deref()))?;
|
||||||
|
Some((doc, found))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one candidate a name alone can stand for: the only one declared in
|
||||||
|
/// the container the item's `detail` names (no container for `$unit`).
|
||||||
|
///
|
||||||
|
/// The container is asked even of a lone candidate: when `mb`'s `log2` has
|
||||||
|
/// been renamed away, `ma`'s is the only `log2` left, and it is still not the
|
||||||
|
/// function the item stood for.
|
||||||
|
fn by_name(
|
||||||
|
semantics: &Semantics,
|
||||||
|
candidates: &[SymbolId],
|
||||||
|
detail: Option<&str>,
|
||||||
|
) -> Option<SymbolId> {
|
||||||
|
let mut inside = candidates.iter().filter(|id| {
|
||||||
|
semantics.symbol(**id).is_some_and(|s| container_name(semantics, s).as_deref() == detail)
|
||||||
|
});
|
||||||
|
match (inside.next(), inside.next()) {
|
||||||
|
(Some(one), None) => Some(*one),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `span` holds `offset`, its end included.
|
||||||
|
pub(super) fn holds(span: TextRange, offset: u32) -> bool {
|
||||||
|
span.start <= offset && offset <= span.end
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use lsp_types::{Position, Range};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn bare(data: Option<Value>) -> CallHierarchyItem {
|
||||||
|
let range = Range::new(Position::new(0, 0), Position::new(0, 1));
|
||||||
|
CallHierarchyItem {
|
||||||
|
name: "f".to_string(),
|
||||||
|
kind: SymbolKind::FUNCTION,
|
||||||
|
tags: None,
|
||||||
|
detail: None,
|
||||||
|
uri: Uri::from_str("file:///x.sv").expect("uri"),
|
||||||
|
range,
|
||||||
|
selection_range: range,
|
||||||
|
data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn data_round_trips_through_its_json() {
|
||||||
|
for kind in [ItemKind::Function, ItemKind::Task, ItemKind::Package, ItemKind::Class] {
|
||||||
|
let data = Data { kind, name: "f".to_string(), offset: 42 };
|
||||||
|
assert_eq!(Data::of(&bare(Some(data.to_value()))), Some(data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_module_item_and_foreign_data_carry_no_data_of_ours() {
|
||||||
|
assert_eq!(Data::of(&bare(None)), None, "a module item");
|
||||||
|
for foreign in [
|
||||||
|
json!({ "kind": "rocket", "name": "f", "offset": 1 }),
|
||||||
|
json!({ "kind": "function", "name": "f" }),
|
||||||
|
json!({ "kind": "function", "name": 7, "offset": 1 }),
|
||||||
|
json!({ "kind": "function", "name": "f", "offset": -1 }),
|
||||||
|
json!({ "kind": "function", "name": "f", "offset": 5_000_000_000u64 }),
|
||||||
|
json!("function"),
|
||||||
|
] {
|
||||||
|
assert_eq!(Data::of(&bare(Some(foreign.clone()))), None, "{foreign}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_innermost_function_or_task_encloses_an_offset() {
|
||||||
|
let text = "module m;\n task t;\n begin\n x = 1;\n end\n endtask\n \
|
||||||
|
wire w;\nendmodule\n";
|
||||||
|
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||||
|
let semantics = vlog_semantic::analyze(&tree, text);
|
||||||
|
let name = |offset| {
|
||||||
|
enclosing(&semantics, offset)
|
||||||
|
.and_then(|id| semantics.symbol(id))
|
||||||
|
.map(|s| s.name.clone())
|
||||||
|
};
|
||||||
|
let at = |needle: &str| text.find(needle).expect("needle") as u32;
|
||||||
|
assert_eq!(name(at("x = 1")).as_deref(), Some("t"), "through a nested block");
|
||||||
|
assert_eq!(name(at("endtask") + 7).as_deref(), Some("t"), "the end included");
|
||||||
|
assert_eq!(name(at("wire")), None, "a module item is in no task");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,691 @@
|
|||||||
|
//! Call hierarchy from wherever the cursor is, and for functions and tasks
|
||||||
|
//! (`docs/features/call-hierarchy-everywhere/README.md`), driven through the
|
||||||
|
//! real dispatch.
|
||||||
|
//!
|
||||||
|
//! The fixture is a small design: a package of functions (one recursive), a
|
||||||
|
//! module that imports it and calls through a function, a task and an
|
||||||
|
//! `always` block, a top that instantiates that module and calls the package
|
||||||
|
//! with a scoped name, and a class whose methods call each other through
|
||||||
|
//! `this.` and through a handle.
|
||||||
|
|
||||||
|
use lsp_types::request::{CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls};
|
||||||
|
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const PKG: &str = "\
|
||||||
|
package util_pkg;
|
||||||
|
function automatic int add1(int a);
|
||||||
|
return a + 1;
|
||||||
|
endfunction : add1
|
||||||
|
|
||||||
|
function automatic int fact(int n);
|
||||||
|
if (n <= 1) return 1;
|
||||||
|
return n * fact(n - 1);
|
||||||
|
endfunction
|
||||||
|
endpackage
|
||||||
|
";
|
||||||
|
|
||||||
|
const CORE: &str = "\
|
||||||
|
module core (input logic clk, output int q);
|
||||||
|
import util_pkg::*;
|
||||||
|
int r;
|
||||||
|
|
||||||
|
function automatic int twice(int a);
|
||||||
|
twice = add1(a) + add1(a);
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
task automatic kick(input int v);
|
||||||
|
r = twice(v);
|
||||||
|
$display(\"%0d\", v);
|
||||||
|
endtask
|
||||||
|
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
q <= twice(r);
|
||||||
|
end
|
||||||
|
|
||||||
|
initial kick(3);
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
const TOP: &str = "\
|
||||||
|
// the top of the design
|
||||||
|
module top;
|
||||||
|
logic clk;
|
||||||
|
int q;
|
||||||
|
core u_core (.clk(clk), .q(q));
|
||||||
|
int z = util_pkg::add1(2);
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
const CLS: &str = "\
|
||||||
|
class counter;
|
||||||
|
int n;
|
||||||
|
extern function void reset();
|
||||||
|
function void bump();
|
||||||
|
n++;
|
||||||
|
endfunction
|
||||||
|
function void bump_twice();
|
||||||
|
bump();
|
||||||
|
this.bump();
|
||||||
|
endfunction
|
||||||
|
task run();
|
||||||
|
counter h;
|
||||||
|
h = new;
|
||||||
|
h.bump();
|
||||||
|
endtask
|
||||||
|
endclass
|
||||||
|
|
||||||
|
class fancy extends counter;
|
||||||
|
function void bump_more();
|
||||||
|
super.bump();
|
||||||
|
endfunction
|
||||||
|
endclass
|
||||||
|
|
||||||
|
function void counter::reset();
|
||||||
|
bump();
|
||||||
|
endfunction
|
||||||
|
";
|
||||||
|
|
||||||
|
/// The design on disk, a wide session over it, `core.sv` open.
|
||||||
|
fn design(name: &str) -> (Tree, Session, Uri) {
|
||||||
|
let tree = Tree::new(name);
|
||||||
|
tree.write("util_pkg.sv", PKG);
|
||||||
|
tree.write("core.sv", CORE);
|
||||||
|
tree.write("top.sv", TOP);
|
||||||
|
tree.write("cls.sv", CLS);
|
||||||
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||||
|
let uri = session.open(&tree.path.join("core.sv"), CORE);
|
||||||
|
session.drain();
|
||||||
|
(tree, session, uri)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The LSP position of the `nth` occurrence of `needle` in `text`, `skip`
|
||||||
|
/// bytes in.
|
||||||
|
fn pos(text: &str, needle: &str, nth: usize, skip: usize) -> Value {
|
||||||
|
let mut at = text.find(needle).expect("needle");
|
||||||
|
for _ in 0..nth {
|
||||||
|
at = text[at + 1..].find(needle).expect("nth needle") + at + 1;
|
||||||
|
}
|
||||||
|
let at = at + skip;
|
||||||
|
let line = text[..at].matches('\n').count();
|
||||||
|
let character = at - text[..at].rfind('\n').map_or(0, |nl| nl + 1);
|
||||||
|
serde_json::json!({ "line": line, "character": character })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `prepareCallHierarchy` at a position: `None` for a `null` answer.
|
||||||
|
fn prepare(session: &mut Session, uri: &Uri, position: Value) -> Option<Vec<CallHierarchyItem>> {
|
||||||
|
let result = session.result(
|
||||||
|
CallHierarchyPrepare::METHOD,
|
||||||
|
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
|
||||||
|
);
|
||||||
|
serde_json::from_value(result).expect("items or null")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one item prepared at a position.
|
||||||
|
fn one(session: &mut Session, uri: &Uri, position: Value) -> CallHierarchyItem {
|
||||||
|
let items = prepare(session, uri, position).expect("an item");
|
||||||
|
assert_eq!(items.len(), 1, "{items:#?}");
|
||||||
|
items.into_iter().next().expect("one")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn incoming(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
||||||
|
let result =
|
||||||
|
session.result(CallHierarchyIncomingCalls::METHOD, serde_json::json!({ "item": item }));
|
||||||
|
serde_json::from_value(result).expect("incoming calls")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outgoing(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
|
||||||
|
let result =
|
||||||
|
session.result(CallHierarchyOutgoingCalls::METHOD, serde_json::json!({ "item": item }));
|
||||||
|
serde_json::from_value(result).expect("outgoing calls")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An item as `(name, file name, selection line)`.
|
||||||
|
fn shape(item: &CallHierarchyItem) -> (String, String, u32) {
|
||||||
|
let file = item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string();
|
||||||
|
(item.name.clone(), file, item.selection_range.start.line)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each incoming call as `(caller name, caller file, lines of its ranges)`.
|
||||||
|
fn callers(calls: &[CallHierarchyIncomingCall]) -> Vec<(String, String, Vec<u32>)> {
|
||||||
|
calls
|
||||||
|
.iter()
|
||||||
|
.map(|call| {
|
||||||
|
let (name, file, _) = shape(&call.from);
|
||||||
|
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each outgoing call as `(callee name, callee file, lines of its ranges)`.
|
||||||
|
fn callees(calls: &[CallHierarchyOutgoingCall]) -> Vec<(String, String, Vec<u32>)> {
|
||||||
|
calls
|
||||||
|
.iter()
|
||||||
|
.map(|call| {
|
||||||
|
let (name, file, _) = shape(&call.to);
|
||||||
|
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn s(text: &str) -> String {
|
||||||
|
text.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// prepare, every position
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_instance_name_prepares_the_instantiated_module() {
|
||||||
|
let (tree, mut session, _) = design("hev_instance");
|
||||||
|
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||||
|
let item = one(&mut session, &top, pos(TOP, "u_core", 0, 2));
|
||||||
|
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0));
|
||||||
|
assert_eq!(item.kind, lsp_types::SymbolKind::MODULE);
|
||||||
|
assert!(item.data.is_none(), "a module item is the M11 item, unchanged");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_function_declaration_a_call_and_its_end_label_prepare_the_function() {
|
||||||
|
let (tree, mut session, core) = design("hev_function");
|
||||||
|
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
|
||||||
|
let declared = one(&mut session, &pkg, pos(PKG, "add1(int", 0, 1));
|
||||||
|
let labelled = one(&mut session, &pkg, pos(PKG, ": add1", 0, 3));
|
||||||
|
let called = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
|
||||||
|
for item in [&declared, &labelled, &called] {
|
||||||
|
assert_eq!(shape(item), (s("add1"), s("util_pkg.sv"), 1));
|
||||||
|
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
|
||||||
|
assert_eq!(item.detail.as_deref(), Some("util_pkg"));
|
||||||
|
let data = item.data.as_ref().expect("data");
|
||||||
|
assert_eq!(data["kind"], "function");
|
||||||
|
assert_eq!(data["name"], "add1");
|
||||||
|
assert!(data["offset"].is_u64(), "{data}");
|
||||||
|
}
|
||||||
|
assert_eq!(declared, called, "one item, wherever it was prepared from");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cursor_just_past_a_call_name_prepares_the_function() {
|
||||||
|
let (_tree, mut session, core) = design("hev_caret");
|
||||||
|
let item = one(&mut session, &core, pos(CORE, "twice(v)", 0, 5));
|
||||||
|
assert_eq!(shape(&item), (s("twice"), s("core.sv"), 4));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_task_declaration_and_a_call_prepare_the_task() {
|
||||||
|
let (_tree, mut session, core) = design("hev_task");
|
||||||
|
for position in [pos(CORE, "kick(input", 0, 0), pos(CORE, "kick(3)", 0, 1)] {
|
||||||
|
let item = one(&mut session, &core, position);
|
||||||
|
assert_eq!(shape(&item), (s("kick"), s("core.sv"), 8));
|
||||||
|
assert_eq!(item.data.as_ref().expect("data")["kind"], "task");
|
||||||
|
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inside_a_function_or_task_body_prepares_it() {
|
||||||
|
let (_tree, mut session, core) = design("hev_body");
|
||||||
|
let in_task = one(&mut session, &core, pos(CORE, "$display", 0, 2));
|
||||||
|
assert_eq!(shape(&in_task), (s("kick"), s("core.sv"), 8), "a system task names no item");
|
||||||
|
let on_arg = one(&mut session, &core, pos(CORE, "v);", 0, 0));
|
||||||
|
assert_eq!(shape(&on_arg).0, "kick", "a use of an argument");
|
||||||
|
let on_keyword = one(&mut session, &core, pos(CORE, "endfunction", 0, 3));
|
||||||
|
assert_eq!(shape(&on_keyword).0, "twice", "the closing keyword");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inside_a_module_body_prepares_the_module() {
|
||||||
|
let (_tree, mut session, core) = design("hev_module");
|
||||||
|
for (what, position) in [
|
||||||
|
("a net declaration", pos(CORE, "int r", 0, 4)),
|
||||||
|
("inside an always block", pos(CORE, "q <=", 0, 0)),
|
||||||
|
("an import", pos(CORE, "import", 0, 2)),
|
||||||
|
] {
|
||||||
|
let item = one(&mut session, &core, position);
|
||||||
|
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0), "{what}");
|
||||||
|
assert!(item.data.is_none(), "{what}: the module item, as M11 builds it");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn where_nothing_encloses_the_cursor_prepare_is_null() {
|
||||||
|
let (tree, mut session, _) = design("hev_null");
|
||||||
|
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||||
|
assert!(prepare(&mut session, &top, pos(TOP, "the top", 0, 0)).is_none(), "a file comment");
|
||||||
|
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
|
||||||
|
assert!(
|
||||||
|
prepare(&mut session, &pkg, pos(PKG, "\n\n", 0, 1)).is_none(),
|
||||||
|
"a package body outside its functions"
|
||||||
|
);
|
||||||
|
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||||
|
assert!(
|
||||||
|
prepare(&mut session, &cls, pos(CLS, "int n", 0, 4)).is_none(),
|
||||||
|
"a class property: the call hierarchy has no class node to open"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn existing_module_answers_are_unchanged() {
|
||||||
|
let (tree, mut session, core) = design("hev_unchanged");
|
||||||
|
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||||
|
let declared = one(&mut session, &core, pos(CORE, "module core", 0, 7));
|
||||||
|
let instantiated = one(&mut session, &top, pos(TOP, "core u_core", 0, 1));
|
||||||
|
assert_eq!(declared, instantiated);
|
||||||
|
assert!(declared.data.is_none());
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &declared)), [(s("top"), s("top.sv"), vec![4])]);
|
||||||
|
assert!(outgoing(&mut session, &declared).is_empty(), "a module lists no function calls");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// incoming and outgoing for functions and tasks
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_function_called_from_a_task_and_an_always_block() {
|
||||||
|
let (_tree, mut session, core) = design("hev_twice");
|
||||||
|
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||||
|
let calls = incoming(&mut session, &twice);
|
||||||
|
assert_eq!(
|
||||||
|
callers(&calls),
|
||||||
|
[(s("core"), s("core.sv"), vec![14]), (s("kick"), s("core.sv"), vec![9])],
|
||||||
|
"the task and the module of the always block; not `twice = …`, which is a result"
|
||||||
|
);
|
||||||
|
assert_eq!(calls[0].from.kind, lsp_types::SymbolKind::MODULE);
|
||||||
|
assert!(calls[0].from.data.is_none(), "a module caller is the M11 item");
|
||||||
|
assert_eq!(calls[1].from.data.as_ref().expect("data")["kind"], "task");
|
||||||
|
let from = calls[1].from_ranges[0];
|
||||||
|
assert_eq!((from.start.character, from.end.character), (8, 13), "the call's name");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_task_called_from_an_initial_block_and_its_outgoing_calls() {
|
||||||
|
let (_tree, mut session, core) = design("hev_kick");
|
||||||
|
let kick = one(&mut session, &core, pos(CORE, "kick(input", 0, 0));
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &kick)), [(s("core"), s("core.sv"), vec![17])]);
|
||||||
|
assert_eq!(
|
||||||
|
callees(&outgoing(&mut session, &kick)),
|
||||||
|
[(s("twice"), s("core.sv"), vec![9])],
|
||||||
|
"`$display` is a system task and is skipped"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outgoing_calls_resolve_into_another_file_grouped_by_callee() {
|
||||||
|
let (_tree, mut session, core) = design("hev_out");
|
||||||
|
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||||
|
let calls = outgoing(&mut session, &twice);
|
||||||
|
assert_eq!(callees(&calls), [(s("add1"), s("util_pkg.sv"), vec![5, 5])]);
|
||||||
|
assert_eq!(calls[0].to.data.as_ref().expect("data")["kind"], "function");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_package_function_is_called_from_modules_in_other_files() {
|
||||||
|
// `util_pkg.sv` and `top.sv` are closed: the item is prepared from the
|
||||||
|
// call in `core.sv`, and the callers are found the way references are.
|
||||||
|
let (_tree, mut session, core) = design("hev_cross");
|
||||||
|
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
|
||||||
|
let calls = incoming(&mut session, &add1);
|
||||||
|
assert_eq!(
|
||||||
|
callers(&calls),
|
||||||
|
[(s("twice"), s("core.sv"), vec![5, 5]), (s("top"), s("top.sv"), vec![5])],
|
||||||
|
"a function caller in an open file, a module caller in a closed one; the end label is no call"
|
||||||
|
);
|
||||||
|
let top = &calls[1].from;
|
||||||
|
let instantiated = outgoing(&mut session, top);
|
||||||
|
assert_eq!(
|
||||||
|
callees(&instantiated),
|
||||||
|
[(s("core"), s("core.sv"), vec![4])],
|
||||||
|
"expanding a module caller walks the design, one level down"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_cross_file_answer_matches_references() {
|
||||||
|
let (_tree, mut session, core) = design("hev_refs");
|
||||||
|
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
|
||||||
|
let mut from_calls: Vec<(String, u32, u32)> = incoming(&mut session, &add1)
|
||||||
|
.iter()
|
||||||
|
.flat_map(|call| {
|
||||||
|
let file = shape(&call.from).1;
|
||||||
|
call.from_ranges.iter().map(move |r| (file.clone(), r.start.line, r.start.character))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let references = session.result(
|
||||||
|
References::METHOD,
|
||||||
|
serde_json::json!({
|
||||||
|
"textDocument": { "uri": core },
|
||||||
|
"position": pos(CORE, "add1(a)", 0, 0),
|
||||||
|
"context": { "includeDeclaration": false },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let mut from_refs: Vec<(String, u32, u32)> = references
|
||||||
|
.as_array()
|
||||||
|
.expect("locations")
|
||||||
|
.iter()
|
||||||
|
.map(|loc| {
|
||||||
|
let file =
|
||||||
|
loc["uri"].as_str().unwrap_or("").rsplit('/').next().unwrap_or("").to_string();
|
||||||
|
let start = &loc["range"]["start"];
|
||||||
|
(
|
||||||
|
file,
|
||||||
|
start["line"].as_u64().unwrap_or(0) as u32,
|
||||||
|
start["character"].as_u64().unwrap_or(0) as u32,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.filter(|(file, line, _)| !(file == "util_pkg.sv" && *line == 3))
|
||||||
|
.collect();
|
||||||
|
from_calls.sort();
|
||||||
|
from_refs.sort();
|
||||||
|
assert_eq!(from_calls, from_refs, "every reference but the end label is a call");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_recursive_function_is_its_own_caller_and_callee() {
|
||||||
|
let (tree, mut session, _) = design("hev_fact");
|
||||||
|
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
|
||||||
|
let fact = one(&mut session, &pkg, pos(PKG, "fact(int", 0, 0));
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
|
||||||
|
assert_eq!(callees(&outgoing(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn class_methods_called_through_this_a_handle_and_super() {
|
||||||
|
let (tree, mut session, _) = design("hev_class");
|
||||||
|
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||||
|
let bump = one(&mut session, &cls, pos(CLS, "bump();\n n++", 0, 0));
|
||||||
|
assert_eq!(bump.kind, lsp_types::SymbolKind::METHOD);
|
||||||
|
assert_eq!(bump.detail.as_deref(), Some("counter"));
|
||||||
|
assert_eq!(
|
||||||
|
callers(&incoming(&mut session, &bump)),
|
||||||
|
[
|
||||||
|
(s("reset"), s("cls.sv"), vec![24]),
|
||||||
|
(s("bump_twice"), s("cls.sv"), vec![7, 8]),
|
||||||
|
(s("run"), s("cls.sv"), vec![13]),
|
||||||
|
(s("bump_more"), s("cls.sv"), vec![19]),
|
||||||
|
],
|
||||||
|
"a bare call and `this.`; a handle; the out-of-body definition's body, \
|
||||||
|
credited to its prototype; `super.` from a subclass"
|
||||||
|
);
|
||||||
|
let twice = one(&mut session, &cls, pos(CLS, "bump_twice", 0, 0));
|
||||||
|
assert_eq!(callees(&outgoing(&mut session, &twice)), [(s("bump"), s("cls.sv"), vec![7, 8])]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_out_of_body_definition_prepares_and_expands_its_prototype() {
|
||||||
|
let (tree, mut session, _) = design("hev_extern");
|
||||||
|
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||||
|
let inside = one(&mut session, &cls, pos(CLS, "bump();\nendfunction", 0, 0));
|
||||||
|
assert_eq!(shape(&inside).0, "bump", "on the call");
|
||||||
|
let body = one(&mut session, &cls, pos(CLS, "endfunction\n", 3, 3));
|
||||||
|
assert_eq!(shape(&body), (s("reset"), s("cls.sv"), 2), "the prototype");
|
||||||
|
assert_eq!(callees(&outgoing(&mut session, &body)), [(s("bump"), s("cls.sv"), vec![24])]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_super_method_call_resolves_through_the_workspace_overlay() {
|
||||||
|
// `super.bump()` inside `fancy` is answered by the workspace overlay
|
||||||
|
// (the base class is a file-scope declaration the index holds), not by
|
||||||
|
// the file's own symbol table — both directions must read both layers.
|
||||||
|
let (tree, mut session, _) = design("hev_super");
|
||||||
|
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||||
|
let more = one(&mut session, &cls, pos(CLS, "bump_more", 0, 0));
|
||||||
|
assert_eq!(callees(&outgoing(&mut session, &more)), [(s("bump"), s("cls.sv"), vec![19])]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_method_called_through_a_handle_from_another_file() {
|
||||||
|
let pkg = "\
|
||||||
|
package env_pkg;
|
||||||
|
class driver;
|
||||||
|
task drive();
|
||||||
|
endtask
|
||||||
|
endclass
|
||||||
|
endpackage
|
||||||
|
";
|
||||||
|
let tb = "\
|
||||||
|
module tb;
|
||||||
|
import env_pkg::*;
|
||||||
|
driver d;
|
||||||
|
initial begin
|
||||||
|
d = new;
|
||||||
|
d.drive();
|
||||||
|
end
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let tree = Tree::new("hev_handle");
|
||||||
|
tree.write("env_pkg.sv", pkg);
|
||||||
|
tree.write("tb.sv", tb);
|
||||||
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||||
|
let uri = session.open(&tree.path.join("env_pkg.sv"), pkg);
|
||||||
|
session.drain();
|
||||||
|
let drive = one(&mut session, &uri, pos(pkg, "drive()", 0, 0));
|
||||||
|
assert_eq!(drive.kind, lsp_types::SymbolKind::METHOD);
|
||||||
|
assert_eq!(drive.detail.as_deref(), Some("driver"));
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &drive)), [(s("tb"), s("tb.sv"), vec![5])]);
|
||||||
|
let tb_uri = session.open(&tree.path.join("tb.sv"), tb);
|
||||||
|
let from_call = one(&mut session, &tb_uri, pos(tb, "drive()", 0, 1));
|
||||||
|
assert_eq!(from_call, drive, "the call through the handle prepares the method");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_unit_scope_function_answers_in_its_own_file_only() {
|
||||||
|
// A `$unit` function works like any other in the file that declares it.
|
||||||
|
// A call from *another* file is a documented limit: the semantic layer
|
||||||
|
// resolves an unqualified value-position name through imports only, so
|
||||||
|
// `ufn(1)` in `user.sv` names nothing and the cursor there falls back to
|
||||||
|
// the enclosing module (README, Handshakes).
|
||||||
|
let unit = "\
|
||||||
|
function automatic int ufn(int a);
|
||||||
|
return a;
|
||||||
|
endfunction
|
||||||
|
module local_user;
|
||||||
|
int j = ufn(2);
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let user = "module user;\n int k = ufn(1);\nendmodule\n";
|
||||||
|
let tree = Tree::new("hev_unit");
|
||||||
|
tree.write("unit.sv", unit);
|
||||||
|
tree.write("user.sv", user);
|
||||||
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||||
|
let uri = session.open(&tree.path.join("unit.sv"), unit);
|
||||||
|
session.drain();
|
||||||
|
let ufn = one(&mut session, &uri, pos(unit, "ufn", 0, 0));
|
||||||
|
assert_eq!(shape(&ufn), (s("ufn"), s("unit.sv"), 0));
|
||||||
|
assert_eq!(ufn.detail, None, "declared at `$unit`, in no container");
|
||||||
|
assert_eq!(one(&mut session, &uri, pos(unit, "ufn(2)", 0, 0)), ufn);
|
||||||
|
assert_eq!(
|
||||||
|
callers(&incoming(&mut session, &ufn)),
|
||||||
|
[(s("local_user"), s("unit.sv"), vec![4])],
|
||||||
|
"the call in `user.sv` is not resolved, so it is not listed"
|
||||||
|
);
|
||||||
|
let user_uri = session.open(&tree.path.join("user.sv"), user);
|
||||||
|
let there = one(&mut session, &user_uri, pos(user, "ufn", 0, 0));
|
||||||
|
assert_eq!(shape(&there).0, "user", "the limit: the enclosing module, not `ufn`");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_edit_since_the_item_was_built_is_followed() {
|
||||||
|
// The item's recorded offset no longer matches once a line is added
|
||||||
|
// above the function; the selection range is stale too, so the item is
|
||||||
|
// re-found by name — `twice` is the only one, in its container `core`.
|
||||||
|
let (tree, mut session, core) = design("hev_stale");
|
||||||
|
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||||
|
let edited = format!("// a new first line\n{CORE}");
|
||||||
|
session.open(&tree.path.join("core.sv"), &edited);
|
||||||
|
let calls = incoming(&mut session, &twice);
|
||||||
|
assert_eq!(
|
||||||
|
callers(&calls),
|
||||||
|
[(s("core"), s("core.sv"), vec![15]), (s("kick"), s("core.sv"), vec![10])]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QA finding 3: two `log2`s in one file. After an edit moves both, the old
|
||||||
|
/// item for `mb`'s answers `mb`'s callers (its `detail` breaks the tie); once
|
||||||
|
/// `mb`'s is renamed away it answers nothing — never `ma`'s.
|
||||||
|
#[test]
|
||||||
|
fn a_stale_item_never_answers_for_a_same_named_function_elsewhere() {
|
||||||
|
let text = "\
|
||||||
|
module ma;
|
||||||
|
function int log2(int v); return v; endfunction
|
||||||
|
int a = log2(1);
|
||||||
|
endmodule
|
||||||
|
module mb;
|
||||||
|
function int log2(int v); return v; endfunction
|
||||||
|
int b = log2(2);
|
||||||
|
int c = log2(3);
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let tree = Tree::new("hev_ma_mb");
|
||||||
|
tree.write("two.sv", text);
|
||||||
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||||
|
let path = tree.path.join("two.sv");
|
||||||
|
let uri = session.open(&path, text);
|
||||||
|
session.drain();
|
||||||
|
let in_mb = one(&mut session, &uri, pos(text, "log2(int", 1, 0));
|
||||||
|
assert_eq!(in_mb.detail.as_deref(), Some("mb"));
|
||||||
|
let moved = format!("// one\n// two\n// three\n{text}");
|
||||||
|
session.open(&path, &moved);
|
||||||
|
assert_eq!(
|
||||||
|
callers(&incoming(&mut session, &in_mb)),
|
||||||
|
[(s("mb"), s("two.sv"), vec![9, 10])],
|
||||||
|
"the tie broken by the container"
|
||||||
|
);
|
||||||
|
let renamed = moved.replace(
|
||||||
|
"log2(int v); return v; endfunction\n int b",
|
||||||
|
"lg(int v); return v; endfunction\n int b",
|
||||||
|
);
|
||||||
|
session.open(&path, &renamed);
|
||||||
|
assert!(incoming(&mut session, &in_mb).is_empty(), "never `ma`'s `log2`");
|
||||||
|
assert!(outgoing(&mut session, &in_mb).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_classic_clog2_is_not_its_own_caller() {
|
||||||
|
// QA finding 1: `clog2 = clog2 + 1;` reads the result variable.
|
||||||
|
let text = "\
|
||||||
|
module lg (output integer o);
|
||||||
|
function integer clog2(input integer v);
|
||||||
|
begin
|
||||||
|
clog2 = 0;
|
||||||
|
while (v > 1) begin
|
||||||
|
clog2 = clog2 + 1;
|
||||||
|
v = v >> 1;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
endfunction
|
||||||
|
initial o = clog2(16);
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let tree = Tree::new("hev_clog2");
|
||||||
|
tree.write("lg.sv", text);
|
||||||
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||||
|
let uri = session.open(&tree.path.join("lg.sv"), text);
|
||||||
|
session.drain();
|
||||||
|
let clog2 = one(&mut session, &uri, pos(text, "clog2(input", 0, 0));
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &clog2)), [(s("lg"), s("lg.sv"), vec![10])]);
|
||||||
|
assert!(outgoing(&mut session, &clog2).is_empty(), "no false recursion");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_untitled_buffer_answers_from_itself() {
|
||||||
|
let text = "module m;\n function int f(); return 1; endfunction\n int x = f();\nendmodule\n";
|
||||||
|
let tree = Tree::new("hev_untitled");
|
||||||
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||||
|
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
|
||||||
|
session.notify(
|
||||||
|
DidOpenTextDocument::METHOD,
|
||||||
|
serde_json::json!({
|
||||||
|
"textDocument": { "uri": uri, "languageId": "systemverilog", "version": 1, "text": text }
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
session.drain();
|
||||||
|
let f = one(&mut session, &uri, pos(text, "f()", 1, 0));
|
||||||
|
assert_eq!(f.uri, uri);
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &f)), [(s("m"), s("untitled:Untitled-1"), vec![2])]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_functions_of_one_name_are_told_apart_by_data() {
|
||||||
|
let text = "\
|
||||||
|
module a;
|
||||||
|
function int f(); return 1; endfunction
|
||||||
|
initial $display(f());
|
||||||
|
endmodule
|
||||||
|
|
||||||
|
module b;
|
||||||
|
function int f(); return 2; endfunction
|
||||||
|
int x = f();
|
||||||
|
int y = f();
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let tree = Tree::new("hev_same_name");
|
||||||
|
tree.write("two.sv", text);
|
||||||
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||||
|
let uri = session.open(&tree.path.join("two.sv"), text);
|
||||||
|
session.drain();
|
||||||
|
let in_b = one(&mut session, &uri, pos(text, "f()", 2, 0));
|
||||||
|
assert_eq!(shape(&in_b), (s("f"), s("two.sv"), 6), "the declaration in `b`");
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &in_b)), [(s("b"), s("two.sv"), vec![7, 8])]);
|
||||||
|
let in_a = one(&mut session, &uri, pos(text, "f()", 0, 0));
|
||||||
|
assert_eq!(callers(&incoming(&mut session, &in_a)), [(s("a"), s("two.sv"), vec![2])]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_item_whose_data_is_not_ours_is_treated_as_a_module_item() {
|
||||||
|
let (_tree, mut session, core) = design("hev_foreign");
|
||||||
|
let mut item = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||||
|
item.data = Some(serde_json::json!({ "kind": "rocket" }));
|
||||||
|
assert!(incoming(&mut session, &item).is_empty(), "no module is called `twice`");
|
||||||
|
assert!(outgoing(&mut session, &item).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// type hierarchy inside a class body
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn prepare_type(session: &mut Session, uri: &Uri, position: Value) -> Vec<String> {
|
||||||
|
let result = session.result(
|
||||||
|
TypeHierarchyPrepare::METHOD,
|
||||||
|
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
|
||||||
|
);
|
||||||
|
match result.as_array() {
|
||||||
|
Some(items) => {
|
||||||
|
items.iter().map(|i| i["name"].as_str().unwrap_or("?").to_string()).collect()
|
||||||
|
}
|
||||||
|
None => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inside_a_class_body_prepares_the_class_and_super_prepares_its_base() {
|
||||||
|
let (tree, mut session, core) = design("hev_type");
|
||||||
|
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||||
|
assert_eq!(
|
||||||
|
prepare_type(&mut session, &cls, pos(CLS, "int n", 0, 4)),
|
||||||
|
["counter"],
|
||||||
|
"a property"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
prepare_type(&mut session, &cls, pos(CLS, "n++", 0, 0)),
|
||||||
|
["counter"],
|
||||||
|
"a method body"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
prepare_type(&mut session, &cls, pos(CLS, "this.bump", 0, 1)),
|
||||||
|
["counter"],
|
||||||
|
"`this`"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 2)),
|
||||||
|
["counter"],
|
||||||
|
"`super`"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 7)),
|
||||||
|
["fancy"],
|
||||||
|
"the method name after `super.` is inside `fancy`"
|
||||||
|
);
|
||||||
|
assert!(prepare_type(&mut session, &core, pos(CORE, "int r", 0, 4)).is_empty(), "a module");
|
||||||
|
}
|
||||||
@@ -52,6 +52,7 @@ mod code_action;
|
|||||||
mod file_ops;
|
mod file_ops;
|
||||||
mod folders;
|
mod folders;
|
||||||
mod formatting;
|
mod formatting;
|
||||||
|
mod hierarchy_everywhere;
|
||||||
mod hierarchy_reach;
|
mod hierarchy_reach;
|
||||||
mod index;
|
mod index;
|
||||||
mod large_file;
|
mod large_file;
|
||||||
|
|||||||
@@ -31,11 +31,12 @@ use crate::state::{Document, Workspace};
|
|||||||
use crate::uri::{path_to_uri, uri_to_path};
|
use crate::uri::{path_to_uri, uri_to_path};
|
||||||
|
|
||||||
/// The class the cursor names, as the root of a type hierarchy — its own
|
/// The class the cursor names, as the root of a type hierarchy — its own
|
||||||
/// declaration, or any use of its name.
|
/// declaration, or any use of its name — else the class whose body holds the
|
||||||
|
/// cursor (its base, on `super`).
|
||||||
///
|
///
|
||||||
/// `None` for every other position, which is what stops an editor from opening
|
/// `None` outside every class, which is what stops an editor from opening an
|
||||||
/// an empty hierarchy view on a `wire`. A name that resolves to something other
|
/// empty hierarchy view on a module's `wire`: modules stay off the type
|
||||||
/// than a class declines the same way: there is no node to stand on.
|
/// hierarchy.
|
||||||
///
|
///
|
||||||
/// A name two files declare returns *both* items rather than a guess, the same
|
/// A name two files declare returns *both* items rather than a guess, the same
|
||||||
/// answer `textDocument/definition` gives for the same ambiguity — the client
|
/// answer `textDocument/definition` gives for the same ambiguity — the client
|
||||||
@@ -55,7 +56,47 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<TypeHierarc
|
|||||||
// navigation uses: this file's own symbol table, then the workspace
|
// navigation uses: this file's own symbol table, then the workspace
|
||||||
// overlay.
|
// overlay.
|
||||||
let items = classes_at(ws, doc, uri, offset);
|
let items = classes_at(ws, doc, uri, offset);
|
||||||
(!items.is_empty()).then_some(items)
|
if !items.is_empty() {
|
||||||
|
return Some(items);
|
||||||
|
}
|
||||||
|
// Anywhere else inside a class — a property, a method body, a keyword —
|
||||||
|
// the class that encloses the cursor is the node to stand on, and `super`
|
||||||
|
// names its base.
|
||||||
|
let positions = doc.positions();
|
||||||
|
let decl = enclosing_class(&doc.tree.items, offset)?;
|
||||||
|
let class = item(uri.clone(), &positions, decl)?;
|
||||||
|
if on_super(doc, offset) {
|
||||||
|
let bases = bases_of(ws, doc, uri, &class);
|
||||||
|
if !bases.is_empty() {
|
||||||
|
return Some(bases);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(vec![class])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The innermost class declaration whose extent holds `offset`, its end
|
||||||
|
/// included.
|
||||||
|
///
|
||||||
|
/// Read off the same [`classes::declarations`] walk every other answer here
|
||||||
|
/// uses, so a class that walk cannot see (one inside a generate block) is not
|
||||||
|
/// a node from the inside either.
|
||||||
|
fn enclosing_class(items: &[Item], offset: u32) -> Option<Decl<'_>> {
|
||||||
|
classes::declarations(items)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|decl| decl.span.start <= offset && offset <= decl.span.end)
|
||||||
|
.min_by_key(|decl| decl.span.end - decl.span.start)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the cursor is on `super`, the end of it included. The lexer reads
|
||||||
|
/// `super` as an identifier, so the token's text is what is asked.
|
||||||
|
fn on_super(doc: &Document, offset: u32) -> bool {
|
||||||
|
use vlog_parser::token::TokenKind;
|
||||||
|
let at = crate::state::first_token_reaching(&doc.tokens, offset);
|
||||||
|
doc.tokens.get(at).is_some_and(|token| {
|
||||||
|
matches!(token.kind, TokenKind::Ident | TokenKind::Keyword)
|
||||||
|
&& token.text == "super"
|
||||||
|
&& token.span.start <= offset
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What this class extends: its base class, resolved in this file first and
|
/// What this class extends: its base class, resolved in this file first and
|
||||||
@@ -409,8 +450,11 @@ endclass
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reversed by call-hierarchy-everywhere (2026-10-14): the `class`
|
||||||
|
/// keyword and a property are inside `base` and prepare it. A module
|
||||||
|
/// and its wire still prepare nothing — modules stay off this view.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_position_on_no_class_prepares_nothing() {
|
fn a_position_on_no_class_prepares_the_enclosing_one_or_nothing() {
|
||||||
let text = "\
|
let text = "\
|
||||||
class base;
|
class base;
|
||||||
int x;
|
int x;
|
||||||
@@ -421,8 +465,9 @@ module m;
|
|||||||
endmodule
|
endmodule
|
||||||
";
|
";
|
||||||
let (_tree, ws, uri) = workspace("none", &[("n.sv", text)]);
|
let (_tree, ws, uri) = workspace("none", &[("n.sv", text)]);
|
||||||
assert!(prepare(&ws, &uri, 0).is_none(), "the `class` keyword");
|
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("a class")[0]).0;
|
||||||
assert!(prepare(&ws, &uri, at(text, "int x") + 4).is_none(), "a property name");
|
assert_eq!(name(0), "base", "the `class` keyword is inside `base`");
|
||||||
|
assert_eq!(name(at(text, "int x") + 4), "base", "a property name is inside `base`");
|
||||||
assert!(prepare(&ws, &uri, at(text, "module m") + 7).is_none(), "a module is not a class");
|
assert!(prepare(&ws, &uri, at(text, "module m") + 7).is_none(), "a module is not a class");
|
||||||
assert!(prepare(&ws, &uri, at(text, "wire w") + 5).is_none(), "a wire");
|
assert!(prepare(&ws, &uri, at(text, "wire w") + 5).is_none(), "a wire");
|
||||||
}
|
}
|
||||||
@@ -831,15 +876,21 @@ endclass
|
|||||||
// QA (2026-08-26): prepare on the keyword, and name shadowing
|
// QA (2026-08-26): prepare on the keyword, and name shadowing
|
||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Reversed by call-hierarchy-everywhere (2026-10-14): the keyword is
|
||||||
|
/// inside `child`'s header and prepares `child` — still not `base`.
|
||||||
#[test]
|
#[test]
|
||||||
fn prepare_on_the_extends_keyword_itself_prepares_nothing() {
|
fn prepare_on_the_extends_keyword_itself_prepares_the_class_it_is_written_in() {
|
||||||
let text = "class base;\nendclass\nclass child extends base;\nendclass\n";
|
let text = "class base;\nendclass\nclass child extends base;\nendclass\n";
|
||||||
let (_tree, ws, uri) = workspace("keyword", &[("f.sv", text)]);
|
let (_tree, ws, uri) = workspace("keyword", &[("f.sv", text)]);
|
||||||
assert!(prepare(&ws, &uri, at(text, "extends") + 2).is_none(), "the keyword, not a name");
|
let items = prepare(&ws, &uri, at(text, "extends") + 2).expect("the enclosing class");
|
||||||
|
assert_eq!(shape(&items[0]).0, "child", "the keyword, not a name");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reversed by call-hierarchy-everywhere (2026-10-14): the variable use
|
||||||
|
/// is inside `child` and prepares `child`. The point of the pin stands —
|
||||||
|
/// it never prepares the class `base` its text spells.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing() {
|
fn a_class_name_shadowed_by_a_local_variable_prepares_the_enclosing_class() {
|
||||||
// `base` is both a class and, inside `child`'s method, a local
|
// `base` is both a class and, inside `child`'s method, a local
|
||||||
// variable name. The use on the right-hand side of the assignment
|
// variable name. The use on the right-hand side of the assignment
|
||||||
// names the variable, not the class, and must not be treated as a
|
// names the variable, not the class, and must not be treated as a
|
||||||
@@ -857,10 +908,9 @@ endclass
|
|||||||
";
|
";
|
||||||
let (_tree, ws, uri) = workspace("shadow", &[("f.sv", text)]);
|
let (_tree, ws, uri) = workspace("shadow", &[("f.sv", text)]);
|
||||||
let use_offset = at(text, "base + 1");
|
let use_offset = at(text, "base + 1");
|
||||||
assert!(
|
let items = prepare(&ws, &uri, use_offset).expect("the enclosing class");
|
||||||
prepare(&ws, &uri, use_offset).is_none(),
|
assert_eq!(items.len(), 1);
|
||||||
"a local variable named `base`, not the class"
|
assert_eq!(shape(&items[0]).0, "child", "a local variable named `base`, not the class");
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
|
|||||||
@@ -3398,7 +3398,9 @@ fn the_module_hierarchy_round_trips_over_the_wire_in_both_directions() {
|
|||||||
"both sites of the same module, in one call"
|
"both sites of the same module, in one call"
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_eq!(response(5)["result"], serde_json::Value::Null, "an instance name is no module");
|
// Reversed by call-hierarchy-everywhere (2026-10-14): an instance name
|
||||||
|
// prepares the module it instantiates.
|
||||||
|
assert_eq!(response(5)["result"][0]["name"], "hier_mid", "an instance name is its module");
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
@@ -4873,7 +4875,9 @@ fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() {
|
|||||||
assert_eq!(subtypes[0]["uri"], leaf_uri.as_str());
|
assert_eq!(subtypes[0]["uri"], leaf_uri.as_str());
|
||||||
assert_eq!(subtypes[0]["kind"], 5, "SymbolKind.Class");
|
assert_eq!(subtypes[0]["kind"], 5, "SymbolKind.Class");
|
||||||
|
|
||||||
assert_eq!(response(5)["result"], serde_json::Value::Null, "a property name is no class");
|
// Reversed by call-hierarchy-everywhere (2026-10-14): inside a class body
|
||||||
|
// the enclosing class answers.
|
||||||
|
assert_eq!(response(5)["result"][0]["name"], "type_mid", "a property is in its class");
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,597 @@
|
|||||||
|
# call-hierarchy-everywhere
|
||||||
|
|
||||||
|
Lane A of a two-lane wave (2026-10-14). Builds on `hierarchy` (M11, the
|
||||||
|
module call hierarchy) and `type-hierarchy` (the class tree); both READMEs
|
||||||
|
point here for what changed.
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
A user report: in VS Code, "Show Call Hierarchy" showed nothing. The lead
|
||||||
|
reproduced it at the LSP level — `prepareCallHierarchy` answered only with the
|
||||||
|
cursor exactly on a module's declaration name or on an instantiated module
|
||||||
|
name, and `null` everywhere else (an instance name, anywhere in a module body,
|
||||||
|
on or inside a function or task); `prepareTypeHierarchy` answered `null`
|
||||||
|
anywhere inside a class body but on its name. An editor that opens nothing
|
||||||
|
from 95 % of the positions a user invokes the command from looks broken,
|
||||||
|
whatever the protocol allows. This feature makes both views open from wherever
|
||||||
|
the cursor is, and gives functions and tasks a call hierarchy of their own —
|
||||||
|
callers and callees resolved through the semantic and workspace layers, not by
|
||||||
|
name-matching strings.
|
||||||
|
|
||||||
|
## What each prepare position answers
|
||||||
|
|
||||||
|
`textDocument/prepareCallHierarchy`, first match wins:
|
||||||
|
|
||||||
|
| cursor | answer |
|
||||||
|
|---|---|
|
||||||
|
| a module's own declaration name | that module (M11, byte-identical) |
|
||||||
|
| the module name of an instantiation | every declaration of it (M11, byte-identical) |
|
||||||
|
| an **instance name** (`u_sub` in `sub u_sub (…)`) | the instantiated module's item(s) — the same answer as its module name |
|
||||||
|
| a function or task: its declaration name, a call, the `endfunction : f` label | a function/task item (`FUNCTION`, or `METHOD` in a class); a call two files could answer gives both, as `definition` does |
|
||||||
|
| anywhere else inside a function or task body (incl. its header and `endfunction`) | that function or task |
|
||||||
|
| anywhere else inside a module, interface or program (incl. its header, comments, strings) | the innermost enclosing module's item, exactly as M11 builds it |
|
||||||
|
| a package body outside its functions, a file-level or package-level class body outside its methods, file scope, a large-file buffer | `null` |
|
||||||
|
|
||||||
|
A class declared *inside a module* is inside that module, so a position in
|
||||||
|
its body outside a method answers the enclosing module (the innermost-module
|
||||||
|
rule), not `null`. A cursor on a macro use (`` `CALL_IT(1) ``) is no name
|
||||||
|
either layer resolves, so it answers the enclosing function or module.
|
||||||
|
|
||||||
|
A position just past the last character of a name is on that name (M11's
|
||||||
|
caret rule, extended to calls: `twice|(v)` prepares `twice`).
|
||||||
|
|
||||||
|
`textDocument/prepareTypeHierarchy`: the class name or a use of it as before;
|
||||||
|
otherwise the **innermost class whose declaration encloses the cursor**; on
|
||||||
|
`super`, that class's base(s) (`supertypes` of the enclosing class), falling
|
||||||
|
back to the class itself when the base is unresolvable. `this` needs no case —
|
||||||
|
it is inside its class. Modules stay off the type hierarchy (the type-hierarchy
|
||||||
|
README's lead decision): a position in a module and outside every class is
|
||||||
|
still `null`.
|
||||||
|
|
||||||
|
## Item kinds and `data`
|
||||||
|
|
||||||
|
| item | `kind` | `data` |
|
||||||
|
|---|---|---|
|
||||||
|
| module / interface / program | `MODULE` (unchanged) | none (unchanged) |
|
||||||
|
| function or task | `FUNCTION`; `METHOD` when declared in a class | `{"kind":"function"\|"task","name":…,"offset":…}` |
|
||||||
|
| package caller | `PACKAGE` | `{"kind":"package","name":…,"offset":…}` |
|
||||||
|
| class caller | `CLASS` | `{"kind":"class","name":…,"offset":…}` |
|
||||||
|
|
||||||
|
`offset` is the byte offset of the declared name in the item's file when the
|
||||||
|
item was built. `detail` on a function/task/package/class item is the name of
|
||||||
|
the container the declaration sits in (`util_pkg`, `counter`), so two `log2`s
|
||||||
|
in one list can be told apart; `None` at `$unit`.
|
||||||
|
|
||||||
|
`incomingCalls`/`outgoingCalls` route on `data`: an item whose `data` parses
|
||||||
|
as above goes to `hierarchy/calls.rs`; anything else (no `data`, or `data`
|
||||||
|
this server did not write) is a module item and takes the M11 path untouched.
|
||||||
|
Package and class caller items answer both directions with nothing.
|
||||||
|
|
||||||
|
**Re-finding the declaration.** The item's file (the open buffer, else a fresh
|
||||||
|
analysis of the file on disk) is searched for symbols of that name and kind:
|
||||||
|
the one whose name starts at `offset`, else the one at the item's
|
||||||
|
`selectionRange` start, else — by name alone — the **only** one of that name
|
||||||
|
and kind declared in the container the item's `detail` names (no container
|
||||||
|
for `$unit`). Otherwise the item answers nothing: unlike modules, two
|
||||||
|
functions of one name are ordinary, and the old "first of that name" fallback
|
||||||
|
let a stale item for `mb`'s `log2` answer for `ma`'s (QA finding 3). `detail`
|
||||||
|
is the one echoed field relied on besides `data`, and only as a tie-break.
|
||||||
|
|
||||||
|
## Incoming and outgoing
|
||||||
|
|
||||||
|
**A call** is a use of the function's name that the semantic layer resolved
|
||||||
|
to the declaration — in the declaring file through the symbol table or the
|
||||||
|
workspace overlay (`super.f()` reaches a base-class method through the
|
||||||
|
overlay), in another file through the overlay — and that is not one of three
|
||||||
|
non-call uses: the `endfunction : f` end label, the name of an out-of-body
|
||||||
|
definition (`function void c::f();`, recorded as a redeclaration), and the
|
||||||
|
Verilog **result variable**: a function's own name inside its own body with no
|
||||||
|
`(` after it, whether written (`f = a;`, `f += 1;`) or read
|
||||||
|
(`clog2 = clog2 + 1;`). `f(…)` inside its own body is recursion and is listed;
|
||||||
|
a bare `f` in *another* body is a call (a function with no arguments may be
|
||||||
|
called without parentheses) and is listed too.
|
||||||
|
|
||||||
|
**`incomingCalls`** — every call, workspace-wide, from the same files
|
||||||
|
`textDocument/references` reads for the same declaration: the declaring file;
|
||||||
|
for a declaration the index holds (a package or class member), every open
|
||||||
|
buffer plus every closed file the index has a reference posting for. The same
|
||||||
|
ambiguity contract too: a declaration whose uses the index marks ambiguous,
|
||||||
|
or an open buffer holding an ambiguous use of it, falls back to the declaring
|
||||||
|
file alone (references falls back to the cursor's file). Grouped one entry per
|
||||||
|
caller — the innermost enclosing function or task, else the enclosing module,
|
||||||
|
interface, program, package or class — with `fromRanges` the call names. A
|
||||||
|
call at file scope has no caller and is dropped (the same rule as an
|
||||||
|
instantiation outside a module). Sorted by caller URI, then line. A **module
|
||||||
|
caller** is the very M11 module item (no `data`), so expanding it walks
|
||||||
|
instantiations — one level up the design.
|
||||||
|
|
||||||
|
**`outgoingCalls`** — the calls written in the function's bodies (plural: an
|
||||||
|
`extern` prototype and its out-of-body definition are two scopes owned by one
|
||||||
|
symbol), each resolved to its declaration, grouped by callee in order of first
|
||||||
|
call. **Skipped:** system tasks and functions (`$display` is not a reference
|
||||||
|
at all), an unresolved name, and a name the overlay finds ambiguous — the same
|
||||||
|
silence M11's `outgoingCalls` keeps for an ambiguous instantiation, for the
|
||||||
|
same reason (a node pointing at the wrong one of two declarations is
|
||||||
|
unfalsifiable to the reader).
|
||||||
|
|
||||||
|
**Module items do not mix in function calls** (the brief's default, kept). A
|
||||||
|
module's outgoing calls are instantiations; listing `always`-block calls beside
|
||||||
|
them would put two relations behind one node with no way for a client to tell
|
||||||
|
them apart — exactly the argument the type-hierarchy README makes for keeping
|
||||||
|
modules off `typeHierarchy`. The function-to-module direction does mix, on
|
||||||
|
purpose: a function's caller may *be* a module, and that node is the module
|
||||||
|
item, whose own expansion is the design tree.
|
||||||
|
|
||||||
|
Each request answers one hop; recursion (`fact` calls `fact`) is the function
|
||||||
|
appearing as its own caller and callee, and the client drives the expansion.
|
||||||
|
|
||||||
|
## Assumptions
|
||||||
|
|
||||||
|
- **Callers are found by re-analysing files, not from the index's spans.**
|
||||||
|
Attribution needs the enclosing scope of every call, which a reference
|
||||||
|
posting does not carry, so each candidate closed file is parsed and analysed
|
||||||
|
once (`Document::new`) — the cost is one parse per file that references the
|
||||||
|
function, the same order as `incomingCalls` for modules reading the files
|
||||||
|
that instantiate. The *file selection* is references'; the spans are the
|
||||||
|
live analysis's, so a closed file edited on disk since the last index build
|
||||||
|
answers with its current text (references would drop the stale span).
|
||||||
|
- **The result variable is recognised by scope plus one token:** the use
|
||||||
|
resolves to a function, sits in a body that function owns (its own scope
|
||||||
|
or an out-of-body definition's), and the next token is not `(`. Tasks have
|
||||||
|
no result variable. This is the only token-level judgement; everything else
|
||||||
|
is the semantic model's.
|
||||||
|
- **An end label is recognised structurally:** it lies inside the extent of
|
||||||
|
the scope its declaration opens but is recorded in the scope around it
|
||||||
|
(`vlog_semantic`'s `use_end_label`). A recursive call is recorded inside.
|
||||||
|
- **Two declarations of one name and kind in one file** resolve by `offset`;
|
||||||
|
when an edit has moved both the offset and the selection range, by the
|
||||||
|
item's `detail` (container), and otherwise not at all — see "Re-finding the
|
||||||
|
declaration".
|
||||||
|
- **The two ambiguity fallbacks are defensive.** `indexed_def_for_symbol`
|
||||||
|
accepts a declaration only when its unit's member table holds exactly one
|
||||||
|
record for the name, and every use's lookup reads that same table, so in a
|
||||||
|
consistent workspace no use can be ambiguous *and* include a declaration
|
||||||
|
this feature stands on. The decision lives in one predicate, `declined`,
|
||||||
|
whose two clauses are each pinned by a unit test that reaches it directly
|
||||||
|
(an indexed caller of a twice-declared package; an open buffer outside the
|
||||||
|
indexed folder); kept because references has the same contract and a
|
||||||
|
future index rule could make the case reachable.
|
||||||
|
- **A function's caller inside a class body but outside a method** (a
|
||||||
|
property initializer) is the class; inside a package outside a function, the
|
||||||
|
package. Both are items with `data` and no further hops.
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
|
||||||
|
- **A `$unit` function called from another file** is not resolved: the
|
||||||
|
semantic layer finishes an unqualified value-position name only through
|
||||||
|
imports, so `ufn(1)` in a file that does not declare `ufn` is `NotFound`.
|
||||||
|
In-file calls work. The cursor on such a call falls back to the enclosing
|
||||||
|
module. Pinned by
|
||||||
|
`hierarchy_everywhere::a_unit_scope_function_answers_in_its_own_file_only`.
|
||||||
|
- **A module's own function called hierarchically from another module**
|
||||||
|
(`u_core.twice()`) is not a call this feature sees: module-level functions
|
||||||
|
are on no index surface (`surface_of(Module, Function)` is `None`).
|
||||||
|
- **The end label of an out-of-body definition** records no use in the binder,
|
||||||
|
so prepare on it falls back to the enclosing function (the definition's own
|
||||||
|
body), which is the right item anyway.
|
||||||
|
- **Class methods:** calls through `this.`, a bare name, a typed handle
|
||||||
|
(same file and across files, through `import`) and `super.` all resolve and
|
||||||
|
are listed. Virtual dispatch is not modelled: `h.f()` is a call of the `f`
|
||||||
|
the handle's *declared* class resolves to, not of every override.
|
||||||
|
- `prepareTypeHierarchy` on `super` with an unresolvable base answers the
|
||||||
|
enclosing class rather than `null`.
|
||||||
|
- **Macros are not expanded.** A cursor on a macro use answers the enclosing
|
||||||
|
function or module, and a call written inside a macro body (`` `CALL_IT(1) ``
|
||||||
|
expanding to `cf(1)`) is not listed by `incomingCalls` or `outgoingCalls` —
|
||||||
|
the same answer references gives, since neither layer sees the expansion.
|
||||||
|
|
||||||
|
## Handshakes
|
||||||
|
|
||||||
|
- **Consumes `vlog_semantic`** (read-only, nothing new asked): `Semantics`
|
||||||
|
scopes/symbols/references/duplicates, `ExternalResolutions::{definition_of,
|
||||||
|
get}`, `WorkspaceIndex::{references_to, references_are_ambiguous, path}`.
|
||||||
|
- **Consumes `crate::nav::indexed_def_for_symbol`** (already `pub(crate)`)
|
||||||
|
— the identity references uses to map a live symbol onto its indexed
|
||||||
|
declaration, so this feature and references agree on what "the same
|
||||||
|
function" is by construction. `nav.rs` is unchanged.
|
||||||
|
- **Consumes `crate::state`**: `Document::new` (a fresh analysis of a closed
|
||||||
|
file, as `type_hierarchy::supertypes` already does), `document`,
|
||||||
|
`document_for_path`, `open_documents`, `text_of`, `first_token_from`,
|
||||||
|
`first_token_reaching`. Unchanged.
|
||||||
|
- **Promises `server/dispatch.rs`**: nothing new — `hierarchy::{prepare,
|
||||||
|
incoming, outgoing}` and `type_hierarchy::prepare` keep their signatures,
|
||||||
|
and the routing on `data` lives inside `hierarchy.rs`. `dispatch.rs` is
|
||||||
|
untouched.
|
||||||
|
- **Promises clients**: a module item is byte-identical to M11's wherever M11
|
||||||
|
answered; `data` is present exactly on function, task, package and class
|
||||||
|
items.
|
||||||
|
- **REQUEST to the lead — `crates/lucisv_server/tests/e2e.rs` (not in this
|
||||||
|
lane's file list).** Two e2e round trips pin the old `null` at positions the
|
||||||
|
brief now makes answer, and fail on this lane:
|
||||||
|
- `the_module_hierarchy_round_trips_over_the_wire_in_both_directions`,
|
||||||
|
line 3401: `assert_eq!(response(5)["result"], Null, "an instance name is
|
||||||
|
no module")` — request 5 is the cursor on the instance name `u_mid` of
|
||||||
|
`hier_mid u_mid ();`; it now answers the `hier_mid` item. Proposed:
|
||||||
|
`assert_eq!(response(5)["result"][0]["name"], "hier_mid", "an instance
|
||||||
|
name stands for its module")` (and the comment above request 5, "The
|
||||||
|
instance name is not a module, so there is no hierarchy to open.", to
|
||||||
|
match).
|
||||||
|
- `the_class_hierarchy_round_trips_over_the_wire_in_both_directions`,
|
||||||
|
line 4876: `assert_eq!(response(5)["result"], Null, "a property name is
|
||||||
|
no class")` — request 5 is the property name `y` inside `type_mid`; it now
|
||||||
|
answers `type_mid`. Proposed: `assert_eq!(response(5)["result"][0]["name"],
|
||||||
|
"type_mid", "inside a class body, the enclosing class")` (and the comment
|
||||||
|
above request 5).
|
||||||
|
No other test outside this lane's files moved.
|
||||||
|
- **Note for a future `vlog_semantic` round (not a request this lane
|
||||||
|
blocks on):** resolving an unqualified call to a `$unit` function declared
|
||||||
|
in another file would lift the first limit above. It is a resolution-rule
|
||||||
|
change (compilation-unit scope is tool- and filelist-dependent), not
|
||||||
|
something to work around here.
|
||||||
|
- **`editors/vscode` needs no change** (lane B owns it): the client already
|
||||||
|
sends `prepareCallHierarchy`/`prepareTypeHierarchy` from any position.
|
||||||
|
|
||||||
|
## Status / TODO
|
||||||
|
|
||||||
|
- [x] `prepareCallHierarchy`: instance name, function/task (declaration, call,
|
||||||
|
end label), inside a function/task body, inside a module body, `null`
|
||||||
|
elsewhere — `hierarchy.rs::prepare`, `hierarchy/tf.rs`
|
||||||
|
- [x] function/task items with `data`; package/class caller items
|
||||||
|
- [x] `incomingCalls` with references' file selection and ambiguity fallback,
|
||||||
|
grouped by caller — `hierarchy/calls.rs`
|
||||||
|
- [x] `outgoingCalls` over the body (and an out-of-body definition), grouped by
|
||||||
|
callee; system tasks, unresolved and ambiguous names skipped
|
||||||
|
- [x] module items unchanged in both directions
|
||||||
|
- [x] `prepareTypeHierarchy` inside a class body, `super` → base —
|
||||||
|
`type_hierarchy.rs`
|
||||||
|
- [x] tests: 24 LSP-level in `server/tests/hierarchy_everywhere.rs`, 3 in
|
||||||
|
`hierarchy/tf.rs`, 4 in `hierarchy/calls.rs`, 1 new in `hierarchy.rs`;
|
||||||
|
seven existing unit tests that pinned the old `null` updated (work log)
|
||||||
|
- [x] probe before/after on real server binaries (work log)
|
||||||
|
- [x] `tests/e2e.rs`: two assertions to update — Handshake request above (lead;
|
||||||
|
flipped by the lead, verified green by QA 2026-10-14)
|
||||||
|
- [x] `cargo fmt --all --check`, clippy `-D warnings`; `cargo test -p
|
||||||
|
lucisv_server` green except the two e2e assertions above
|
||||||
|
- [x] rework after QA (2026-10-14): findings 1–5 and 7 fixed, with tests
|
||||||
|
|
||||||
|
## Work log
|
||||||
|
|
||||||
|
- **2026-10-14 (dev)** — read CLAUDE.md, the hierarchy and type-hierarchy
|
||||||
|
READMEs, `hierarchy.rs`, `type_hierarchy.rs`, `nav.rs` (references),
|
||||||
|
`vlog_semantic`'s model, binder and instantiation walk.
|
||||||
|
|
||||||
|
**Probed the semantic model first** (a throwaway test dumping scopes,
|
||||||
|
symbols, references and duplicates for module, package, class, extern and
|
||||||
|
`$unit` functions; deleted). What it showed shaped the design: a function's
|
||||||
|
scope spans its whole declaration including `endfunction : f`; the end label
|
||||||
|
is a reference *recorded in the outer scope*; `f = a;` resolves to `f`;
|
||||||
|
`c::ext`'s name is a reference to the prototype *and* a `Duplicate`; the
|
||||||
|
out-of-body body is a second scope owned by the prototype's symbol;
|
||||||
|
`this.f()` and `h.f()` resolve locally; `$display` records nothing.
|
||||||
|
|
||||||
|
**Decision — collect callers here rather than reuse `nav::references`.**
|
||||||
|
`references` takes a cursor in an *open* document, and the item a client
|
||||||
|
expands is very often in a closed one (prepare on a call in `core.sv`,
|
||||||
|
the declaration lives in a closed package file). Making `nav.rs` take a
|
||||||
|
`&Document` was outside this lane's files, so `calls.rs` reads the same
|
||||||
|
file set through the same public index API (`references_to`,
|
||||||
|
`references_are_ambiguous`) and the same identity
|
||||||
|
(`nav::indexed_def_for_symbol`), and a test
|
||||||
|
(`the_cross_file_answer_matches_references`) asserts the two agree
|
||||||
|
location for location, end label aside.
|
||||||
|
|
||||||
|
**Decision — routing on `data` inside `hierarchy.rs`**, so `dispatch.rs`
|
||||||
|
is untouched and a module item's path is literally the old code.
|
||||||
|
|
||||||
|
**Decision — module callers are M11 module items.** Expanding a function's
|
||||||
|
caller `top` then shows who instantiates `top`, which reads as one call
|
||||||
|
chain up the design; the reverse direction (module → functions) stays
|
||||||
|
closed, argued above.
|
||||||
|
|
||||||
|
**Found while testing:** `super.bump()` resolves through the workspace
|
||||||
|
overlay (an inherited candidate), not the local table, so the first cut's
|
||||||
|
declaring-file matcher (`resolved() == symbol`) missed it while
|
||||||
|
`outgoingCalls` (which reads both layers) found it. Fixed: the declaring
|
||||||
|
file accepts either layer; pinned by
|
||||||
|
`class_methods_called_through_this_a_handle_and_super`.
|
||||||
|
|
||||||
|
**Existing tests changed — seven, all pins of the old `null` at positions
|
||||||
|
the brief now makes answer** (the brief asks both for these answers and for
|
||||||
|
existing tests "green and unchanged"; the two cannot both hold, so each one
|
||||||
|
was changed to assert the new answer, renamed where its name stated the old
|
||||||
|
one, and given a "Reversed by call-hierarchy-everywhere" doc line):
|
||||||
|
`hierarchy.rs`: `a_position_on_no_module_prepares_nothing` →
|
||||||
|
`…_prepares_the_enclosing_one_or_nothing` (`module` keyword and a connected
|
||||||
|
expression → `top`, instance name → `sub`; the package case still `null`);
|
||||||
|
`an_instantiation_of_a_module_nothing_declares_prepares_nothing` →
|
||||||
|
`…_prepares_the_enclosing_module`; `qa_prepare_on_a_string_or_comment_is_null`
|
||||||
|
→ `…_is_the_enclosing_module_not_the_text`;
|
||||||
|
`qa_prepare_on_a_bind_target_module_name_is_currently_null` →
|
||||||
|
`…_was_null` (now `top`, the module the bind is written in) plus a new
|
||||||
|
`…_is_the_enclosing_module` with the bind moved into a `harness` so target
|
||||||
|
and enclosing module differ. `type_hierarchy.rs`:
|
||||||
|
`a_position_on_no_class_prepares_nothing` →
|
||||||
|
`…_prepares_the_enclosing_one_or_nothing` (`class` keyword and a property →
|
||||||
|
`base`; module and wire still `null`);
|
||||||
|
`prepare_on_the_extends_keyword_itself_prepares_nothing` →
|
||||||
|
`…_prepares_the_class_it_is_written_in` (`child`, never `base`);
|
||||||
|
`a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing`
|
||||||
|
→ `…_prepares_the_enclosing_class` (`child`, never `base`). The
|
||||||
|
generate-class "known gap" pin is unchanged and green: the enclosing-class
|
||||||
|
fallback reads the same `classes::declarations` walk, so a class that walk
|
||||||
|
cannot see is not a node from the inside either. The two e2e pins of the
|
||||||
|
same kind are a Handshake request (not this lane's file).
|
||||||
|
|
||||||
|
**Probe** (`probe.py` against `proj/`, a `sub`/`top`/`cls` trio; "before"
|
||||||
|
is a debug build of master 41a9091 from `git archive`, "after" this lane's
|
||||||
|
debug build):
|
||||||
|
|
||||||
|
```
|
||||||
|
position before after
|
||||||
|
instance name u_sub null sub (MODULE, data null)
|
||||||
|
inside module body (logic r) null sub
|
||||||
|
inside always_ff null sub
|
||||||
|
function decl inv null inv (FUNCTION, data function)
|
||||||
|
call inv(r) null inv
|
||||||
|
inside poke body null poke (data task)
|
||||||
|
on endfunction keyword null inv
|
||||||
|
task decl poke null poke
|
||||||
|
module decl sub sub sub (identical)
|
||||||
|
call hello() in leaf_c::go null hello (METHOD, base_c's)
|
||||||
|
incoming(inv) = [poke @9] outgoing(poke) = [inv @9]
|
||||||
|
incoming(hello) = [go (METHOD) @9]
|
||||||
|
type: class name mid_c mid_c mid_c
|
||||||
|
type: inside leaf_c method body null leaf_c
|
||||||
|
type: module body null null
|
||||||
|
```
|
||||||
|
|
||||||
|
**Gates.** `cargo fmt --all --check` clean;
|
||||||
|
`tools/guard.sh -- cargo clippy --workspace --all-targets -- -D warnings`
|
||||||
|
clean; `tools/guard.sh -t 1800 -- cargo test -p lucisv_server`: unit/server
|
||||||
|
binary **1753 passed, 36 ignored** (1757 tests before → 1789 after, +32);
|
||||||
|
`tests/e2e.rs` **97 passed, 2 failed, 2 ignored** — the two failures are
|
||||||
|
exactly the Handshake request above; `tests/grammar.rs` green. No change to
|
||||||
|
`vlog_semantic` or `vlog_refactor` behaviour, so their suites were not
|
||||||
|
re-run. No new dependencies. No commits.
|
||||||
|
|
||||||
|
**Files.** New: `crates/lucisv_server/src/hierarchy/tf.rs`,
|
||||||
|
`crates/lucisv_server/src/hierarchy/calls.rs`,
|
||||||
|
`crates/lucisv_server/src/server/tests/hierarchy_everywhere.rs`, this README.
|
||||||
|
Edited: `crates/lucisv_server/src/hierarchy.rs` (prepare chain, routing on
|
||||||
|
`data`, test updates), `crates/lucisv_server/src/type_hierarchy.rs`
|
||||||
|
(enclosing-class fallback, `super`, test updates),
|
||||||
|
`crates/lucisv_server/src/server/tests/mod.rs` (one `mod` line),
|
||||||
|
`docs/features/hierarchy/README.md` and
|
||||||
|
`docs/features/type-hierarchy/README.md` (pointer notes). Not touched:
|
||||||
|
`dispatch.rs`, `nav.rs`, `main.rs`, `vlog_*`, `editors/`, `TODO.md`.
|
||||||
|
|
||||||
|
- **2026-10-14 (dev) — rework after QA.** QA's findings 1–5 and 7.
|
||||||
|
|
||||||
|
1. **Result variable (MEDIUM).** `is_call` now treats a function's own name
|
||||||
|
inside a body it owns, with no `(` after it, as the result variable —
|
||||||
|
read or written — and drops the separate assignment-operator check it
|
||||||
|
subsumes. `f(…)` there stays recursion; a bare `f` from another body
|
||||||
|
stays a call. The unit test that pinned `+ f` as a call is flipped;
|
||||||
|
new: `the_result_variable_read_in_its_own_body_is_not_a_call` (QA's
|
||||||
|
`clog2`), `a_bare_function_name_in_another_body_is_a_call`, and the
|
||||||
|
LSP-level `the_classic_clog2_is_not_its_own_caller`.
|
||||||
|
2. **Per-callee re-parse (MEDIUM, perf).** `tf::Loaded` holds one
|
||||||
|
analysis per path for the life of one request; `outgoingCalls` and
|
||||||
|
prepare's multi-declaration answer build every cross-file item through
|
||||||
|
it, and `live_symbol` asks identity of the symbol at the recorded
|
||||||
|
position first. QA's shape (one closed 430 KB package of 300 functions,
|
||||||
|
a caller calling all 300, `scratchpad/lsp/gen_perf.py` + `s_perf.py`),
|
||||||
|
release builds, three runs each: **before 3 043 / 3 018 / 3 032 ms,
|
||||||
|
after 21 / 18 / 17 ms**.
|
||||||
|
3. **Stale item (LOW-MEDIUM).** The "first of that name" fallback is gone:
|
||||||
|
by name alone only the one candidate in the item's `detail` container
|
||||||
|
answers, asked even of a lone candidate (a renamed-away `mb` leaves
|
||||||
|
`ma`'s `log2` as the only one, and it is still the wrong function).
|
||||||
|
New: `a_stale_item_never_answers_for_a_same_named_function_elsewhere`
|
||||||
|
(QA's `ma`/`mb` reproduction: after the move it answers `mb`'s callers,
|
||||||
|
after the rename nothing).
|
||||||
|
4. **Ambiguity fallbacks (coverage).** Both checks now sit in one
|
||||||
|
predicate, `declined`, called once before any file is read (same
|
||||||
|
answers: either clause still returns the declaring file alone). Its
|
||||||
|
clauses are each killed by a unit test:
|
||||||
|
`an_index_that_marks_the_uses_ambiguous_declines` (no buffer open, an
|
||||||
|
indexed `p::f()` with `p` declared twice),
|
||||||
|
`an_open_buffer_holding_an_ambiguous_use_declines` (index clean, a
|
||||||
|
buffer outside the indexed folder), plus
|
||||||
|
`an_ambiguous_use_in_the_declaring_file_itself_does_not_decline`.
|
||||||
|
**Not killable end to end, and why:** with a consistent workspace the
|
||||||
|
branch cannot be reached through `incomingCalls` — see the new
|
||||||
|
Assumption "The two ambiguity fallbacks are defensive". Removing the
|
||||||
|
single `if declined(..)` line in `other_files` therefore still survives
|
||||||
|
the suite; the predicate it calls does not.
|
||||||
|
5. **README.** Limits: macro uses and calls inside macro bodies. The
|
||||||
|
prepare table: a class inside a module answers the module.
|
||||||
|
|
||||||
|
**Gates.** `cargo fmt --all --check` clean; clippy `-D warnings` clean;
|
||||||
|
`tools/guard.sh -t 1800 -- cargo test -p lucisv_server`: guard exit 0;
|
||||||
|
server binary **1760 passed, 0 failed, 36 ignored** (1753 before the
|
||||||
|
rework, +7: five in `hierarchy/calls.rs`, two in
|
||||||
|
`server/tests/hierarchy_everywhere.rs`); `tests/e2e.rs` 99 passed, 2
|
||||||
|
ignored; `tests/grammar.rs` 3 passed.
|
||||||
|
|
||||||
|
## QA log
|
||||||
|
|
||||||
|
### 2026-10-14 — QA agent (Opus)
|
||||||
|
|
||||||
|
**Verdict: PASS with findings.** No corruption, panic or regression found; the
|
||||||
|
M11 module answers are byte-identical and no other client-visible feature moved.
|
||||||
|
Two medium findings (a false self-recursion for the classic Verilog result-variable
|
||||||
|
idiom, and per-callee re-parsing in `outgoingCalls`) are worth fixing before
|
||||||
|
release but block nothing else.
|
||||||
|
|
||||||
|
**Gates** (in this worktree):
|
||||||
|
- `cargo fmt --all --check`: clean.
|
||||||
|
- `tools/guard.sh -- cargo clippy --workspace --all-targets -- -D warnings`:
|
||||||
|
clean, guard exit 0.
|
||||||
|
- `tools/guard.sh -t 1800 -- cargo test -p lucisv_server`: guard exit 0.
|
||||||
|
Unit/server binary **1753 passed, 0 failed, 36 ignored**; `tests/e2e.rs`
|
||||||
|
**99 passed, 0 failed, 2 ignored** (the lead's two flipped assertions included);
|
||||||
|
`tests/grammar.rs` 3 passed. No host stall.
|
||||||
|
|
||||||
|
**Mutation check** (a scratch copy of the tree, `cargo test -p lucisv_server
|
||||||
|
--bin lucisv-server hierarch`, 144 tests in the filter). Killed: return-assignment
|
||||||
|
check removed (4 failures), instance-name path removed (2), `data.offset` ignored
|
||||||
|
in `tf::target` (1), end-label exclusion removed (3), `super` → base removed (1),
|
||||||
|
the caret rule (`offset - 1`) removed (1), the overlay acceptance in the declaring
|
||||||
|
file removed (1). **Survived: both ambiguity fallbacks** (finding 4).
|
||||||
|
|
||||||
|
**Byte-identity vs master 41a9091.** Built 41a9091 in a scratch `git worktree`
|
||||||
|
(removed afterwards). Ran `prepareCallHierarchy` at **every character offset** of
|
||||||
|
three projects (3 137 positions: the dev's `sub`/`top`/`cls` trio; an attack
|
||||||
|
project with packages, classes, DPI, generate and macros; and a module-hierarchy
|
||||||
|
project with interfaces, a program, multi-instance statements, generate `for`/`if`,
|
||||||
|
parameter overrides, an undeclared module and a `bind`). Wherever the old server
|
||||||
|
answered (124 positions), the new answer is identical, byte for byte. The
|
||||||
|
`incomingCalls`/`outgoingCalls` answers on all 15 distinct module items are also
|
||||||
|
identical. The old server answered 124 positions and the new one answers 2 832.
|
||||||
|
|
||||||
|
**Other features unchanged.** On two projects, compared `documentSymbol` per file
|
||||||
|
plus `definition`, `references` and `hover` at every identifier (1 340 queries)
|
||||||
|
between the old and new binaries: **0 differences**.
|
||||||
|
|
||||||
|
**Attacks over the wire** (`probe.py`, debug build unless noted). Each was as the
|
||||||
|
README describes, unless it is listed under findings:
|
||||||
|
- Ambiguity. A module two files declare gives both items, and each has the
|
||||||
|
instantiating module as its caller. A package two files declare (`pz` in
|
||||||
|
`z1.sv`/`z2.sv`): a call prepares both items, as `definition` answers 2; incoming
|
||||||
|
is empty for both (the declaring-file fallback).
|
||||||
|
- A function and a module with the same name (`module g` plus `function g` in
|
||||||
|
`host`). On the instantiation's module name and on its instance name, the answer
|
||||||
|
is module `g` (MODULE, no `data`). On the call `g(1)` and on the declaration, it
|
||||||
|
is function `g` (FUNCTION, `detail` `host`). A module that nothing declares, named
|
||||||
|
like an in-scope function (`nope u1 ();`), answers the enclosing module, never
|
||||||
|
the function.
|
||||||
|
- Shadowing. In task `sh`, the local `int g`, written or read, prepares `sh`, never
|
||||||
|
the function `g`.
|
||||||
|
- `extern` prototype, out-of-body `c::ext` name, its end label: all prepare the
|
||||||
|
prototype, and outgoing lists the callees in the out-of-body body (`hook`,
|
||||||
|
`helper`).
|
||||||
|
- `push_back`, `.size()`, `randomize()`, `this.randomize() with {…}`: the
|
||||||
|
enclosing method, with no crash and no callee listed.
|
||||||
|
- DPI imports (`import "DPI-C" function int c_add…`, a `context task`): FUNCTION
|
||||||
|
or TASK items, `detail` none, incoming the module that calls them, outgoing
|
||||||
|
empty. That is a sensible answer.
|
||||||
|
- `$display` is the enclosing module. A call in a parameter default
|
||||||
|
(`#(parameter int P = cf(3))`), a `localparam`, a continuous `assign`, and an
|
||||||
|
`assign` in a generate `for` are all credited to the module. A call at file scope
|
||||||
|
is dropped.
|
||||||
|
- Caller attribution. A call in `initial`, `final`, an `always_comb` named block or
|
||||||
|
a `fork` named block is credited to the enclosing module, method or task. A call
|
||||||
|
in a package `localparam` is credited to the PACKAGE item, and one in a class
|
||||||
|
property initializer to the CLASS item. Qualified `pk::kf` is the same function.
|
||||||
|
- Stale and foreign items (finding 3 covers the one gap). These all answer empty
|
||||||
|
or correct, never a panic or a wrong file: `offset` 99 999 999, a nonexistent
|
||||||
|
name, `kind` `class`/`package`/`task` on a function, selection range line 99 999
|
||||||
|
or character 4e9, `untitled:` / `/etc/hosts` / a directory / a missing file as
|
||||||
|
URI, `data` missing / null / a string, extra fields in `data`.
|
||||||
|
- Large-file mode: in a 5 MB buffer, call prepare, type prepare and the module name
|
||||||
|
all answer `null`, and a package function's incoming skips it.
|
||||||
|
- UTF-16: ranges after `✓` comments are correct (character 18 where the UTF-16
|
||||||
|
count is 18).
|
||||||
|
- Type hierarchy: a method body and an out-of-body body give the class; a class
|
||||||
|
inside a module gives the class; a module body and a package body give `null`.
|
||||||
|
|
||||||
|
**Timing.** Release build, 200 closed files each calling `big_pkg::pf` 31 times
|
||||||
|
from a module and 10 functions, with only `pkg.sv` and `m000.sv` open:
|
||||||
|
- prepare: 2 ms;
|
||||||
|
- `incomingCalls`: 76 / 65 / 55 ms over three runs, 2 200 callers and 6 200 ranges.
|
||||||
|
This equals `references` (6 200 locations, 23 ms).
|
||||||
|
- Server RSS: 13 MB, then 69 MB after the first incoming, then flat.
|
||||||
|
- Debug build: incoming 325 / 312 / 302 ms, references 89 ms, 74 MB.
|
||||||
|
|
||||||
|
The README's "each referencing closed file is parsed once" holds for incoming. It
|
||||||
|
does not hold for outgoing (finding 2).
|
||||||
|
|
||||||
|
**Code review.** Production lines (non-blank, non-comment, before `mod tests`):
|
||||||
|
`hierarchy.rs` 212, `hierarchy/tf.rs` 216, `hierarchy/calls.rs` 246,
|
||||||
|
`type_hierarchy.rs` 189. All functions are under 50 lines. Production code has no
|
||||||
|
`unwrap`/`expect`/`panic`, no new indexing (the one slice in `type_hierarchy.rs`
|
||||||
|
predates the lane), and no byte slicing of text (`Positions::offset` clamps). The
|
||||||
|
README test counts (24 / 3 / 4) match the code.
|
||||||
|
|
||||||
|
**Findings**
|
||||||
|
|
||||||
|
1. **Medium: a Verilog result-variable read is counted as a recursive call.**
|
||||||
|
`crates/lucisv_server/src/hierarchy/calls.rs:208-227` (`is_call`). The unit
|
||||||
|
test `calls.rs:337-354` pins `+ f` (a bare read) as a call. Reproduction:
|
||||||
|
```verilog
|
||||||
|
module lg (output integer o);
|
||||||
|
function integer clog2(input integer v);
|
||||||
|
begin
|
||||||
|
clog2 = 0;
|
||||||
|
while (v > 1) begin
|
||||||
|
clog2 = clog2 + 1;
|
||||||
|
v = v >> 1;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
endfunction
|
||||||
|
initial o = clog2(16);
|
||||||
|
endmodule
|
||||||
|
```
|
||||||
|
`outgoingCalls(clog2)` = `[clog2 @6]`, and `incomingCalls(clog2)` lists `clog2`
|
||||||
|
as its own caller at line 6. That is a false recursion on one of the most common
|
||||||
|
Verilog-2001 idioms. Inside a function's own body, its name without a following
|
||||||
|
`(` is the result variable, not a call. That is a token-level rule of the same
|
||||||
|
kind as the existing `assigned` check, and it applies to functions only.
|
||||||
|
2. **Medium (performance): `outgoingCalls` parses a closed callee file once per
|
||||||
|
distinct callee.** `calls.rs:272` calls `tf::def_item`, which calls `tf.rs:243`
|
||||||
|
`load_path`, which calls `Document::new` for every callee. Reproduction: a
|
||||||
|
236 KB closed package with 300 functions, and a caller function `all` that calls
|
||||||
|
all 300. In the release build, `outgoingCalls(all)` takes **3 503 ms**, and
|
||||||
|
34 ms once the package is open. The cost is about 12 ms per callee for this file
|
||||||
|
size. A per-request cache of loaded analyses keyed by path would make it one
|
||||||
|
parse per file, as incoming already is.
|
||||||
|
3. **Low-Medium: after an edit, a stale item silently resolves to a different
|
||||||
|
function with the same name.** `crates/lucisv_server/src/hierarchy/tf.rs:293-295`
|
||||||
|
(the `candidates.first()` fallback). Reproduction: `module ma` and `module mb`,
|
||||||
|
each declaring `log2`. Prepare `mb`'s `log2`, then `didChange` to add 3 comment
|
||||||
|
lines at the top. `incomingCalls` with the old item answers **`ma`'s** caller
|
||||||
|
(line 9). After renaming `mb`'s function to `lg`, the old item also answers
|
||||||
|
`ma`'s callers. The README documents this fallback (Assumptions, "the module
|
||||||
|
rule"), but its own Goal says two functions of one name are ordinary. For
|
||||||
|
modules the fallback is rarely wrong; for functions it often is. Suggestion:
|
||||||
|
fall back to the first candidate only when it is the only one, or break the tie
|
||||||
|
on the item's `detail` (container name).
|
||||||
|
4. **Low (coverage): the two ambiguity fallbacks are untested.**
|
||||||
|
`calls.rs:79-81` (`references_are_ambiguous`) and `calls.rs:86-88`
|
||||||
|
(`names_it_ambiguously`). Each removed alone, the 144 hierarchy tests stay green.
|
||||||
|
The README claims "the same ambiguity contract" as references. A test with two
|
||||||
|
files declaring one package, and the user file closed and then open, would pin
|
||||||
|
it.
|
||||||
|
5. **Info: a cursor on a macro use gives the enclosing module, and a call inside a
|
||||||
|
macro body is not listed.** For `` `CALL_IT(1) `` expanding to `cf(1)`,
|
||||||
|
incoming(`cf`) omits that line. This matches references, since there is no
|
||||||
|
macro expansion, but it is not in the README's Limits.
|
||||||
|
6. **Info: an ambiguous wildcard import resolves to the first package.** With
|
||||||
|
`import pa::*; import pb::*;` and both declaring `f`, `f(1)` prepares `pa::f`
|
||||||
|
and is listed in its incoming. This is the semantic layer, and `definition` and
|
||||||
|
`references` give the same answer. It is not this lane's.
|
||||||
|
7. **Info: the doc row "a class body outside its methods → null" does not apply to
|
||||||
|
a class declared inside a module.** There the enclosing module answers. This is
|
||||||
|
consistent with the "innermost enclosing module" rule; the table row could say
|
||||||
|
"a file-level class".
|
||||||
|
|
||||||
|
**Fixes made by QA:** ticked the `tests/e2e.rs` Status item, since the lead
|
||||||
|
flipped both assertions and the suite is green. No code changed.
|
||||||
|
|
||||||
|
## Review
|
||||||
|
|
||||||
|
**2026-10-14 — lead.** Accepted after one rework. The user's report (Show
|
||||||
|
Call Hierarchy empty in VS Code) was a prepare that answered only on a
|
||||||
|
module name; it now answers from any position inside a module, function or
|
||||||
|
task, and functions/tasks are call-hierarchy nodes of their own. QA (Opus)
|
||||||
|
confirmed the old module answers byte-identical at 3 137 positions and no
|
||||||
|
change in outline/definition/references/hover at 1 340 queries; its two
|
||||||
|
mediums (result-variable reads counted as recursion; outgoing re-parsing a
|
||||||
|
closed file per callee, 3.0 s → 18 ms) and the stale-item fallback are
|
||||||
|
fixed with tests. The e2e handshake is granted: two assertions that pinned
|
||||||
|
the old `null` now assert the new answers. The one surviving mutant (the
|
||||||
|
`declined` call in `other_files`) guards a branch the index makes
|
||||||
|
unreachable today; kept, and recorded as an Assumption. Merged onto master
|
||||||
|
with the lane-B references view; gates re-run on the merged tree.
|
||||||
|
|
||||||
@@ -232,6 +232,15 @@ lucisv-server qa_perf_worst_case -- --ignored --nocapture`).
|
|||||||
interface and program instantiations as their own node kind, and any
|
interface and program instantiations as their own node kind, and any
|
||||||
whole-tree "show me the design" view — this milestone is exactly the
|
whole-tree "show me the design" view — this milestone is exactly the
|
||||||
two directions of the module graph.
|
two directions of the module graph.
|
||||||
|
- [x] **Extended (call-hierarchy-everywhere, 2026-10-14):** `prepare` now
|
||||||
|
answers from an instance name, from inside a module body, and for
|
||||||
|
functions and tasks (declaration, call, end label, body), which gained
|
||||||
|
their own `incomingCalls`/`outgoingCalls`. Module items and their two
|
||||||
|
directions are unchanged where they already answered; the "anything
|
||||||
|
else is `null`" contract above is superseded — see
|
||||||
|
`docs/features/call-hierarchy-everywhere/README.md`. The bind-target
|
||||||
|
gap the Review recorded stays a gap: the cursor there now prepares the
|
||||||
|
module the `bind` is written in.
|
||||||
|
|
||||||
## Work log
|
## Work log
|
||||||
|
|
||||||
|
|||||||
@@ -283,6 +283,12 @@ UVM class names are long and specific, and no such name exists in the corpus.
|
|||||||
- [ ] Not done, deliberately: chasing a chain server-side (the client drives
|
- [ ] Not done, deliberately: chasing a chain server-side (the client drives
|
||||||
it), a whole-tree "show me every class" view, and typedef/struct
|
it), a whole-tree "show me every class" view, and typedef/struct
|
||||||
hierarchies — SystemVerilog has no inheritance for them.
|
hierarchies — SystemVerilog has no inheritance for them.
|
||||||
|
- [x] **Extended (call-hierarchy-everywhere, 2026-10-14):** `prepare`
|
||||||
|
inside a class body (a property, a method body, a keyword, `this`)
|
||||||
|
answers the innermost enclosing class, and on `super` its base. The
|
||||||
|
"anything else is `null`" contract above holds now only outside every
|
||||||
|
class; classes-only scope is kept — modules stay off this view. See
|
||||||
|
`docs/features/call-hierarchy-everywhere/README.md`.
|
||||||
|
|
||||||
## Work log
|
## Work log
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user