hierarchy
M11 of the refactoring plan (docs/features/refactor/README.md), TODO.md §8:
module hierarchy both directions, over LSP callHierarchy.
Goal
"Who instantiates this module?" and "what does this module instantiate?" are
the two questions a hardware engineer asks about a design they did not write,
and until now lucisv could answer neither without a grep. LSP already has the
shape for both: its call hierarchy is a graph of callers and callees, and a
design's module hierarchy is that same graph under different names — the
modules are the nodes and an instantiation is the call. So
textDocument/prepareCallHierarchy picks a module out of the text under the
cursor, callHierarchy/incomingCalls answers "who instantiates X" and
callHierarchy/outgoingCalls answers "what does X instantiate", and every LSP
client draws the tree with its own hierarchy view — no editor code at all.
Each request answers one hop. The client drives the expansion, so
recursion needs no handling here beyond not crashing: a module that
instantiates itself simply appears again one level down, and an a → b → a
pair unrolls as far as the user keeps clicking.
Assumptions
- An instantiation is the call, and the enclosing module is the caller. There is no other candidate: a Verilog module has no call sites of its own, and its instances are exactly the edges of the design tree.
- The walk is by name. An instantiation of
fifowritesfifowhere the parser recordsInstantiation::module, whatever its connection list looks like — named, ordered,.*, an instance array, several instances in one statement, or abind. Nothing here reads the connections at all. - A scope-qualified instantiation (
pkg::mod u ()) is not matched. The parser stores that name with its::glued, so it does not equalmod, and the workspace index models no package-scoped module lookup either (docs/features/workspace-index/README.md). Matching on the trailing segment would silently claimother_pkg::fifoas an instantiation offifo. Not seen anywhere in the corpus; if it ever matters, it needs the index to answer the qualified name, not a string split here. - One
Instantiationis one call site, however many instances it declares.sub u1 (), u2 ();writessubonce, and thefromRangeis that one name — which is the range a client highlights, and the rangetextDocument/referencesreports for the same text. - An instantiation with no enclosing module has no caller to report.
Illegal SystemVerilog, reachable through the tolerant parser, and there is
no honest
fromitem for it, so it is dropped. - Ambiguity is answered differently in the two directions, on purpose.
preparereturns every declaration of an ambiguous name — LSP's return type is a list, and the client asks the user which one they meant, exactly astextDocument/definitiondoes.outgoingCallsskips an ambiguous or unknown target silently: a hierarchy node has nowhere to ask a question, and a node pointing at the wrong one of two same-named modules would send the user to the wrong file with no way to tell. - Two declarations of one name in one file resolve to the first. The index's span picks between them when it is still accurate; a buffer edited since the last index rebuild falls back to the first of that name rather than answering nothing.
- A cursor immediately after the last character of a name is on that name.
TextRange::containsexcludes the end, which is right for a span of text and wrong for a caret — that is where a double-click and an end-of-word motion leave it. - The scope ladder decides which files are searched.
incomingCallsreadsWorkspace::sources(), so a file a filelist or anexcludekeeps out of the index instantiates nothing, exactly as it references nothing (docs/features/references-nav/README.md). - Open buffers beat disk. The same
sources()overlay every other cross-file answer uses, so an instantiation just typed and not yet saved is already a caller. - Nested module declarations. Legal SystemVerilog; today's parser recovers them into sibling items rather than nesting them. The walk carries the innermost enclosing declaration either way, so both spellings attribute correctly and neither needs a special case here.
`ifdef/`elsearound an instantiation reports both arms. The parser does not evaluate the condition — each arm's items land in the same flat list,Directiveitems and all (vlog_parser'sparse_item_kind) — somodule ...ifdef A sub_a u1();else sub_b u1();endifgivesoutgoingCallstwo entries,sub_aandsub_b, even though only one is ever really built. This is not the same failureinlay.rsguards against: a hint draws one confident, potentially-wrong label, where a hierarchy edge is a fact about the *text* ("this instantiation exists, guarded"), and showing both is the honest answer to a question lucisv cannot resolve without evaluating defines. Found in QA (2026-08-25); pinned byhierarchy::tests::qa_ifdef_instantiation_both_arms_are_reported_undisclosed_in_the_readme`.
Handshakes
- Consumes
crate::instantiations— new in this change, and the shared instantiation walk:sites(every instantiation, with the module it is written inside) anddeclarations(every module declaration, with the extent of itsmodule ... endmodule). It is the walk that used to live privately ininlay.rs, lifted rather than copied, with the enclosing declaration threaded through it.inlay.rsnow readssites(...)and ignores the owner; its behavior is byte-identical and its 34 tests are the regression net for that claim. - Consumes
vlog_parser—parse_source_tolerantfor every file that is not the open buffer,ast::Module/Instantiation(read-only),Item::span,LineIndex. Nothing new is asked of the crate. - Consumes
vlog_semantic::WorkspaceIndex—units(name)andpath(file), to turn a module name into the file that declares it. The index records what a file declares and not what it instantiates: there is no edge table, which is whyincomingCallswalks files rather than querying. Adding such a table is a real option and is recorded as backlog below rather than assumed here. - Consumes
crate::state::Workspace—document,index,text_of,sources. Nothing instate.rswas changed; the workspace stays immutable through all three handlers, and no cache was added. - Promises
lucisv_server—hierarchy::{prepare, incoming, outgoing}never panic, never return an item whoseselectionRangeis outside itsrange, and never return ato/fromitem for a module the workspace does not really declare. editors/vscodeneeds no change.vscode-languageclient9.0.1 ships the call-hierarchy feature and enables it off the advertised capability; the extension sets noinitializationOptionsthat would suppress it, and the Vim/Neovim client hasvim.lsp.buf.incoming_calls()/outgoing_calls()built in.editors/vscode/smoke.jschecks a fixed four-name capability list and was deliberately left untouched (it is editor-packaging's file) — it still passes. If the lead wantscallHierarchyProviderin that list, it is a one-line addition there.
What it looks like
hier_mid.sv:
module hier_mid;
hier_sub u_a (.clk(1'b0));
hier_sub u_b (.clk(1'b1));
endmodule
Cursor on hier_mid anywhere — its own declaration, or the hier_mid of an
instantiation in hier_top.sv — and the hierarchy view shows:
incoming (who instantiates hier_mid) outgoing (what hier_mid instantiates)
hier_top hier_top.sv:2 hier_sub hier_sub.sv:1
hier_mid.sv:2, hier_mid.sv:3
One entry per calling module, not per instantiation: two instantiations of
hier_sub in one module are one outgoing call carrying two fromRanges, and
the client highlights both.
Cost
Release build, this machine, the checked-in 860-file corpus:
| request | measured |
|---|---|
incomingCalls for prim_flop_2sync (25 calling modules across the corpus) |
56 ms |
— of which reading the 860 files (Workspace::sources()) |
51 ms |
| — of which the substring prefilter over all of them | 0.26 ms |
| — of which parsing + walking the 26 files that mention the name | ~5 ms |
outgoingCalls for the corpus's densest module (uart_reg_top.sv, 63 instantiation sites, 4 distinct resolvable targets) |
2.2 ms |
the same incomingCalls in a debug build |
106 ms |
Two things the table says. First, incomingCalls costs 4× less than M7's
textDocument/references on the same corpus (218 ms) even though it answers
a superset of the question — it needs the caller, not just the span. The
reason is the prefilter: a module that is instantiated somewhere has its name
written there, so a file whose text does not contain the name is skipped
before it is parsed, and 834 of 860 files are. Second, what is left is
almost entirely file I/O — sources() reads every in-scope file whether
it will be parsed or not. That is the shared cost of every cross-file answer
in this server, and the place a future win lives (see backlog); nothing in
this feature can shave it alone.
prepare and outgoingCalls never walk the workspace at all: they parse the
buffer and, at most, one file per distinct instantiated module.
The 4× claim is specific to prim_flop_2sync, not general. It holds
because the substring prefilter skips 834 of 860 files for that name. QA
(2026-08-25) measured the prefilter's worst case: a module name that is a
substring of nearly every file (a single letter, in the probe) admits close
to all 860 files for parsing regardless of whether any of them really
instantiate it. Release, this machine: 206 ms — close to, not below,
references's 218 ms. Still correct (zero calls, since no such module is
declared), and still not a hang, but the speed claim is a property of the
name being looked up, not a guarantee incomingCalls gives universally.
Real single- or two-letter module names are not a corpus pattern seen so far;
recorded here rather than in the backlog because it is a measurement, not a
design gap. See hierarchy::tests::qa_perf_worst_case_common_word_module_name
(#[ignore]d, run with cargo test --release -p lucisv_server --bin lucisv-server qa_perf_worst_case -- --ignored --nocapture).
Status / TODO
crates/lucisv_server/src/instantiations.rs: the shared walk, lifted out ofinlay.rswith the enclosing declaration threaded through itcrates/lucisv_server/src/inlay.rs: reads the shared walk, behavior unchanged (its own 34 tests re-run green untouched)crates/lucisv_server/src/hierarchy.rs:prepare,incoming,outgoingcallHierarchyProviderinmain.rs; three dispatch arms inserver.rsprepareon a declaration / on an instantiation / on anything else (null), including an instance name, a connected expression, a keyword, a package and a module nothing declares- Ambiguity: every declaration from
prepare, silence fromoutgoing - Generate regions,
bind, instance arrays, several instances in one statement and ordered connection lists found in both directions - Self-instantiation: both directions answer one hop and neither hangs
- Scope ladder and unsaved-buffer overlay honoured by
incomingCalls - UTF-16 positions, an untitled buffer, a file that has since moved, a buffer that does not parse
- Unit tests (25 in
hierarchy.rs, 7 ininstantiations.rs, 1 capability test inmain.rs) and one e2e stdio round trip: prepare → incoming → outgoing across three files - Cost measured over the 860-file corpus, with the I/O split out
cargo fmt --all -- --check,cargo clippy --all-targets,cargo test --workspace,editors/vscode/smoke.jsdocs/features/lucisv-server/README.mdcapability table + work log- Not done, backlog: an instantiation edge table in
WorkspaceIndex, built with the index, which would makeincomingCallsa map lookup and cost one extra tree walk per file at index time. Worth doing when something else wants the same edges (a design-tree view, an unused-module lint); today one request in 56 ms does not justify widening the index's contract. - Not done, deliberately: type hierarchy (
typeHierarchy) for classes, interface and program instantiations as their own node kind, and any whole-tree "show me the design" view — this milestone is exactly the two directions of the module graph.
Work log
-
2026-08-25 (dev) — read
workspace-index,lucisv-server,references-navandinlay-hintsREADMEs, thennav.rs,inlay.rsandworkspace.rsbefore writing anything.Finding that shaped the design: the index holds no instantiation edges.
WorkspaceIndexrecords what each file declares (units and their exported members) and nothing about what it uses. So "who instantiates X" cannot be a lookup, and the two honest options were M7'sfind_referencesmachinery or a fresh walk of the in-scope files.Design decision 1 — walk, don't reuse
find_references. References answer where a name appears; an incoming call needs which module the appearance is inside, which references cannot say. Reusing them would have meant collecting spans and then parsing every hit file a second time to attribute each span to a module — strictly more work than one walk that carries the owner along. Measured after the fact: 56 ms againstfind_references's 218 ms on the same corpus, because the walk can skip a file on a substring test before parsing it and references cannot (it must analyze to know what a name resolves to).Design decision 2 — the shared walk carries the owner, and
inlay.rsignores it. The brief asked for theinlay.rswalk to be factored rather than copied. The lifted version threads the innermost enclosingDeclthrough the recursion;inlay.rsmaps straight past it. That also gave outgoing calls their boundary for free: walking a module's items makes the instantiations written directly in it the ones whose owner isNone, so a neighbouring or nested module's instantiations are never claimed as this module's.inlay.rs's 34 tests were not touched and are green, which is the evidence the factoring changed nothing.Design decision 3 — the substring prefilter.
callers_inreturns early when the file's text does not contain the module's name. This is not a heuristic: an instantiation offifowritesfifo, so a file that does not contain those four bytes cannot contain one. It turns the walk from 860 parses into 26, and is the whole reason this request is cheaper than references.Ambiguity is answered two different ways, which is worth stating plainly because it looks inconsistent:
preparereturns every declaration (the protocol takes a list and the user is there to choose, exactly as go-to-definition does), andoutgoingskips (a node in a tree has nobody to ask, and a wrong node is unfalsifiable to the reader — the same argumentinlay.rsmakes for drawing no hint).Nested modules. The walk supports them; today's parser recovers a nested
moduleinto sibling items instead of nesting them. Rather than write tests asserting a shape the parser does not produce, the equivalent case is pinned with two modules in one file — the real, legal, common shape that the owner attribution has to get right — plus one test that both names are found however the nested form parses.Files touched. New:
crates/lucisv_server/src/instantiations.rs,crates/lucisv_server/src/hierarchy.rs, this README. Edited:crates/lucisv_server/src/inlay.rs(its private walk removed, the shared one called; no behavior change),crates/lucisv_server/src/main.rs(two module declarations, the capability, two tests),crates/lucisv_server/src/server.rs(three dispatch arms and their imports),crates/lucisv_server/tests/e2e.rs(one new test),docs/features/lucisv-server/README.md(capability table and work log).Not touched, deliberately:
TODO.mdand the umbrella checklist indocs/features/refactor/README.md(the lead's, per the brief),nav.rs,state.rs,vlog_semantic,vlog_refactor,editors/. No version bump.Gates.
cargo fmt --all -- --checkclean,cargo clippy --all-targetszero warnings,cargo test --workspacegreen at 1463 passed, 0 failed (1429 before; +34 = 25 inhierarchy.rs, 7 ininstantiations.rs, 1 inmain.rs, 1 e2e round trip).node editors/vscode/smoke.js target/release/lucisv-server: OK. No new dependencies. No commits.
QA log
-
2026-08-25 (QA) — read this README,
inlay-hints/README.md(for the factoring claim and its ownifdefprecedent),instantiations.rsandhierarchy.rsend to end before touching anything.Gates.
cargo fmt --all -- --check,cargo clippy --all-targets --workspace,cargo test --workspaceall clean before any QA change — 1463 passed, 0 failed, matching the dev's number exactly (summed the per-cratetest resultlines by hand to be sure).node editors/vscode/smoke.js target/release/lucisv-server— OK, against a freshly rebuilt release binary. Independently re-ran the dev's own corpus perf test in release: 25 callers, 63.7 ms — same order as the claimed 56 ms (normal run-to-run variance), same caller count.Factoring check.
git diff HEAD -- crates/lucisv_server/src/inlay.rs: the privateinstantiations/walk/blockfunctions (previously at the bottom of the file) are deleted in full; the only other change is the call site (instantiations(&doc.tree)→instantiations::sites(&doc.tree.items), with.instfield access) and one internal test updated the same way. Nothing else in the file moved. Readinstantiations.rs'swalk/blockside by side with the deleted code: identical control flow, node-for-node, withOption<Decl>threaded as an extra parameter andownerattached to eachSite. The verbatim claim holds. Confirmed separately thatinlay.rs's 34 tests are untouched (diff shows no test-body edits besides the one call-site change) and green.Break-it testing. Added 11 tests to
hierarchy.rs(10 permanent, 1#[ignore]d perf probe) and one e2e test, all listed below with what they found. All pass; full suite re-green after at 1474 passed, 4 ignored, 0 failed (1463 + 10 hierarchy.rs + 1 e2e; the 11th QA test is the ignored perf probe).- Generate
forwith a genvar-indexed instance. Covered by the dev's ownincoming_calls_reach_generate_regions_bind_and_instance_arrays— oneInstantiationnode inside the loop body gives onefromRangeregardless of the genvar's range, which is correct under the "one AST node is one call site" assumption. Re-verified by hand; no new test needed. bindin another file, target ≠ owner. New testqa_bind_owner_is_the_module_containing_the_directive_not_the_bind_target—bind top chk u_chk();written insidemodule harnessin a third file:incoming(chk)namesharnessas the caller, nottop. This is the honest answer given the feature's own "instantiation is the call, enclosing module is the caller" assumption —bind's effect targetstop, but the instantiation text sits inharness, and lucisv only ever reads text. Not a bug; not previously tested at this granularity (the dev's own bind test has target == owner, which cannot distinguish the two).- A module name that is a word in a comment elsewhere. New test
qa_prefilter_over_admits_but_walk_rejects_a_comment_only_mention—widgetappears only inside// this file mentions widget only in a commentinb.sv. The substring prefilter admitsb.svfor parsing (as designed — it can't know the difference from source text alone), but the walk'ssite.inst.module != namefilter means no false incoming call. Confirmed correct; no over-admission reaches the client. - Instantiation under
`ifdef. Finding, MEDIUM, documented.outgoing(top)for`ifdef A sub_a u1(); `else sub_b u1(); `endifinsidetopreturns bothsub_aandsub_bas real calls — the parser does not evaluate`ifdefat the item level (confirmed againstvlog_parser::parser::parse_item_kind; both arms become ordinaryInstantiationitems in source order). This is arguably the honest answer — lucisv cannot know which arm is live and showing both is not a single wrong claim the way a mis-ordered inlay hint would be — but it was undisclosed: no Assumption, Handshake, or test mentioned`ifdefanywhere in this feature, despiteinlay-hints/README.mdtreating the identical directive shape as a first-class, tested case one milestone earlier. Fix applied (documentation only, no behavior change): added an Assumptions bullet explaining the policy and why it differs frominlay.rs's silence. Pinned by new testqa_ifdef_instantiation_both_arms_are_reported_undisclosed_in_the_readme. - Same module instantiated inside a
package. New testqa_instantiation_in_a_package_does_not_crash— illegal-ish SystemVerilog, reachable through the tolerant parser. No panic; no assertion on the answer itself (incomingreturns empty, sincePackageitems aren't part of whatoutgoingwalks either way) — survival was the point. - Outgoing, ambiguous target, no leak. New test
qa_outgoing_ambiguous_does_not_leak_fromranges_into_resolved_entries— a module instantiating bothsub(resolvable) anddup(declared twice, ambiguous) gets exactly one outgoing call, forsub, and itsfromRangesare exactlysub's two sites —dup's site does not leak in. Confirms the dev'sfilter_mapinhierarchy.rs:112-120drops the whole(name, spans)pair together, not just theto. - Outgoing, nested module declaration boundary. New test
qa_outgoing_nested_module_declaration_boundary, using the dev's own pinned fixture shape frominstantiations.rs(module outer; module inner; ... endmodule endmodule) driven through the publichierarchyAPI rather than the private walk:outgoing(outer)is empty andoutgoing(inner)claimssub. The parser's sibling-recovery shape does not leakinner's instantiations intoouter's answer. - Prepare on a string or comment. New test
qa_prepare_on_a_string_or_comment_is_null— cursor inside// sub lives hereand inside"sub"both preparenull. Correct: neitherdeclarations()norsites()covers comment or string text, by construction. - Prepare on a bind target. Finding, LOW-MEDIUM, documented, not
fixed. Cursor on
topinbind top chk u_chk();— a real reference to a really-declared module — preparesnull. Neitherdeclarations()(only seesmodule ...headers) norsites()(a bind's site span ischk's, the instantiated module, not the target) covers that text. This fails safe rather than corrupting anything, and is arguably a defensible scope boundary (the bind's target module is not itself an instantiation site), but it was untested and undocumented, and a user right-clicking a bind target reasonably expects a hierarchy view. Not fixed — this is a design call for the lead, not an unambiguous typo-class fix. Pinned as today's actual behavior byqa_prepare_on_a_bind_target_module_name_is_currently_null, named to make clear it is not being endorsed. - Cycles,
a → b → a, two hops. New testqa_cycle_a_to_b_to_a_two_hops_no_hang—outgoing(a)→b,outgoing(b)→a,incoming(b)→a, each a clean one-hop answer, no recursion, no hang. Confirms the "client drives the expansion" design holds under an actual two-node cycle, not just self-instantiation (which the dev already covers ina_self_instantiating_module_is_its_own_caller_and_does_not_hang). - Consistency:
incoming(X)vsoutgoing(parent). New testqa_consistency_incoming_x_matches_outgoing_parent_of_x, run over the three-file fixture (hier_mid/hier_top/hier_othershape): for every callerincoming(sub)names,outgoing(that caller)has a matchingsubentry with the exact samefromRanges(sorted, compared pointwise). This is the property that makes the two directions honest with each other, and it holds. - Perf, worst case. Finding, MEDIUM, documented. The realistic-case
corpus number (56 ms, re-verified at 63.7 ms) is not a general bound: a
module name that is a substring of nearly every file (a single letter,
in the probe) defeats the prefilter almost entirely. Release measurement:
206 ms, versus the 218 ms
referencesbaseline the feature claims a 4× win over — i.e. the worst case erases nearly all of the claimed advantage. Still correct and still fast enough to not be a hang, but the "4× cheaper" framing in Cost read as general and is not. Fix applied (documentation only): added a caveat paragraph to Cost quantifying this, and keptqa_perf_worst_case_common_word_module_name(#[ignore]d, matching the dev's own pattern for corpus-gated perf tests) as the reproduction. - e2e, incoming with two
fromRanges. The dev's own e2e test has twofromRangesonly on theoutgoingside; itsincomingcase is single-range. New, independent testqa_incoming_calls_with_two_fromranges_round_trips_over_the_wirespawns the real binary twice (one session toprepare, a second, fresh session to send the resulting item toincomingCalls— closer to what a real client does across two requests than reusing one open connection):mid2instantiatessub2twice, andincomingCallsreturns one call frommid2with bothfromRanges, at the right lines, over the wire.
Everything else tried to break, and did not, no new test needed:
- Instance array (
sub u [3:0] (...)) and several instances in one statement. Already covered by the dev's ownincoming_calls_reach_generate_regions_bind_and_instance_arrays; independently re-derived by hand againstInstantiation::instancesand agree it is one call site regardless of instance count. - UTF-16 positions, an untitled buffer, a moved file, a buffer that does
not parse. Dev's own tests (
positions_are_utf16_units_on_a_line...,an_untitled_buffer_prepares_from_itself,an_item_naming_a_file_that_is_gone_answers_with_no_calls,a_buffer_that_does_not_parse_invents_no_calls) re-run and agree with the assertions as written. - Cursor on an instance name (
u1), not the module. Already covered by the dev'sa_position_on_no_module_prepares_nothing. Assessed:nullis right — an instance name is not module text under any of this feature's own assumptions, and the alternative (walking outward to the nearest enclosing instantiation) is a different, undiscussed feature.
Verdict: ship-after-fixes. The two MEDIUM findings (
ifdefbehavior, worst-case prefilter perf) are addressed the same way the dev's owninlay-hintsQA round handled itsifdeffinding in spirit — except here the underlying behavior is judged acceptable and the fix is documentation, not code, because unlike inlay hints a hierarchy edge is a fact about text ("this instantiation exists, conditionally") rather than a single confident claim that can be wrong. The LOW-MEDIUM bind-target finding is a real gap but not unambiguous enough for QA to fix unilaterally (it is a scope question, not a typo) — left for the lead. Nothing else found rises above documentation, and every new claim added above is now pinned by a test. No commits made. - Generate
Review
2026-08-25 — lead. Reviewed after QA's verdict (doc-only fixes,
already applied); gates run independently (1474 tests, 0 failures). The
two design calls that matter are both right: the walk over M7's
references (an incoming call needs the enclosing module, which
references cannot attribute — and it measured faster), and owner
threading giving outgoing its module boundary for free. QA verified the
factoring verbatim and, most valuably, the incoming/outgoing consistency
property on a fixture — the check that keeps the two directions honest.
Rulings on QA's findings: the ifdef both-arms answer is accepted and
now disclosed (consistent with the parser's no-evaluation stance; unlike
inlay hints, hierarchy answers are lists the user inspects, so listing
both arms is honest rather than wrong); the prefilter-defeating-name
cost caveat is accepted; prepare-on-bind-target returning null is an
accepted completeness gap — recorded here as backlog rather than fixed,
since the right answer needs a design decision about whether a bind
target is a "call" at all. Accepted; M11 checked off in the umbrella
plan and TODO §8.