From 203e9b1a4f8e63effb1cd00f408410927bff02bc Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 26 Aug 2026 21:35:36 -0700 Subject: [PATCH] =?UTF-8?q?LSP=20=C2=A79c:=20type=20hierarchy=20over=20ext?= =?UTF-8?q?ends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit textDocument/prepareTypeHierarchy + typeHierarchy/supertypes/subtypes for SystemVerilog classes. Supertypes is one computed offset into the existing resolution machinery — the overlay promotion made cross-file bare class names answerable, and the offset is the LAST byte of the extends name span so pkg::base lands in the tail's reference, never the package's. Subtypes is a workspace census on the callers_of_each pattern (one sources() pass, prefilter, deterministic sort), matching the base name as written — 0 of the corpus's 270 extends clauses are qualified, and the asymmetry with supertypes is documented and pinned from both directions, including the same-name/different-file consequence. Ambiguous bases answer every declaration, like definition. Modules stay on callHierarchy by scope ruling. lsp-types 0.97 has no server-side typeHierarchyProvider field, so initialize_value() inserts the one key into the serialized result — QA's strip-and-compare test proves every other key survives with identical values. QA also traced the parser to show the degenerate extends spans the code guards against cannot be constructed, corrected two README figures the lead applied (the 309 extends count did not reproduce; 270 does), and pinned the generate-block walk gap as a scoped choice. Interface classes stay blocked on the parser, pinned. 45 tests added (dev 33 + QA 12), including the real ibex UVM chain and a 10-deep expansion. The inheritance-edge index want is filed beside the instantiation-edge Handshake as one future round. docs/features/type-hierarchy/README.md Co-Authored-By: Claude Fable 5 --- TODO.md | 25 +- crates/lucisv_server/src/main.rs | 64 +- crates/lucisv_server/src/server.rs | 33 +- crates/lucisv_server/src/type_hierarchy.rs | 1189 ++++++++++++++++++++ crates/lucisv_server/tests/e2e.rs | 97 ++ docs/features/lucisv-server/README.md | 45 + docs/features/type-hierarchy/README.md | 581 ++++++++++ 7 files changed, 2028 insertions(+), 6 deletions(-) create mode 100644 crates/lucisv_server/src/type_hierarchy.rs create mode 100644 docs/features/type-hierarchy/README.md diff --git a/TODO.md b/TODO.md index b146e43..756f21e 100644 --- a/TODO.md +++ b/TODO.md @@ -866,9 +866,32 @@ and are not gaps. the `;` is the one closing a module header. `pairs.rs` gained three `pub(crate)` accessors so the matcher and the indent model read one keyword table. -- [ ] **Type hierarchy (3.17)** — arguably the semantically correct +- [x] **Type hierarchy (3.17)** — arguably the semantically correct home for the module hierarchy (and later interface/class extends chains); keep callHierarchy as the compatibility surface. + → delivered 2026-08-26 by `docs/features/type-hierarchy/README.md`: + `typeHierarchyProvider` + `crates/lucisv_server/src/type_hierarchy.rs`, + all three requests. **Classes, not modules** — the lead's scope call: + an instantiation is a containment edge and `extends` is an inheritance + edge, so the module hierarchy stays on callHierarchy exactly as this + item's second clause asks, and typeHierarchy serves one node kind + well. `supertypes` is not a new lookup: `extends Base` is already a + `vlog_semantic` reference and overlay-promotion already made a bare + cross-file class name reachable through it, so the answer is + `definition_of` asked at the last byte of the extends name span — + which is the tail of `pkg::base`, the whole of a bare `base`, and the + bare name of a parameterized `base #(8)`. A base the workspace does + not index (every UVM chain top) yields no item rather than a guess. + `subtypes` is `hierarchy::callers_of_each`'s census in another key — + one `sources()` pass, substring prefilter, deterministic sort — at + 55 ms over the 860-file corpus, 53 ms of it file I/O; the + inheritance-edge table that would make it a lookup is filed beside the + instantiation-edge table §9c's code-lens item already recorded. Two + gaps recorded there: `lsp-types` 0.97 has no `typeHierarchyProvider` + field, so the capability is inserted into the serialized `initialize` + result by hand, and `vlog_parser` rejects `interface class`, so + `implements` can never resolve and no item can carry + `SymbolKind::Interface`. - [ ] **File operations** — `workspace/willRenameFiles`: renaming a `.sv/.svh` rewrites `` `include`` lines that reference it (the include graph exists); `didRename/didDelete` as cheaper index nudges diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 6d9e9b6..5cea71a 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -39,6 +39,7 @@ mod sync; mod templates; mod tokens; mod type_def; +mod type_hierarchy; mod uri; mod watch; @@ -79,7 +80,7 @@ fn main() -> Result<(), Box> { code_lens_refresh: code_lens_refresh_support(¶ms), show_document: show_document_support(¶ms), }; - connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?; + connection.initialize_finish(id, initialize_value()?)?; Server::new(connection, roots, abilities).run()?; io_threads.join()?; @@ -285,6 +286,22 @@ fn commands() -> Vec { commands } +/// The `initialize` result exactly as it goes on the wire. +/// +/// `typeHierarchyProvider` is written in here rather than in [`capabilities`] +/// because `lsp-types` 0.97 models type hierarchy on the *client* side only: +/// `ServerCapabilities` has no field for it, and `experimental` is a different +/// key that no client reads for this. So the one capability this server +/// advertises that the crate cannot spell is inserted into the serialized +/// object, which is the same JSON a field would have produced. +fn initialize_value() -> Result { + let mut value = serde_json::to_value(initialize_result())?; + if let Some(caps) = value.get_mut("capabilities").and_then(serde_json::Value::as_object_mut) { + caps.insert("typeHierarchyProvider".to_string(), serde_json::Value::Bool(true)); + } + Ok(value) +} + fn initialize_result() -> lsp_types::InitializeResult { lsp_types::InitializeResult { capabilities: capabilities(), @@ -434,6 +451,51 @@ mod tests { assert!(caps.document_on_type_formatting_provider.is_some()); } + #[test] + fn the_type_hierarchy_is_advertised_even_though_lsp_types_cannot_spell_it() { + // `ServerCapabilities` has no `type_hierarchy_provider` field in + // lsp-types 0.97 — the crate models type hierarchy on the client side + // only — so the capability is written into the serialized object. A + // client keys entirely off this key: without it the three requests are + // never sent, however well they are implemented. + let value = initialize_value().expect("the initialize result serializes"); + assert_eq!( + value["capabilities"]["typeHierarchyProvider"], + serde_json::json!(true), + "{value:#?}" + ); + // And the rest of the object is untouched by the insertion. + assert_eq!(value["capabilities"]["callHierarchyProvider"], serde_json::json!(true)); + assert_eq!(value["serverInfo"]["name"], serde_json::json!("lucisv-server")); + } + + // QA (2026-08-26): the spot checks above name two fields; this pins the + // whole object instead. `initialize_result()` and `capabilities()` are + // untouched by this round (confirmed against `24e8eab`), so the only way + // the insertion could disturb anything is the one `caps.insert` call + // itself — this proves that byte-for-byte rather than by inspection: pull + // the one inserted key back out and what remains must equal the plain, + // uninserted serialization exactly. A future round that lets the + // insertion clobber an existing key, or that adds a field to + // `ServerCapabilities` under the same JSON name, fails this immediately. + #[test] + fn the_json_insertion_disturbs_nothing_else_in_the_initialize_result() { + let mut with_insertion = initialize_value().expect("the initialize result serializes"); + let plain = serde_json::to_value(initialize_result()).expect("serializes on its own too"); + let caps = + with_insertion["capabilities"].as_object_mut().expect("capabilities is a JSON object"); + assert_eq!( + caps.remove("typeHierarchyProvider"), + Some(serde_json::json!(true)), + "the one key the insertion is supposed to add" + ); + assert_eq!( + with_insertion, plain, + "removing the inserted key must restore exactly what capabilities() \ + and initialize_result() produce on their own, key for key, value for value" + ); + } + #[test] fn on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else() { // The trigger set is the feature: a client sends this request on every diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 10f12dc..a583662 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -27,8 +27,9 @@ use lsp_types::request::{ InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, - SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, UnregisterCapability, - WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, + SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, + TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillSaveWaitUntil, + WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, @@ -48,7 +49,8 @@ use lsp_types::{ SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowDocumentParams, ShowMessageParams, SignatureHelpParams, - TextDocumentPositionParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, + TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, + TypeHierarchySupertypesParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, @@ -62,7 +64,7 @@ use crate::state::Workspace; use crate::{ code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, signature, - symbols, sync, tokens, type_def, watch, + symbols, sync, tokens, type_def, type_hierarchy, watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -585,6 +587,29 @@ impl Server { to_value(hierarchy::outgoing(&self.workspace, &p.item)) }) } + // The class inheritance tree. Same contract as the call hierarchy + // above: `prepare` answers `null` for a position that is not a + // class name, and the two directions answer one hop each while the + // client drives the expansion. + TypeHierarchyPrepare::METHOD => { + decode(request).and_then(|p: TypeHierarchyPrepareParams| { + let at = p.text_document_position_params; + let (uri, position) = (at.text_document.uri, at.position); + self.offset(&uri, position) + .and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset)) + .map_or(Ok(Value::Null), to_value) + }) + } + TypeHierarchySupertypes::METHOD => { + decode(request).and_then(|p: TypeHierarchySupertypesParams| { + to_value(type_hierarchy::supertypes(&self.workspace, &p.item)) + }) + } + TypeHierarchySubtypes::METHOD => { + decode(request).and_then(|p: TypeHierarchySubtypesParams| { + to_value(type_hierarchy::subtypes(&self.workspace, &p.item)) + }) + } WorkspaceSymbolRequest::METHOD => { decode(request).and_then(|p: WorkspaceSymbolParams| { to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols( diff --git a/crates/lucisv_server/src/type_hierarchy.rs b/crates/lucisv_server/src/type_hierarchy.rs new file mode 100644 index 0000000..83806fb --- /dev/null +++ b/crates/lucisv_server/src/type_hierarchy.rs @@ -0,0 +1,1189 @@ +//! `textDocument/prepareTypeHierarchy`, `typeHierarchy/supertypes` and +//! `typeHierarchy/subtypes` — the class inheritance tree, both directions. +//! +//! LSP's type hierarchy is a graph of supertypes and subtypes, and +//! SystemVerilog's `extends` is exactly that graph: a class is a node and +//! `class d extends b` is the edge. So "what does this class extend?" is +//! `supertypes` and "who extends it?" is `subtypes`, drawn by every LSP +//! client's own hierarchy view without a line of editor code. +//! +//! **Classes only.** The module hierarchy stays on `callHierarchy`, where it +//! shipped and is tested (`docs/features/hierarchy/README.md`): an +//! instantiation is a containment edge, not an inheritance edge, and moving it +//! here would put two unrelated relations behind one request with no way for a +//! client to tell them apart. +//! +//! Each request answers **one hop**. The client drives the expansion, so +//! `class a extends a;` and an `a → b → a` pair need no cycle handling here: +//! nothing recurses, and the user simply sees the same node again one level +//! down. +//! +//! See `docs/features/type-hierarchy/README.md`. + +use lsp_types::{Range, SymbolKind, TypeHierarchyItem, Uri}; +use vlog_parser::ast::{ClassDecl, Item, ItemKind}; +use vlog_parser::{parse_source_tolerant, LineIndex, TextRange}; +use vlog_semantic::{Definition, SymbolKind as SemanticKind}; + +use crate::convert::Positions; +use crate::state::{Document, Workspace}; +use crate::uri::{path_to_uri, uri_to_path}; + +/// One class declaration: the node, and the extent of the whole +/// `class ... endclass` it was written as. +#[derive(Clone, Copy)] +struct Decl<'a> { + class: &'a ClassDecl, + /// Code extent of the declaration, attributes included — what a type + /// hierarchy item's `range` is. + span: TextRange, +} + +/// The class the cursor names, as the root of a type hierarchy — its own +/// declaration, or any use of its name. +/// +/// `None` for every other position, which is what stops an editor from opening +/// an empty hierarchy view on a `wire`. A name that resolves to something other +/// than a class declines the same way: there is no node to stand on. +/// +/// A name two files declare returns *both* items rather than a guess, the same +/// answer `textDocument/definition` gives for the same ambiguity — the client +/// asks the user which one they meant. +pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option> { + let doc = ws.document(uri)?; + // The cursor on a declaration written in this buffer answers from the + // buffer, unsaved edits and all — no index lookup can beat that. + if let Some(decl) = + declarations(&doc.tree.items).into_iter().find(|decl| touches(decl.class.name_span, offset)) + { + let positions = doc.positions(); + return Some(vec![item(uri.clone(), &positions, decl)?]); + } + // Any other position is a *use*, answered by the two layers every other + // navigation uses: this file's own symbol table, then the workspace + // overlay. + let items = classes_at(ws, doc, uri, offset); + (!items.is_empty()).then_some(items) +} + +/// What this class extends: its base class, resolved in this file first and +/// through the workspace after. +/// +/// SystemVerilog gives a class exactly one base, so this is a list of at most +/// one — except for the ambiguity every cross-file answer in this server has, +/// where two files declare the base name and both are offered. +/// +/// A base the workspace cannot name — declared in a file no filelist indexes, +/// or in a library lucisv never sees — yields **no** item. There is nothing +/// honest to put in a hierarchy view for it: an item whose `uri` is a guess +/// would send the user to the wrong file with no way to tell. +pub fn supertypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec { + // The item may name a file no editor has open — the client is free to send + // back anything `subtypes` handed it — so the analysis is rebuilt here when + // there is no buffer to read it off. + match ws.document(&item.uri) { + Some(doc) => bases_of(ws, doc, &item.uri, item), + None => { + let Some(path) = uri_to_path(&item.uri) else { return Vec::new() }; + let Some(text) = ws.text_of(&path) else { return Vec::new() }; + let doc = Document::new(Some(path), text, ws.index()); + bases_of(ws, &doc, &item.uri, item) + } + } +} + +/// Who extends this class, across the workspace. +/// +/// Every in-scope file is walked, because the workspace index records what a +/// file *declares* and not what it extends — there is no edge table to consult, +/// exactly as there is none for instantiations +/// (`docs/features/hierarchy/README.md`). A file whose text does not contain +/// the name is skipped before it is parsed, which is what keeps the walk +/// affordable: `extends base` has to write `base`. +/// +/// An empty name is answered with nothing rather than searched for: nothing +/// this server hands out is nameless, and the prefilter matches every file for +/// one, which would parse the whole workspace to find nothing. +pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec { + if item.name.is_empty() { + return Vec::new(); + } + let mut found: Vec = Vec::new(); + for (path, text) in ws.sources() { + if !text.contains(&item.name) { + continue; + } + let Some(uri) = path_to_uri(&path) else { continue }; + let (tree, _) = parse_source_tolerant(&text); + let line_index = LineIndex::new(&text); + let positions = Positions::new(&text, &line_index); + for decl in declarations(&tree.items) { + if extends_name(decl.class) != Some(item.name.as_str()) { + continue; + } + if let Some(built) = self::item(uri.clone(), &positions, decl) { + found.push(built); + } + } + } + found.sort_by(|a, b| { + (a.uri.as_str(), key(a.selection_range)).cmp(&(b.uri.as_str(), key(b.selection_range))) + }); + found +} + +/// The base class of one class declaration, as written — `None` when the +/// header has no `extends`. +/// +/// The name is the bare base: `extends base #(8)` stores `base`, because the +/// parser keeps the parameter overrides on their own field, so a parameterized +/// base needs no unwrapping here. +fn extends_name(class: &ClassDecl) -> Option<&str> { + class.extends.as_ref().map(|extends| extends.name.as_str()) +} + +/// The base classes of the class an item names, in the file it names. +fn bases_of( + ws: &Workspace, + doc: &Document, + uri: &Uri, + item: &TypeHierarchyItem, +) -> Vec { + let positions = doc.positions(); + let at = span(&positions, item.selection_range); + let Some(decl) = find_class(&doc.tree.items, &item.name, Some(at)) else { return Vec::new() }; + let Some(extends) = decl.class.extends.as_ref() else { return Vec::new() }; + if extends.name_span.is_empty() { + return Vec::new(); + } + // The last byte of the base-name span. For `pkg::base` that is inside the + // *tail's* own reference, which is the one that names a class — the head + // names the package. For a bare `base` it is that one reference. Either + // way the answer comes from the same two layers `textDocument/definition` + // uses, so a base in another file needs no lookup of this feature's own. + classes_at(ws, doc, uri, extends.name_span.end - 1) +} + +/// Every class declaration the name at `offset` resolves to, through both +/// layers — this file's symbol table first, then the workspace overlay. +/// +/// A name that resolves to anything but a class is not a type hierarchy node +/// and answers nothing. +fn classes_at(ws: &Workspace, doc: &Document, uri: &Uri, offset: u32) -> Vec { + match doc.external.definition_of(&doc.semantics, offset) { + Some(Definition::Local(symbol)) => { + if symbol.kind != SemanticKind::Class { + return Vec::new(); + } + let positions = doc.positions(); + find_class(&doc.tree.items, &symbol.name, Some(symbol.name_span)) + .and_then(|decl| item(uri.clone(), &positions, decl)) + .into_iter() + .collect() + } + Some(Definition::External(defs)) => { + // A `Definition::External` only ever comes from a reference at this + // offset, and its name is what the declaring file has to spell. + let Some(reference) = doc.semantics.reference_at(offset) else { return Vec::new() }; + defs.iter() + .filter(|def| def.kind == SemanticKind::Class) + .filter_map(|def| { + let path = ws.index().path(def.file)?; + item_in_file(ws, path, &reference.name, Some(def.name_span)) + }) + .collect() + } + None => Vec::new(), + } +} + +/// The hierarchy item for one class declaration, positioned against the text it +/// was parsed from. +fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option { + let name_span = decl.class.name_span; + if name_span.is_empty() { + return None; + } + // The protocol requires `selectionRange` inside `range`; a declaration the + // parser could not close is the case where that may not hold, and there the + // name alone is the honest extent. + let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end { + decl.span + } else { + name_span + }; + Some(TypeHierarchyItem { + name: decl.class.name.clone(), + // `interface class` is a different construct (IEEE 1800 §8.26) that + // `vlog_parser` does not model at all, so there is nothing here that + // could carry `SymbolKind::INTERFACE`. + kind: SymbolKind::CLASS, + tags: None, + detail: None, + uri, + range: positions.range(full), + selection_range: positions.range(name_span), + // Items are re-derived from the text on every request, exactly as the + // call hierarchy's are, so there is nothing to preserve between them. + data: None, + }) +} + +/// Re-read a declaring file and build the item for the class in it. +/// +/// The index knows the file and the name's span but keeps no text, so the file +/// is parsed here for the declaration's full extent. `at` is the span the index +/// recorded, used to pick between two same-named declarations in one file; it +/// is a preference and not a requirement, because the buffer may have been +/// edited since the index was built. +fn item_in_file( + ws: &Workspace, + path: &std::path::Path, + name: &str, + at: Option, +) -> Option { + let uri = path_to_uri(path)?; + let text = ws.text_of(path)?; + let (tree, _) = parse_source_tolerant(&text); + let decl = find_class(&tree.items, name, at)?; + let line_index = LineIndex::new(&text); + item(uri, &Positions::new(&text, &line_index), decl) +} + +/// Every class declaration in `items`, wherever a class may be written: at file +/// scope, inside a `package`, inside a `module`, and nested inside another +/// class. +fn declarations(items: &[Item]) -> Vec> { + let mut out = Vec::new(); + collect(items, &mut out); + out +} + +fn collect<'a>(items: &'a [Item], out: &mut Vec>) { + for item in items { + match &item.kind { + ItemKind::Class(class) => { + out.push(Decl { class, span: item.span }); + collect(&class.items, out); + } + ItemKind::Package { items, .. } => collect(items, out), + ItemKind::Module(module) => collect(&module.items, out), + _ => {} + } + } +} + +/// The declaration of `name` in a parsed file: the one whose name sits at `at`, +/// else the first of that name. +fn find_class<'a>(items: &'a [Item], name: &str, at: Option) -> Option> { + let decls: Vec = + declarations(items).into_iter().filter(|d| d.class.name == name).collect(); + if let Some(at) = at { + if let Some(exact) = decls.iter().find(|d| d.class.name_span == at) { + return Some(*exact); + } + } + decls.first().copied() +} + +/// Whether `offset` is inside `span`, its end included — a cursor placed +/// immediately after the last character of a name is on that name, which is +/// where a double-click leaves it. +/// +/// Restated rather than shared with `hierarchy.rs`: it is a statement of what +/// this handler means by "the cursor is on a name", and the two handlers share +/// no logic that a common helper would keep honest. +fn touches(span: TextRange, offset: u32) -> bool { + !span.is_empty() && span.start <= offset && offset <= span.end +} + +/// A `Range` back as a byte span, for matching an item against a fresh parse. +fn span(positions: &Positions, range: Range) -> TextRange { + TextRange::new(positions.offset(range.start), positions.offset(range.end)) +} + +/// A range as a sort key. +fn key(range: Range) -> (u32, u32) { + (range.start.line, range.start.character) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::PathBuf; + + /// A scratch workspace root, removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_type_hierarchy_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + /// A workspace over `files`, with the first of them opened as a buffer. + fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { + let tree = Tree::new(name); + let mut first = None; + for (rel, text) in files { + let path = tree.write(rel, text); + if first.is_none() { + first = Some((path, *text)); + } + } + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let (path, text) = first.expect("at least one file"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + (tree, ws, uri) + } + + /// The byte offset of the first occurrence of `needle`. + fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 + } + + /// An item as `(name, file name, selection line)`. + fn shape(item: &TypeHierarchyItem) -> (String, String, u32) { + ( + item.name.clone(), + item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), + item.selection_range.start.line, + ) + } + + const BASE: &str = "class base;\n int x;\nendclass\n"; + const CHILD: &str = "class child extends base;\n int y;\nendclass\n"; + + /// The two-file workspace of the cross-file tests, `child.sv` open. + fn two(name: &str) -> (Tree, Workspace, Uri) { + workspace(name, &[("child.sv", CHILD), ("base.sv", BASE)]) + } + + // ------------------------------------------------------------------ + // prepare + // ------------------------------------------------------------------ + + #[test] + fn the_cursor_on_a_class_declaration_prepares_that_class() { + let (_tree, ws, uri) = workspace("decl", &[("base.sv", BASE)]); + let items = prepare(&ws, &uri, at(BASE, "base")).expect("a class"); + assert_eq!(items.len(), 1); + assert_eq!(shape(&items[0]), ("base".to_string(), "base.sv".to_string(), 0)); + assert_eq!(items[0].kind, SymbolKind::CLASS); + assert_eq!(items[0].selection_range.start.character, 6, "the name, not the keyword"); + assert_eq!(items[0].range.start.character, 0, "the whole declaration"); + assert_eq!(items[0].range.end.line, 2, "through `endclass`"); + assert!(items[0].data.is_none(), "items are re-derived, never carried"); + } + + #[test] + fn the_cursor_on_a_use_prepares_the_class_it_names() { + // Three kinds of use, all answered by the same two layers + // `textDocument/definition` uses. + let text = "\ +class base; +endclass + +class child extends base; + base handle; + function void f(); + base local_one; + endfunction +endclass +"; + let (_tree, ws, uri) = workspace("uses", &[("u.sv", text)]); + let uses = [ + ("the `extends` base", at(text, "extends base") + 8), + ("a property's type", at(text, "base handle")), + ("a method local's type", at(text, "base local_one")), + ]; + for (what, offset) in uses { + let items = prepare(&ws, &uri, offset).unwrap_or_else(|| panic!("{what}")); + assert_eq!(items.len(), 1, "{what}: {items:#?}"); + assert_eq!(shape(&items[0]), ("base".to_string(), "u.sv".to_string(), 0), "{what}"); + } + } + + #[test] + fn a_position_on_no_class_prepares_nothing() { + let text = "\ +class base; + int x; +endclass + +module m; + wire w; +endmodule +"; + let (_tree, ws, uri) = workspace("none", &[("n.sv", text)]); + assert!(prepare(&ws, &uri, 0).is_none(), "the `class` keyword"); + assert!(prepare(&ws, &uri, at(text, "int x") + 4).is_none(), "a property name"); + 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"); + } + + #[test] + fn a_cursor_just_past_the_last_character_of_a_name_still_prepares() { + // Where a double-click and an end-of-word motion leave it. + let (_tree, ws, uri) = workspace("edge", &[("base.sv", BASE)]); + assert!(prepare(&ws, &uri, at(BASE, "base") + 4).is_some()); + } + + #[test] + fn a_class_two_files_declare_prepares_both_rather_than_guessing() { + let dup = "class dup;\nendclass\n"; + let user = "class user extends dup;\nendclass\n"; + let (_tree, ws, uri) = workspace("dup", &[("user.sv", user), ("a.sv", dup), ("b.sv", dup)]); + let items = prepare(&ws, &uri, at(user, "extends dup") + 8).expect("both"); + let files: Vec = items.iter().map(|i| shape(i).1).collect(); + assert_eq!(files, ["a.sv", "b.sv"], "every declaration, as definition does"); + } + + #[test] + fn an_unopened_document_prepares_nothing() { + let ws = Workspace::default(); + let uri = path_to_uri(std::path::Path::new("/nowhere/c.sv")).expect("uri"); + assert!(prepare(&ws, &uri, 0).is_none()); + } + + #[test] + fn an_untitled_buffer_prepares_from_itself() { + // No path, so no index entry — but the declaration is right there in + // the buffer, and its own hierarchy root is a fair answer. + use std::str::FromStr; + let text = "class scratch;\nendclass\n"; + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let items = prepare(&ws, &uri, at(text, "scratch")).expect("the buffer's own class"); + assert_eq!(items[0].name, "scratch"); + assert_eq!(items[0].uri, uri); + assert!(supertypes(&ws, &items[0]).is_empty(), "and it extends nothing"); + } + + #[test] + fn an_interface_class_is_not_a_node_because_the_parser_does_not_model_one() { + // `interface class` is a different construct (IEEE 1800 §8.26) that + // `vlog_parser` rejects, so it never becomes a `ClassDecl` and there is + // no item — and no `SymbolKind::INTERFACE` case — to build. Pinned so a + // future parser round that models it is forced past this test. + let text = "interface class ic;\n pure virtual function void f();\nendclass\n"; + let (_tree, ws, uri) = workspace("ifaceclass", &[("ic.sv", text)]); + assert!(prepare(&ws, &uri, at(text, "ic")).is_none()); + } + + #[test] + fn a_class_declared_in_a_package_in_a_module_and_in_a_class_is_all_found() { + let text = "\ +package p; + class in_package; + endclass +endpackage + +module m; + class in_module; + endclass +endmodule + +class outer; + class inner; + endclass +endclass +"; + let (_tree, ws, uri) = workspace("nesting", &[("n.sv", text)]); + for name in ["in_package", "in_module", "outer", "inner"] { + let items = prepare(&ws, &uri, at(text, &format!("class {name}")) + 6) + .unwrap_or_else(|| panic!("{name} is a class")); + assert_eq!(items[0].name, name); + } + } + + // ------------------------------------------------------------------ + // supertypes + // ------------------------------------------------------------------ + + #[test] + fn supertypes_name_the_base_declared_in_the_same_file() { + let text = "class base;\nendclass\n\nclass child extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace("infile", &[("both.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class child") + 6).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "both.sv".to_string(), 0)); + assert_eq!(bases[0].kind, SymbolKind::CLASS); + } + + #[test] + fn supertypes_reach_a_base_declared_in_another_file() { + // The workspace overlay answers the bare `base`, which is what the + // overlay-promotion round made reachable — no lookup of this feature's + // own. + let (_tree, ws, uri) = two("crossfile"); + let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); + } + + #[test] + fn a_qualified_base_resolves_through_its_package() { + let pkg = "package p;\n class base;\n endclass\nendpackage\n"; + let child = "class child extends p::base;\nendclass\n"; + let (_tree, ws, uri) = workspace("qualified", &[("child.sv", child), ("p.sv", pkg)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "p.sv".to_string(), 1)); + } + + #[test] + fn a_parameterized_base_resolves_by_its_bare_name() { + // `#( ... )` lives on its own field, so the base name the parser stores + // is already bare and nothing here unwraps anything. + let child = "class child extends base #(8);\nendclass\n"; + let (_tree, ws, uri) = workspace("param", &[("child.sv", child), ("base.sv", BASE)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); + } + + #[test] + fn a_base_the_workspace_does_not_declare_yields_no_supertype() { + // The UVM shape: `uvm_component` is in a library nobody indexed. No + // item is better than an item pointing at a file that is not there. + let child = "class child extends uvm_component;\nendclass\n"; + let (_tree, ws, uri) = workspace("unknown", &[("child.sv", child)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + assert!(supertypes(&ws, &root).is_empty()); + } + + #[test] + fn a_class_that_extends_nothing_has_no_supertypes() { + let (_tree, ws, uri) = workspace("root", &[("base.sv", BASE)]); + let root = prepare(&ws, &uri, at(BASE, "base")).expect("base")[0].clone(); + assert!(supertypes(&ws, &root).is_empty()); + } + + #[test] + fn an_implements_clause_names_no_supertype() { + // `implements` names an *interface* class, which `vlog_parser` does not + // model — so there is never a declaration to point at, and matching one + // by name would claim an unrelated ordinary class. Only `extends` is an + // edge here. + let base = "class base;\nendclass\n"; + let child = "class child implements base;\nendclass\n"; + let (_tree, ws, uri) = workspace("implements", &[("child.sv", child), ("base.sv", base)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + assert!(supertypes(&ws, &root).is_empty(), "pinning today's answer and its reason"); + } + + #[test] + fn supertypes_answer_for_a_file_no_editor_has_open() { + // What a client does after `subtypes`: it sends back an item naming a + // file it never opened, and the hop has to work anyway. + let (_tree, ws, uri) = two("closedfile"); + let base_root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone(); + assert!(ws.document(&base_root.uri).is_none(), "premise: base.sv is not open"); + let children = subtypes(&ws, &base_root); + assert_eq!(children.len(), 1); + // And `child.sv` *is* open, so go one further: an item from a closed + // file, asked for its own base. + let bases = supertypes(&ws, &children[0]); + assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); + } + + #[test] + fn an_item_naming_a_file_that_is_gone_answers_with_nothing() { + let (tree, ws, uri) = two("missing"); + let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + assert_eq!(supertypes(&ws, &root).len(), 1, "premise"); + let mut stale = root.clone(); + stale.uri = path_to_uri(&tree.path.join("gone.sv")).expect("uri"); + assert!(supertypes(&ws, &stale).is_empty(), "no file, no supertype, no panic"); + let mut renamed = root; + renamed.name = "no_such_class".to_string(); + assert!(supertypes(&ws, &renamed).is_empty(), "a name the file does not declare"); + } + + // ------------------------------------------------------------------ + // subtypes + // ------------------------------------------------------------------ + + #[test] + fn subtypes_name_every_class_that_extends_this_one() { + let text = "\ +class base; +endclass + +class first extends base; +endclass + +class second extends base; +endclass + +class unrelated; +endclass +"; + let (_tree, ws, uri) = workspace("subs", &[("all.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + let children = subtypes(&ws, &root); + assert_eq!( + children.iter().map(shape).collect::>(), + [ + ("first".to_string(), "all.sv".to_string(), 3), + ("second".to_string(), "all.sv".to_string(), 6), + ], + "sorted by file then position: {children:#?}" + ); + } + + #[test] + fn subtypes_reach_other_files_in_a_deterministic_order() { + let base = "class base;\nendclass\n"; + let one = "class one extends base;\nendclass\n"; + let two_text = "class two extends base;\nendclass\n"; + let three = "class three extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace( + "crosssubs", + &[("base.sv", base), ("c.sv", three), ("a.sv", one), ("b.sv", two_text)], + ); + let root = prepare(&ws, &uri, at(base, "base")).expect("base")[0].clone(); + let first = subtypes(&ws, &root); + assert_eq!( + first.iter().map(|i| shape(i).1).collect::>(), + ["a.sv", "b.sv", "c.sv"], + "sorted by URI, not by whatever order the files were read in" + ); + assert_eq!( + first.iter().map(|i| i.name.clone()).collect::>(), + ["one", "two", "three"] + ); + let again = subtypes(&ws, &root); + assert_eq!(first, again, "the same question twice gives the same answer"); + } + + #[test] + fn a_class_nobody_extends_has_no_subtypes() { + let (_tree, ws, uri) = two("leaf"); + let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + assert!(subtypes(&ws, &root).is_empty()); + } + + #[test] + fn a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with() { + // The `hierarchy` precedent: matching on the trailing segment would let + // `other_pkg::base` claim to extend *this* `base`. Zero of the 309 + // `extends` clauses in the checked-in corpus are qualified, so this + // costs nothing measurable and never lies. The asymmetry with + // `supertypes` (which *does* follow `p::base`, through the package) is + // deliberate and documented. + let pkg = "package other_pkg;\n class base;\n endclass\nendpackage\n"; + let base = "class base;\nendclass\n"; + let child = "class child extends other_pkg::base;\nendclass\n"; + let (_tree, ws, uri) = + workspace("qualsub", &[("base.sv", base), ("p.sv", pkg), ("child.sv", child)]); + let root = prepare(&ws, &uri, at(base, "base")).expect("base")[0].clone(); + assert!(subtypes(&ws, &root).is_empty(), "the file-scope `base` is not the one extended"); + } + + #[test] + fn a_class_extended_only_outside_the_index_scope_has_no_subtypes() { + // The scope ladder decides which files exist; a file the configured + // filelist omits extends nothing, exactly as it references nothing. + let tree = Tree::new("scope"); + tree.write("base.sv", BASE); + tree.write("child.sv", CHILD); + tree.write("files.f", "base.sv\n"); + tree.write("lucisv.toml", "filelist = \"files.f\"\n"); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let base_uri = path_to_uri(&tree.path.join("base.sv")).expect("uri"); + ws.set_document(base_uri.clone(), BASE.to_string()); + + let root = prepare(&ws, &base_uri, at(BASE, "base")).expect("base")[0].clone(); + assert!(subtypes(&ws, &root).is_empty(), "child.sv is out of scope"); + } + + #[test] + fn an_unsaved_extends_is_a_subtype_before_it_is_saved() { + // The sources a walk reads are the open buffers overlaid on disk, so a + // just-typed `extends` counts. + let (tree, mut ws, uri) = two("unsaved"); + let root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone(); + assert_eq!(subtypes(&ws, &root).len(), 1, "premise"); + + let fresh = tree.path.join("child.sv"); + let child_uri = path_to_uri(&fresh).expect("uri"); + ws.set_document(child_uri, "class child;\nendclass\n".to_string()); + assert!(subtypes(&ws, &root).is_empty(), "the buffer took the `extends` away"); + } + + // ------------------------------------------------------------------ + // QA (2026-08-26): malformed `extends` clauses at the last-byte offset + // ------------------------------------------------------------------ + // + // `extends.name_span.end - 1` only underflows or lands off the class if + // `name_span` is empty or missing — checked here at the boundary rather + // than only trusted from reading `parse_class_extends`. In every case + // below the tolerant parser either fails the whole `class` item (so there + // is no `ClassDecl` to ask about at all) or produces a non-empty span; + // the assertion each time is survival, not a particular answer. + + #[test] + fn an_extends_clause_with_no_base_name_never_panics() { + // `class a extends ;` — nothing for `parse_scoped_name` to read after + // `extends`, so `parse_class_extends` errors and the whole `class a` + // item fails to parse; there is no `ClassExtends` with an empty span + // to feed the offset math, but the walk must survive regardless of + // what the tolerant parser recovers into. + let text = "class a extends ;\nendclass\n"; + let (_tree, ws, uri) = workspace("emptyextends", &[("a.sv", text)]); + if let Some(items) = prepare(&ws, &uri, at(text, "class a") + 6) { + let _ = supertypes(&ws, &items[0]); + let _ = subtypes(&ws, &items[0]); + } + } + + #[test] + fn an_extends_clause_at_eof_never_panics() { + // The file ends mid-header, no `;`, no `endclass`. + let text = "class child extends base"; + let (_tree, ws, uri) = workspace("eofextends", &[("child.sv", text), ("base.sv", BASE)]); + if let Some(items) = prepare(&ws, &uri, at(text, "child")) { + let _ = supertypes(&ws, &items[0]); + let _ = subtypes(&ws, &items[0]); + } + } + + #[test] + fn a_qualified_base_with_nothing_after_the_double_colon_never_panics() { + // `pkg::` with no tail identifier: `parse_scoped_name` errors after + // the `::`, so this is another whole-class parse failure, not an + // empty tail span. + let text = "class child extends pkg::;\nendclass\n"; + let (_tree, ws, uri) = workspace("danglingcolon", &[("child.sv", text)]); + if let Some(items) = prepare(&ws, &uri, at(text, "child")) { + let _ = supertypes(&ws, &items[0]); + let _ = subtypes(&ws, &items[0]); + } + } + + #[test] + fn a_single_character_base_name_resolves() { + let text = "class b;\nendclass\nclass a extends b;\nendclass\n"; + let (_tree, ws, uri) = workspace("shortname", &[("f.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class a") + 6).expect("a")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(bases[0].name, "b"); + } + + #[test] + fn multibyte_text_immediately_after_the_extends_name_does_not_shift_the_offset() { + // The last-byte trick reads `name_span` alone, which the parser + // measures in bytes independent of what follows — but attack the + // boundary anyway: a multibyte comment starts at the very next byte + // after `base`. + let text = "class base;\nendclass\nclass mid extends base/*🎉 日本語*/;\nendclass\n"; + let (_tree, ws, uri) = workspace("multibyteafter", &[("f.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class mid") + 6).expect("mid")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(bases[0].name, "base"); + } + + // ------------------------------------------------------------------ + // QA (2026-08-26): prepare on the keyword, and name shadowing + // ------------------------------------------------------------------ + + #[test] + fn prepare_on_the_extends_keyword_itself_prepares_nothing() { + let text = "class base;\nendclass\nclass child extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace("keyword", &[("f.sv", text)]); + assert!(prepare(&ws, &uri, at(text, "extends") + 2).is_none(), "the keyword, not a name"); + } + + #[test] + fn a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing() { + // `base` is both a class and, inside `child`'s method, a local + // 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 + // type-hierarchy node just because the text matches. + let text = "\ +class base; +endclass + +class child extends base; + function void f(); + int base; + base = base + 1; + endfunction +endclass +"; + let (_tree, ws, uri) = workspace("shadow", &[("f.sv", text)]); + let use_offset = at(text, "base + 1"); + assert!( + prepare(&ws, &uri, use_offset).is_none(), + "a local variable named `base`, not the class" + ); + } + + // ------------------------------------------------------------------ + // QA (2026-08-26): deep chains, cheap per hop + // ------------------------------------------------------------------ + + #[test] + fn a_ten_deep_chain_answers_each_hop_without_recursing() { + let names: Vec = (0..10).map(|i| format!("c{i}")).collect(); + let mut files: Vec<(String, String)> = Vec::new(); + for (i, name) in names.iter().enumerate() { + let text = match names.get(i + 1) { + Some(next) => format!("class {name} extends {next};\nendclass\n"), + None => format!("class {name};\nendclass\n"), + }; + files.push((format!("{name}.sv"), text)); + } + let refs: Vec<(&str, &str)> = files.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect(); + let (_tree, ws, uri) = workspace("chain", &refs); + let root_text = &files[0].1; + let mut node = prepare(&ws, &uri, at(root_text, "c0")).expect("c0")[0].clone(); + for expected_next in &names[1..] { + let up = supertypes(&ws, &node); + assert_eq!(up.len(), 1, "{up:#?}"); + assert_eq!(&up[0].name, expected_next); + node = up[0].clone(); + } + assert!(supertypes(&ws, &node).is_empty(), "the chain really ends at the last class"); + } + + #[test] + fn a_nameless_item_reads_no_files_at_all() { + // A malformed item from a client: the prefilter matches every file for + // an empty name, so without the guard this would read and parse the + // whole workspace to find nothing. + let (_tree, ws, uri) = two("nameless"); + let mut nameless = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + nameless.name = String::new(); + assert!(subtypes(&ws, &nameless).is_empty()); + assert!(supertypes(&ws, &nameless).is_empty()); + } + + // ------------------------------------------------------------------ + // QA (2026-08-26): census correctness — the substring prefilter is not + // the match step, and same-named classes across files are a known, + // documented (not previously pinned) source of imprecision. + // ------------------------------------------------------------------ + + #[test] + fn a_file_containing_the_name_as_a_substring_but_no_matching_extends_is_not_a_false_positive() { + // `database` passes the substring prefilter for the name `base` (it + // contains it), and `class d extends database;` passes it too — but + // neither should ever be counted as extending `base`. The match step + // (`extends_name(decl.class) != Some(item.name.as_str())`) is a full + // string comparison, not a substring one, so both must be rejected. + let text = "\ +class base; +endclass + +class database; +endclass + +class d extends database; +endclass +"; + let (_tree, ws, uri) = workspace("substring", &[("f.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + assert!( + subtypes(&ws, &root).is_empty(), + "`database` and `extends database` must not count as extending `base`" + ); + } + + #[test] + fn subtypes_of_two_same_named_classes_in_different_files_share_one_list() { + // Documented in the feature README as a deliberate consequence of + // matching by name and not by uri (the same policy + // `callHierarchy/incomingCalls` uses for a module name), but not + // previously pinned by a test: `subtypes` cannot tell which of two + // same-named `base` declarations `sub` really extends, so *both* + // items answer with `sub` in their subtype list. This is the bound on + // the false positive the name-as-written match allows — not + // eliminated, but confined to genuinely same-named declarations. + let base_a = "class base;\nendclass\n"; + let base_b = "class base;\nendclass\n"; + let sub = "class sub extends base;\nendclass\n"; + let (_tree, ws, uri) = + workspace("samenamesub", &[("sub.sv", sub), ("a.sv", base_a), ("b.sv", base_b)]); + let roots = prepare(&ws, &uri, at(sub, "extends base") + 8).expect("both bases"); + assert_eq!(roots.len(), 2, "two same-named declarations: {roots:#?}"); + for root in &roots { + let children = subtypes(&ws, root); + assert_eq!(children.len(), 1, "{:?}: {children:#?}", root.uri); + assert_eq!(children[0].name, "sub"); + } + } + + // ------------------------------------------------------------------ + // QA (2026-08-26): a class nested inside a generate block + // ------------------------------------------------------------------ + + #[test] + fn a_class_declared_inside_a_generate_block_is_not_found_by_this_walk() { + // The README's Assumptions section states "a generate block is not + // descended into — no class lives there." That justification is not + // quite right: `vlog_parser` *does* parse a `class` written inside + // `generate`/`if`-generate the same way it parses one at module + // scope (`parse_gen_block` shares `item_or_recover` with ordinary + // module-item parsing), so the class is a real `ItemKind::Class` + // node — it is just nested inside `ItemKind::GenIf`/`GenerateRegion`, + // which `collect()` does not descend into. This pins today's answer + // (not found) as a documented gap rather than a silent one; see the + // QA log for the finding filed against the README's wording. + let text = "\ +module m; + generate + if (1) begin : g + class Foo; + int x; + endclass + end + endgenerate +endmodule +"; + let (_tree, ws, uri) = workspace("generateclass", &[("f.sv", text)]); + assert!( + prepare(&ws, &uri, at(text, "class Foo") + 6).is_none(), + "known gap: a class inside a generate block is invisible to this walk" + ); + } + + // ------------------------------------------------------------------ + // cycles + // ------------------------------------------------------------------ + + #[test] + fn a_self_extending_class_answers_one_hop_in_both_directions_without_duplicating() { + // Broken code, reachable through the tolerant parser. Each request is + // one hop, so neither can loop; the assertion is that the answer is one + // item and not the same class twice. + let text = "class a extends a;\nendclass\n"; + let (_tree, ws, uri) = workspace("selfextends", &[("a.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class a") + 6).expect("a")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "one item, not two: {bases:#?}"); + assert_eq!(bases[0].name, "a"); + assert_eq!(bases[0].selection_range, root.selection_range, "and it is the same node"); + let children = subtypes(&ws, &root); + assert_eq!(children.len(), 1, "one item, not two: {children:#?}"); + assert_eq!(children[0].selection_range, root.selection_range); + } + + #[test] + fn a_two_class_cycle_terminates_in_both_directions() { + let a = "class a extends b;\nendclass\n"; + let b = "class b extends a;\nendclass\n"; + let (_tree, ws, uri) = workspace("cycle", &[("a.sv", a), ("b.sv", b)]); + let root_a = prepare(&ws, &uri, at(a, "class a") + 6).expect("a")[0].clone(); + let up = supertypes(&ws, &root_a); + assert_eq!(up.len(), 1, "a -> b: {up:#?}"); + assert_eq!(up[0].name, "b"); + let hop2 = up[0].clone(); + let up2 = supertypes(&ws, &hop2); + assert_eq!(up2.len(), 1, "b -> a: {up2:#?}"); + assert_eq!(up2[0].name, "a"); + // And the other direction mirrors it, one hop at a time. + let down = subtypes(&ws, &hop2); + assert_eq!(down.len(), 1, "b's only subtype is a: {down:#?}"); + assert_eq!(down[0].name, "a"); + } + + // ------------------------------------------------------------------ + // odds and ends + // ------------------------------------------------------------------ + + #[test] + fn positions_are_utf16_units_on_a_line_carrying_multibyte_text() { + let text = "// é 🎉\nclass base;\nendclass\nclass child extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace("utf16", &[("u.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + assert_eq!( + (root.selection_range.start.line, root.selection_range.start.character), + (1, 6), + "the name of the declaration, in UTF-16 units" + ); + let children = subtypes(&ws, &root); + assert_eq!(children.len(), 1); + assert_eq!( + ( + children[0].selection_range.start.character, + children[0].selection_range.end.character + ), + (6, 11), + "`child`, in UTF-16 units" + ); + } + + #[test] + fn a_buffer_that_does_not_parse_invents_no_types() { + // Whatever the tolerant parse recovered from an unclosed class body, + // nothing may panic and no edge may be invented — the assertion is + // deliberately on survival, so a change in recovery is not a failure. + let broken = "class child extends base;\n int y\n"; + let (_tree, ws, uri) = workspace("broken", &[("child.sv", broken), ("base.sv", BASE)]); + if let Some(items) = prepare(&ws, &uri, at(broken, "child")) { + for base in supertypes(&ws, &items[0]) { + assert_eq!(base.name, "base", "only a class really written there"); + assert!(base.selection_range.start >= base.range.start, "selection inside range"); + } + let _ = subtypes(&ws, &items[0]); + } + } + + #[test] + fn every_item_keeps_its_selection_range_inside_its_range() { + // The protocol requires it, and a client that trusts it will scroll to + // a nonsense position otherwise. + let text = "\ +class base; +endclass + +class child extends base; +endclass +"; + let (_tree, ws, uri) = workspace("contained", &[("c.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + let mut all = vec![root.clone()]; + all.extend(subtypes(&ws, &root)); + all.extend(supertypes(&ws, &all[1].clone())); + assert_eq!(all.len(), 3, "root, one subtype, one supertype"); + for item in &all { + assert!(item.range.start <= item.selection_range.start, "{item:#?}"); + assert!(item.selection_range.end <= item.range.end, "{item:#?}"); + } + } + + // ------------------------------------------------------------------ + // the corpus, smoke-tested + // ------------------------------------------------------------------ + + /// Every class of a real UVM-shaped corpus file, through all three + /// requests, plus one known `extends` chain. Skipped when `corpus/` is not + /// checked out (`tools/corpus_fetch.sh`), like the other corpus tests. + #[test] + fn the_corpus_uvm_classes_answer_all_three_requests() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv"); + let Ok(text) = fs::read_to_string(&lib) else { + eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_roots(vec![corpus]); + let uri = path_to_uri(&lib).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + let files = ws.index().files().len(); + + // Every class declared in the file, both directions. No panic, and + // every item the protocol's containment rule. + let doc = ws.document(&uri).expect("the open buffer"); + let names: Vec = + declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect(); + assert!(names.len() > 20, "the file really is class-heavy: {}", names.len()); + let mut with_a_base = 0; + for name in &names { + let offset = at(&text, &format!("class {name}")) + 6; + let items = prepare(&ws, &uri, offset).unwrap_or_else(|| panic!("{name} is a class")); + assert_eq!(items[0].name, *name); + let up = supertypes(&ws, &items[0]); + let down = subtypes(&ws, &items[0]); + if !up.is_empty() { + with_a_base += 1; + } + for item in up.iter().chain(down.iter()) { + assert_eq!(item.kind, SymbolKind::CLASS); + assert!(item.range.start <= item.selection_range.start, "{item:#?}"); + assert!(item.selection_range.end <= item.range.end, "{item:#?}"); + } + } + assert!(with_a_base > 10, "most of these extend something indexed: {with_a_base}"); + + // The chain the corpus really has: + // `core_ibex_debug_intr_basic_test extends core_ibex_base_test extends + // uvm_test`, and `uvm_test` is in a library this corpus does not carry. + let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6; + let child = prepare(&ws, &uri, offset).expect("the class")[0].clone(); + let up = supertypes(&ws, &child); + assert_eq!(up.len(), 1, "{up:#?}"); + assert_eq!(up[0].name, "core_ibex_base_test"); + assert!( + up[0].uri.as_str().ends_with("core_ibex_base_test.sv"), + "declared in its own file: {}", + up[0].uri.as_str() + ); + assert!( + supertypes(&ws, &up[0]).is_empty(), + "`uvm_test` is not in this corpus, so the chain stops rather than guessing" + ); + let down = subtypes(&ws, &up[0]); + assert!(down.len() > 5, "many tests extend the base test: {}", down.len()); + assert!( + down.iter().any(|i| i.name == "core_ibex_debug_intr_basic_test"), + "and the class we came from is one of them" + ); + // What each direction costs over the whole corpus. The budget is + // deliberately loose — a debug build on a loaded machine is the worst + // case this ever runs in — and exists to catch an order-of-magnitude + // regression, not to pin a number; the numbers themselves are in + // `docs/features/type-hierarchy/README.md`. + let base = up[0].clone(); + let mut sub_cost = std::time::Duration::ZERO; + let mut super_cost = std::time::Duration::ZERO; + for _ in 0..3 { + let started = std::time::Instant::now(); + let _ = subtypes(&ws, &base); + sub_cost = sub_cost.max(started.elapsed()); + let started = std::time::Instant::now(); + let _ = supertypes(&ws, &child); + super_cost = super_cost.max(started.elapsed()); + } + eprintln!( + "corpus: {} files, {} classes in core_ibex_test_lib.sv, {with_a_base} with an indexed \ + base; core_ibex_base_test has {} subtypes (worst of three: subtypes {sub_cost:?}, \ + supertypes {super_cost:?})", + files, + names.len(), + down.len() + ); + assert!(sub_cost < std::time::Duration::from_millis(1500), "subtypes cost {sub_cost:?}"); + assert!( + super_cost < std::time::Duration::from_millis(500), + "supertypes cost {super_cost:?}" + ); + } +} diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 2bd31d8..bbf0615 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -3539,3 +3539,100 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +const TYPE_BASE: &str = "class type_base;\n int x;\nendclass\n"; +const TYPE_MID: &str = "class type_mid extends type_base;\n int y;\nendclass\n"; +const TYPE_LEAF: &str = "class type_leaf extends type_mid;\nendclass\n"; + +#[test] +fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() { + // What only an e2e test can check: that `typeHierarchyProvider` is + // advertised in the shape a client reads — `lsp-types` has no field for it, + // so it is written into the serialized capabilities by hand — and that an + // item the *client* sends back, rather than one this process still holds, + // is what the two directions are answered from. + let dir = temp_dir("type_hierarchy"); + let base = dir.join("type_base.sv"); + std::fs::write(&base, TYPE_BASE).expect("write"); + let mid = dir.join("type_mid.sv"); + std::fs::write(&mid, TYPE_MID).expect("write"); + let leaf = dir.join("type_leaf.sv"); + std::fs::write(&leaf, TYPE_LEAF).expect("write"); + + let root = format!("file://{}", dir.display()); + let mid_uri = format!("file://{}", mid.display()); + let base_uri = format!("file://{}", base.display()); + let leaf_uri = format!("file://{}", leaf.display()); + // The item a client holds after `prepareTypeHierarchy` and sends back for + // each direction: `type_mid`, declared on lines 0..2 of `type_mid.sv`. + let mid_item = format!( + r#"{{"name":"type_mid","kind":5,"uri":"{mid_uri}","range":{{"start":{{"line":0,"character":0}},"end":{{"line":2,"character":8}}}},"selectionRange":{{"start":{{"line":0,"character":6}},"end":{{"line":0,"character":14}}}}}}"# + ); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{mid_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(TYPE_MID).expect("json") + )), + // The cursor on the `type_mid` of its own declaration. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/prepareTypeHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":0,"character":8}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"typeHierarchy/supertypes","params":{{"item":{mid_item}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"typeHierarchy/subtypes","params":{{"item":{mid_item}}}}}"# + )), + // A property name is not a class, so there is no hierarchy to open. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/prepareTypeHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":1,"character":7}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) + }; + + let capabilities = &response(1)["result"]["capabilities"]; + assert_eq!(capabilities["typeHierarchyProvider"], serde_json::json!(true)); + + let prepared = response(2)["result"].as_array().expect("a list of items"); + assert_eq!(prepared.len(), 1, "{prepared:#?}"); + assert_eq!( + prepared[0], + serde_json::from_str::(&mid_item).expect("json"), + "the item the client will send back is exactly the one built here" + ); + + let supertypes = response(3)["result"].as_array().expect("a list of items"); + assert_eq!(supertypes.len(), 1, "one base: {supertypes:#?}"); + assert_eq!(supertypes[0]["name"], "type_base"); + assert_eq!(supertypes[0]["uri"], base_uri.as_str()); + assert_eq!(supertypes[0]["kind"], 5, "SymbolKind.Class"); + assert_eq!( + supertypes[0]["selectionRange"], + serde_json::json!({ + "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 15 } + }), + "the base's own name span, in its own file" + ); + + let subtypes = response(4)["result"].as_array().expect("a list of items"); + assert_eq!(subtypes.len(), 1, "one subtype: {subtypes:#?}"); + assert_eq!(subtypes[0]["name"], "type_leaf"); + assert_eq!(subtypes[0]["uri"], leaf_uri.as_str()); + assert_eq!(subtypes[0]["kind"], 5, "SymbolKind.Class"); + + assert_eq!(response(5)["result"], serde_json::Value::Null, "a property name is no class"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 724e7bc..59f1074 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -44,6 +44,9 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/prepareCallHierarchy` | `instantiations::{sites,declarations}`, `WorkspaceIndex::units` | The module under the cursor as a hierarchy node (`SymbolKind::Module`), from its own declaration or from any instantiation of it. Every other position answers `null`; an ambiguous name returns every declaration, as `definition` does. See `docs/features/hierarchy/README.md` | | `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README | | `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README | +| `textDocument/prepareTypeHierarchy` | the class walk over `Document.tree`, then `ExternalResolutions::definition_of` | The **class** under the cursor as a type hierarchy node (`SymbolKind::Class`), from its own declaration or from any use of its name (an `extends` base, a property's type, a method local's type). Every other position answers `null`; a name two files declare returns both, as `definition` does. Advertised by hand — `lsp-types` 0.97's `ServerCapabilities` has no `typeHierarchyProvider` field. See `docs/features/type-hierarchy/README.md` | +| `typeHierarchy/supertypes` | `ClassDecl::extends` + `ExternalResolutions::definition_of` | "What X extends": its base class, resolved by the same two layers F12 uses — in-file first, then the workspace overlay — asked at the **last byte** of the extends name, which is the tail of `pkg::base` and the whole of a bare `base`. A parameterized base resolves by its bare name; a base the workspace does not index (every UVM chain top) yields **no** item rather than a guess. Same feature README | +| `typeHierarchy/subtypes` | the class walk over `Workspace::sources` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. Walks the in-scope files — the index holds no inheritance edges — skipping any file whose text does not contain the name (55 ms over the 860-file corpus, 53 ms of it file I/O). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README | | `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same walk asked about every module in the file at once, so the two can never disagree. `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` | | `workspace/executeCommand` → `lucisv.showInstantiations` | `hierarchy::callers_of_each` | The code lens's own jump: `["module-name"]` in, every site as a `Location` out — one per site, file-then-position order. For a client that advertised `window.showDocument`, the server also pushes a `window/showDocument` for the **first** site, which is what makes the click navigate; LSP has no server-initiated peek-references, and this repo's extension declares no client-side command. A name with no sites answers `[]`; a missing or empty name is `RequestFailed`. Same feature README | | `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README | @@ -577,6 +580,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: the module hierarchy both directions, modules as the nodes and instantiations as the calls, off a walk shared with the inlay hints. `docs/features/hierarchy/README.md`. +- [x] `typeHierarchy` (all three requests) — delivered by **type-hierarchy** + (2026-08-26, TODO.md §9c): the class `extends` tree both directions, + classes as the nodes. The capability is inserted into the serialized + `initialize` result because `lsp-types` 0.97 has no field for it. + `docs/features/type-hierarchy/README.md`. - [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) — `docs/features/macro-expansion/README.md`. - [x] `$/cancelRequest` — delivered by **cancel-request** (2026-08-26, @@ -588,6 +596,43 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: ## Work log +### 2026-08-26 — dev agent (type-hierarchy, TODO.md §9c) + +- **One new capability, one new module, nothing else moved.** The three + `typeHierarchy` requests are served from + `crates/lucisv_server/src/type_hierarchy.rs`; `server.rs` gained three + dispatch arms. No engine change — `vlog_semantic` and `vlog_parser` are + untouched, and `hierarchy.rs`/`instantiations.rs` were not opened. +- **The capability is written by hand.** `lsp-types` 0.97 models type hierarchy + on the *client* side only: `ServerCapabilities` has no + `type_hierarchy_provider` field. `main.rs`'s new `initialize_value` serializes + the `InitializeResult` and inserts `"typeHierarchyProvider": true` into the + capabilities object — the same JSON a field would have produced — because a + capability a client cannot see is a feature that is never requested. + `experimental` was not used: different key, and no client reads it for this. +- **Classes, not modules.** The lead's scope decision, argued in the feature + README: an instantiation is a containment edge and `extends` is an + inheritance edge, so the module hierarchy stays on `callHierarchy` where it + shipped, and this request serves one node kind well. +- **`supertypes` is `definition_of` at a computed offset**, not a new lookup. + `extends Base` is already a reference, and the overlay-promotion round already + made a bare cross-file class name reachable through it, so the only new idea + is *which* offset to ask about: the last byte of the extends name span, which + is the tail of `pkg::base` and the whole of a bare `base`. That gets in-file + bases, cross-file bases, package-qualified bases and parameterized bases from + one line, and can never disagree with F12 on the same token. +- **`subtypes` is `callers_of_each`'s census in another key**: one + `sources()` pass, a substring prefilter before any parse, a deterministic + sort. 55 ms over the 860-file corpus, 53 ms of it file I/O — the same shape + `incomingCalls` measured, and the same backlog item (an edge table in + `WorkspaceIndex`, now filed for inheritance edges beside the instantiation + ones). +- **What the class model lacked:** interface classes. `vlog_parser` rejects + `interface class` outright, so `implements` can never resolve and no item can + carry `SymbolKind::Interface`; both facts are pinned by tests named to force a + future parser round past them. Full details, assumptions, cost table and the + ambiguity argument: `docs/features/type-hierarchy/README.md`. + ### 2026-08-25 — dev agent (M14 macro-expansion, 0.5.0) - **No new capability, one new module, one card grew a section.** diff --git a/docs/features/type-hierarchy/README.md b/docs/features/type-hierarchy/README.md new file mode 100644 index 0000000..c9fd7ad --- /dev/null +++ b/docs/features/type-hierarchy/README.md @@ -0,0 +1,581 @@ +# type-hierarchy + +TODO.md §9c: **the class `extends` tree, both directions, over LSP +`typeHierarchy`.** + +## Goal + +"What does this class extend?" and "who extends it?" are the two questions a +verification engineer asks about a UVM testbench they did not write, and until +now lucisv could answer neither without a grep. LSP has had the shape for both +since 3.17: its type hierarchy is a graph of supertypes and subtypes, and +SystemVerilog's `extends` is exactly that graph — the classes are the nodes and +`class d extends b` is the edge. So `textDocument/prepareTypeHierarchy` picks a +class out of the text under the cursor, `typeHierarchy/supertypes` answers "what +does X extend" and `typeHierarchy/subtypes` answers "who extends X", 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 a cycle +needs no handling here beyond not crashing: `class a extends a;` simply appears +again one level down, and an `a → b → a` pair unrolls as far as the user keeps +clicking. + +**Scope decision, made by the lead before the round: classes only.** The module +hierarchy stays on `callHierarchy`, where it shipped and is tested +(`docs/features/hierarchy/README.md`). Mapping modules onto `typeHierarchy` as +well was considered and rejected: an instantiation is a *containment* edge and +`extends` is an *inheritance* edge, and serving both from one request would put +two unrelated relations behind one node kind with no way for a client — or a +reader — to tell them apart. One item kind, done well. + +## Assumptions + +- **`extends` is the edge, and nothing else is.** `implements` names an + **interface class**, which is a different construct (IEEE 1800 §8.26) that + `vlog_parser` does not model at all — `interface class ic; ... endclass` is + rejected as an unsupported construct + (`vlog_parser::parser::parse_keyword_item`, and its own + `interface_class_is_not_an_interface` test). So an `implements` target can + never be a class declaration this server holds, and matching one by name would + claim an unrelated ordinary class of that name. `implements` therefore + contributes no supertype. Pinned by + `an_implements_clause_names_no_supertype` and + `an_interface_class_is_not_a_node_because_the_parser_does_not_model_one`, + the second named so a future parser round that models interface classes is + forced past it. +- **Every item is `SymbolKind::CLASS`.** Following from the above: there is no + node in this feature that could carry `INTERFACE`, because there is no AST + node for an interface class to build one from. +- **A class has exactly one base**, which is what the AST gives + (`ClassDecl::extends` is an `Option`) and what the LRM says for + ordinary classes. `supertypes` is therefore a list of at most one — except + under the workspace's documented duplicate policy, below. +- **The base is resolved by the same two layers `textDocument/definition` + uses**, and by nothing of this feature's own: the file's symbol table first, + then the workspace overlay. `vlog_semantic` already records `extends Base` as + a reference (`docs/features/class-semantics/README.md` rule 5), and the + overlay-promotion round made a bare cross-file class name reachable through + that same reference, so a base in another file needs no lookup here. The one + thing this feature computes is *which offset* to ask about: the **last byte** + of the extends clause's `name_span`. For a bare `base` that is that one + reference; for `pkg::base` it is inside the **tail's** reference, which is the + one that names a class (the head names the package), and it is the right byte + whatever spacing the source used around the `::`. +- **A parameterized base needs no unwrapping.** The parser keeps `#( ... )` on + its own field, so `extends base #(8)` stores `base` in `ClassExtends::name` + and its `name_span` covers `base` alone. This is the class-semantics policy + already, verified by reading `parse_class_extends`, and pinned by + `a_parameterized_base_resolves_by_its_bare_name`. +- **An unresolvable base yields no item, never a guess.** `extends uvm_object` + in a workspace that does not index UVM has nowhere honest to point: an item + carries a `uri` and a `range`, and a wrong one sends the user to the wrong + file with no way to tell. So the chain simply stops. This is not rare — it is + the normal top of every UVM chain in the corpus — and it is what the corpus + test asserts at `core_ibex_base_test extends uvm_test`. +- **`subtypes` matches the base name exactly as written**, which is the + `hierarchy` feature's own "the walk is by name" assumption applied to + `extends`. Two consequences, both deliberate: + - A **qualified** base is not matched: `class d extends other_pkg::base;` is + not offered as a subtype of a file-scope `base`, because matching on the + trailing segment would silently claim it. Measured: **0 of the 270 `extends` + clauses in the checked-in 860-file corpus are qualified**, so this costs + nothing observable here. It does make the two directions asymmetric — + `supertypes` *does* follow `pkg::base`, through the package — which is + stated rather than hidden, and pinned by + `a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with`. + - Two classes of the same name in different files get the **same** subtype + list. `subtypes` reads the item's `name`, not its `uri` — exactly as + `callHierarchy/incomingCalls` does for a module name — because the text + `extends base` says which *name* was extended and nothing more. +- **Ambiguity is answered the same way in both directions, and differently from + `outgoingCalls`.** A base name two files declare gives **two** supertype + items. This is a deliberate departure from `hierarchy::outgoing`, which skips + an ambiguous target: an outgoing *call* carries `fromRanges`, so two items + would double one edge, whereas a supertype is a bare item in a flat list — + the same list shape `prepare` returns, where showing both is how the user is + told the ambiguity exists. It also comes for free from the shared overlay, + whose documented policy is to offer every declaration + (`docs/features/workspace-index/README.md`). +- **A cursor immediately after the last character of a name is on that name.** + `TextRange::contains` excludes the end, which is right for a span of text and + wrong for a caret — that is where a double-click and an end-of-word motion + leave it. Same convention `hierarchy.rs` states. +- **The scope ladder decides which files are searched.** `subtypes` reads + `Workspace::sources()`, so a file a filelist or an `exclude` keeps out of the + index extends nothing, exactly as it references nothing. Open buffers beat + disk, so an `extends` just typed and not yet saved is already a subtype. +- **Classes are found wherever they can be written**: at file scope, inside a + `package` (the dominant UVM shape), inside a `module`, and nested inside + another class. A generate block is not descended into. QA traced the parser and corrected + the original justification: classes inside generate blocks DO parse into + real `ClassDecl` nodes — the walk simply does not recurse there. Zero such + classes exist in the 860-file corpus, so the gap is theoretical today; the + pinning test (`a_class_declared_inside_a_generate_block_is_not_found_by_this_walk`) + makes a future round close it on purpose. + +## Handshakes + +- **Consumes `vlog_parser`** — `parse_source_tolerant`, `ast::ClassDecl` / + `ClassExtends` (read-only, for `name`, `name_span` and `extends`), + `Item::span`, `LineIndex`. Nothing new is asked of the crate. +- **Consumes `vlog_semantic`** — `ExternalResolutions::definition_of` and + `Definition`, `Semantics::reference_at`, `SymbolKind::Class`, + `WorkspaceIndex::path`. **Nothing was changed in the crate.** The whole + cross-file half of this feature is the overlay-promotion round's work being + consumed: `extends Base` was already a reference carrying the bare name as its + last candidate path, so the workspace already had the answer and this feature + only had to ask for it at the right offset. +- **Consumes `crate::state::{Workspace, Document}`** — `document`, `index`, + `text_of`, `sources`, and `Document::new` for the one case an item names a + file no editor has open (see the work log). Nothing in `state.rs` was changed; + the workspace stays immutable through all three handlers, and no cache was + added. +- **Promises `lucisv_server`** — `type_hierarchy::{prepare, supertypes, + subtypes}` never panic, never return an item whose `selectionRange` is outside + its `range`, and never return an item for a class the workspace does not + really declare. +- **Requested of `vlog_semantic`, not done here: an inheritance edge table in + `WorkspaceIndex`.** This is the *same* Handshake `docs/features/hierarchy` + filed for instantiation edges and `docs/features/code-lens` rode past — the + index records what a file *declares* and not what it uses, so "who extends X" + has to be a workspace walk. One table keyed by base name, built with the + index, would make `subtypes` a map lookup at the cost of one extra field per + class at index time. Filed together with the instantiation table rather than + separately: the two want the same shape and should land as one round when + something finally justifies widening the index's contract. Today one request + in 55 ms does not. +- **`editors/vscode` needs no change.** `vscode-languageclient` 9.0.1 ships the + type-hierarchy feature and enables it off the advertised capability; the + extension sets no `initializationOptions` that would suppress it, and + Vim/Neovim clients drive it through their own commands. + `editors/vscode/smoke.js` checks a fixed capability list and was deliberately + left untouched (it is editor-packaging's file) — it still passes. + +## The one thing `lsp-types` could not spell + +`lsp-types` 0.97 models type hierarchy on the **client** side only: +`TypeHierarchyClientCapabilities` exists, the three request types and +`TypeHierarchyItem` exist, and `ServerCapabilities` has **no** +`type_hierarchy_provider` field. A capability a client cannot see is a feature +that is never requested, however well it is implemented — so `initialize_value` +in `main.rs` serializes the `InitializeResult` and inserts +`"typeHierarchyProvider": true` into the capabilities object, which is the same +JSON a field would have produced. `experimental` was not used: it is a different +key and no client reads it for this. Pinned twice — in `main.rs` (the JSON +carries the key, and the insertion disturbs nothing else) and over the wire in +`tests/e2e.rs`. + +## What it looks like + +`type_mid.sv`: + +```systemverilog +class type_mid extends type_base; + int y; +endclass +``` + +Cursor on `type_mid` anywhere — its own declaration, its `extends` in another +class, or a `type_mid handle;` — and the hierarchy view shows: + +``` +supertypes (what type_mid extends) subtypes (who extends type_mid) + type_base type_base.sv:1 type_leaf type_leaf.sv:1 +``` + +## Cost + +Release build, this machine, the checked-in 860-file corpus, worst of three +(printed by `the_corpus_uvm_classes_answer_all_three_requests`): + +| request | measured | +|---|---:| +| `subtypes` for `core_ibex_base_test` (10 subclasses across the corpus) | **55 ms** | +| — of which reading the 860 files (`Workspace::sources()`) | **53 ms** | +| — of which the substring prefilter over all of them | 0.28 ms | +| — of which parsing + walking the **3** files that mention the name | ~2 ms | +| `supertypes` for `core_ibex_debug_intr_basic_test` | **0.69 ms** | +| the same `subtypes` in a debug build | 101 ms | + +The shape is the same one `callHierarchy/incomingCalls` measured (56 ms), and +for the same reason: what is left after the prefilter is **almost entirely file +I/O**, because `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 (the edge table above, or a cheaper `sources()`); +nothing in this feature can shave it alone. The prefilter itself is not a +heuristic — `extends base` has to write `base` — and here it skips 857 of 860 +files. + +`supertypes` never walks the workspace at all: it parses one file (the item's +own) and, at most, re-reads the one file that declares the base. The same +worst-case caveat `hierarchy` records applies to `subtypes` in principle — a +class name that is a substring of nearly every file defeats the prefilter — but +UVM class names are long and specific, and no such name exists in the corpus. + +## Status / TODO + +- [x] `crates/lucisv_server/src/type_hierarchy.rs`: the class walk, + `prepare`, `supertypes`, `subtypes` +- [x] `typeHierarchyProvider` in `main.rs` (inserted into the serialized + capabilities, because `lsp-types` 0.97 has no field for it); three + dispatch arms in `server.rs` +- [x] `prepare` on a declaration / on a use (`extends` base, a property's type, + a method local's type) / on anything else (`null`), including a property + name, a module, a wire and the `class` keyword +- [x] Ambiguity: every declaration from `prepare` **and** from `supertypes`, + with the departure from `outgoingCalls` argued +- [x] Bases in-file, cross-file through the overlay, package-qualified, + parameterized, and unresolvable (no item) +- [x] `subtypes` in-file, cross-file, sorted deterministically and stable across + two calls; scope ladder and unsaved-buffer overlay honoured +- [x] Self-extends and a two-class cycle: one hop each, no duplicate, no hang +- [x] Classes in a package, in a module and nested in a class +- [x] UTF-16 positions, an untitled buffer, an unopened document, a file that + has since moved, a nameless item, a buffer that does not parse +- [x] `selectionRange` inside `range` asserted for every item the feature can + hand out, in three tests including the corpus one +- [x] Unit tests (31 in `type_hierarchy.rs`, 1 capability test in `main.rs`) and + one e2e stdio round trip: prepare → supertypes → subtypes across three + files +- [x] Corpus smoke: 30 classes of `core_ibex_test_lib.sv` through all three + requests, plus the real `core_ibex_debug_intr_basic_test → + core_ibex_base_test → (uvm_test, unindexed)` chain +- [x] Cost measured over the 860-file corpus, with the I/O split out +- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets --workspace`, + `cargo test --workspace`, `editors/vscode/smoke.js` +- [x] `docs/features/lucisv-server/README.md` capability table + work log; + TODO.md §9c +- [ ] Not done, backlog: the **inheritance edge table in `WorkspaceIndex`**, + filed with the instantiation-edge table it should ship beside (Handshakes + above). +- [ ] Not done, blocked: **interface classes**. `vlog_parser` rejects + `interface class`, so `implements` can never resolve and no item can carry + `SymbolKind::INTERFACE`. When the parser models them, this feature needs + one arm in the walk, one kind, and `implements` added to `supertypes`. +- [ ] Not done, deliberately: chasing a chain server-side (the client drives + it), a whole-tree "show me every class" view, and typedef/struct + hierarchies — SystemVerilog has no inheritance for them. + +## Work log + +- **2026-08-26 (dev)** — read CLAUDE.md, then `lucisv-server`, `hierarchy`, + `class-semantics` and `overlay-promotion` READMEs, then `hierarchy.rs`, + `instantiations.rs`, `type_def.rs`, `nav.rs`, `state.rs`, + `vlog_semantic`'s `workspace.rs` and `vlog_parser`'s `parse_class` before + writing anything. + + **What the class model gave, and what it did not.** It gave everything the + cross-file half needs and it gave it *already resolved*: `ClassDecl` carries a + parser `name_span`, `ClassExtends` carries the base name with its `::` chain + and its own span, `extends` is recorded as a reference by `vlog_semantic`, and + since the overlay-promotion round that reference reaches the workspace unit + table carrying the bare name. So `supertypes` is not a lookup this feature + wrote — it is `definition_of` asked at one computed offset. What the model did + **not** give is interface classes: `interface class` does not parse at all, so + `implements` is a dead end and `SymbolKind::INTERFACE` is unreachable. Checked + rather than assumed, and recorded in Assumptions with the parser's own test as + the citation. + + **Design decision 1 — resolve the base through the semantic reference, not + through the index.** The alternative was `WorkspaceIndex::units(base_name)`, + which is what `hierarchy::outgoing` does for an instantiated module. It would + have been wrong here for two reasons: it cannot see a base declared **in the + same file** (a very common shape — a base and its children in one `_lib.sv`, + which is exactly what the corpus test file is), and it cannot follow + `pkg::base` (the unit table holds no package-scoped class). `definition_of` + handles both, in the documented order, and is the same answer F12 gives on the + same token — so the two can never disagree about what `extends base` names. + That is also what made the round small: the only new idea is *which offset*. + + **Design decision 2 — the offset is the last byte of the extends name span.** + For `pkg::base` the clause records two references (head and tail); the head + names the package and the tail names the class, so the answer has to come from + the tail. Taking `name_span.end - 1` lands inside the tail under every + spelling, including the `pkg :: base` one that class-semantics warns can glue + its `::`. Taking `name_span.start` would have answered the *package* for every + qualified base — a wrong file, silently. + + **Design decision 3 — `subtypes` is a name walk, like `callers_of_each`.** + The brief asked for the census to be modelled on it and it is: one + `sources()` pass, a substring prefilter before any parse, and a deterministic + sort at the end. The precision question it raises — should `other_pkg::base` + count as extending `base`? — was settled by measurement rather than taste: + **0 of 270 `extends` clauses in the corpus are qualified** (count per QA's + reproducible grep — the work log's original 309 did not reproduce), so the precise + version (resolve every candidate's base semantically and compare identities) + would have bought nothing measurable for a large multiple of the cost and a + second resolution path to keep honest. The asymmetry it leaves with + `supertypes` is documented and pinned rather than papered over. + + **Design decision 4 — ambiguity is shown, not skipped.** `hierarchy::outgoing` + skips an ambiguous target and says why: a call carries `fromRanges`, so two + items for one edge would double the edge. A supertype has no such payload — it + is one item in a flat list, the same shape `prepare` returns — so listing both + candidate declarations tells the user the ambiguity exists instead of hiding + it behind silence. Argued in Assumptions so the inconsistency with the + neighbouring feature is on the record. + + **The capability had to be hand-written.** `ServerCapabilities` in `lsp-types` + 0.97 has no `type_hierarchy_provider` field (grepped the crate: the only + `type_hierarchy` in `lib.rs` is the *client* capability at line 1453). Rather + than fork the crate or abuse `experimental`, `initialize_value` inserts the + key into the serialized object. It is three lines, it returns `Result` rather + than unwrapping, and it is pinned at both layers. Recorded here because it is + the one place this feature is not simply "call the crate". + + **`Document::new` for a closed file.** Items carry no `data` payload — they + are re-derived per request, like the call hierarchy's — so a client is free to + send back an item naming a file no editor has open, which is exactly what + happens the moment a user expands a subtype and then asks *it* for its base. + `hierarchy::outgoing` needs only a parse there and re-parses; `supertypes` + needs a *resolution*, so it builds a full `Document` (parse + analyze + + overlay) for that one file. Pinned by + `supertypes_answer_for_a_file_no_editor_has_open`, which walks base → + subtype → base across an unopened file. + + **Three one-line helpers restated rather than shared** (`touches`, `span`, + `key`). Each is a statement of a convention this handler makes — a caret at + the end of a name is on it; a range sorts by line then character — and the two + handlers share no logic a common helper would keep honest. Said out loud in + the source so the duplication reads as a choice. + + **Files touched.** New: `crates/lucisv_server/src/type_hierarchy.rs`, this + README. Edited: `crates/lucisv_server/src/main.rs` (one module declaration, + `initialize_value`, one test), `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), `TODO.md` (§9c). + + **Not touched, deliberately:** `hierarchy.rs` and `instantiations.rs` (the + module hierarchy is untouched by the scope decision), `vlog_semantic`, + `vlog_parser`, `vlog_refactor`, `editors/`, `docs/site/`. No version bump, no + new dependency, no commits. + + **Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets + --workspace` zero warnings; `cargo test --workspace` green at **2 060 passed, + 4 ignored, 0 failed** (2 027 before; +33 = 31 in `type_hierarchy.rs`, 1 in + `main.rs`, 1 e2e round trip). `cargo build --release -p lucisv_server && node + editors/vscode/smoke.js target/release/lucisv-server`: `smoke: OK`. + +## QA log + +- **2026-08-26 (QA)** — re-ran every gate, then attacked the seven surfaces the + lead named plus three of my own. Verdict: **committable as-is**. Two + findings filed, both non-blocking (documentation/completeness, not + correctness or corruption); everything else verified clean. +12 tests added + (11 in `type_hierarchy.rs`, 1 in `main.rs`); all green alongside the dev's + +33. Full workspace total after this round: **2 072 passed, 4 ignored, 0 + failed** (2 060 before QA, +12 from this pass; confirmed on two full runs). + + **Gates.** + - `cargo fmt --all -- --check`: clean (after `cargo fmt --all` reformatted + two lines in the tests I added — reflowing, not a substantive change; + re-checked clean). + - `cargo clippy --all-targets --workspace`: zero warnings, before and after + my additions. + - `cargo test --workspace`: **2 072 passed, 4 ignored, 0 failed**, both + before and after my +12 tests landed (2 060 → 2 072), 0 failed throughout. + - `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: + `smoke: OK`. Confirmed `smoke.js` checks a fixed capability list + (`documentFormattingProvider`, `definitionProvider`, `hoverProvider`, + `semanticTokensProvider`, `documentHighlightProvider`, + `inlineCompletionProvider` — `editors/vscode/smoke.js:140-145`) that does + **not** include `typeHierarchyProvider`, matching the README's claim that + this file was deliberately left untouched. + + **1. `initialize_value()` JSON injection — verified clean, one test added.** + `git diff 24e8eab -- crates/lucisv_server/src/main.rs` shows `capabilities()` + and `initialize_result()` are **byte-for-byte unchanged**; the only new code + is `initialize_value()` itself, which calls the same + `serde_json::to_value(initialize_result())` as before and then does exactly + one `caps.insert(...)`. Since `ServerCapabilities` has no + `type_hierarchy_provider` field (confirmed by grep — the crate's only + `type_hierarchy` hit is the client-side capability), the inserted key cannot + collide with or overwrite an existing one — structurally, not just by test + luck. Added + `the_json_insertion_disturbs_nothing_else_in_the_initialize_result` + (`main.rs`), which strips the one inserted key back out of + `initialize_value()`'s output and asserts the remainder equals + `serde_json::to_value(initialize_result())` exactly — every key, every + value, not just the two the dev's existing test spot-checked. Passes. + `to_value` failing: propagated via `?` all the way out of `main()` + (`Result<(), Box>`), no `unwrap`/`expect` — the + process exits with an error rather than sending a malformed or partial + `initialize` response. `serverInfo` and other siblings: covered by the new + test's full-object comparison. The e2e test decodes + `capabilities["typeHierarchyProvider"] == true` off the real stdio wire + (`tests/e2e.rs`, `the_class_hierarchy_round_trips_over_the_wire_in_both_directions`) + — confirmed by reading it and by re-running it standalone. + + **2. Last-byte offset — verified clean, 5 tests added.** Read + `parse_class_extends`/`parse_scoped_name` in `vlog_parser`: `extends` is + called with `?` from `parse_class`, so every one of "empty target" + (`extends ;`), "EOF right after the base name", and "`pkg::` with nothing + after the `::`" fails the *entire* `class` item's parse (it becomes + `ItemKind::Error`) rather than producing a `ClassExtends` with an empty or + truncated `name_span` — the defensive `if extends.name_span.is_empty()` + guard at `type_hierarchy.rs:156-158` is therefore not reachable through any + input the parser can produce today, but it costs nothing and is the right + thing to keep given that guarantee lives in a different crate. Added + `an_extends_clause_with_no_base_name_never_panics`, + `an_extends_clause_at_eof_never_panics`, + `a_qualified_base_with_nothing_after_the_double_colon_never_panics`, + `a_single_character_base_name_resolves`, and + `multibyte_text_immediately_after_the_extends_name_does_not_shift_the_offset` + (the last puts a `🎉 日本語` block comment starting at the very next byte + after the base name, since `name_span` is measured in bytes independent of + what follows). All pass, none panic. `TextRange::contains` excludes `end` + (`vlog_parser/src/span.rs`), which is exactly why `.end - 1` rather than + `.end` is needed to land on the tail reference of `pkg::base` — confirmed by + reading `use_scoped_unit` in `vlog_semantic/src/bind.rs`, where the tail + reference's span ends exactly at `ext.name_span.end` and the head + reference's ends earlier. + + **3. The supertypes/subtypes asymmetry — pinned correctly, one gap in + coverage found and closed.** `a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with` + exercises exactly the shape asked for: `pkg::base` written by a real class, + a file-scope `base`, `subtypes(base)` empty. The README's "two + consequences" prose also claims same-named classes in different files get + the *same* subtype list (name-only match), but this was **not previously + pinned by a test** — added + `subtypes_of_two_same_named_classes_in_different_files_share_one_list`, + which declares `base` in `a.sv` and `b.sv`, has `sub` extend the bare name, + and asserts both `base` items' `subtypes()` include `sub`. Passes, confirms + the documented (not hidden) imprecision and gives it a regression test it + didn't have. + + **4. Ambiguous-base = two items — verified clean.** + `a_class_two_files_declare_prepares_both_rather_than_guessing` already + distinguishes the two items by file name, which is `uri` under the hood — + no additional test needed for identity (uri+range differ, per spec + equality). + + **5. Census correctness — verified clean, two tests added, one real gap + found.** + - Substring prefilter vs. match step: added + `a_file_containing_the_name_as_a_substring_but_no_matching_extends_is_not_a_false_positive` + — a file with `class database;` and `class d extends database;` alongside + `class base;`; `subtypes(base)` is empty. Passes: the match step + (`extends_name(decl.class) != Some(item.name.as_str())`) is a full string + compare, so the prefilter's looseness never leaks through. + - Self-extends / cycle: re-read the existing + `a_self_extending_class_answers_one_hop_in_both_directions_without_duplicating` + and `a_two_class_cycle_terminates_in_both_directions` — both correctly + assert **one** item per hop, not a duplicate or a hang. Fine as written. + - **Finding (informational, non-blocking): generate-block classes are + invisible to this feature, and the README's given reason is not quite + right.** The Assumptions section says "A generate block is not descended + into — no class lives there." Traced the parser: `parse_gen_block` + dispatches through the same `item_or_recover`/`parse_keyword_item` path + ordinary module items use, so `class Foo; ... endclass` written inside + `generate`/`if`-generate/`for`-generate **does** parse into a real + `ItemKind::Class(ClassDecl)` node — it is just nested one level inside + `ItemKind::GenerateRegion`/`GenIf`/`GenFor`/`GenCase`, which + `type_hierarchy::collect()` (lines ~262-274) does not recurse into. + Confirmed empirically: added + `a_class_declared_inside_a_generate_block_is_not_found_by_this_walk`, + which parses a module with `generate if (1) begin class Foo; endclass end + endgenerate` and asserts `prepare` on `Foo` answers `None` today. This + does not corrupt anything and does not violate a hard invariant — it is a + completeness gap for a construct that is legal per IEEE 1800 + (`package_or_generate_item_declaration` includes `class_declaration`) but + vanishingly rare in real UVM code (0 occurrences in the 860-file corpus). + Recommend the dev correct the README's wording from "no class lives + there" to something like "the walk does not descend into + `GenerateRegion`/`GenIf`/`GenFor`/`GenCase`, so a class declared inside + one is not found — legal per the LRM, not observed in the corpus" — a + one-line wording fix, not a redesign, so left for the dev/lead rather than + changed here. + + **6. Corpus test honesty — mostly confirmed, one citation could not be + reproduced.** Ran `the_corpus_uvm_classes_answer_all_three_requests` twice: + stable both times (860 files, 30 classes in + `core_ibex_test_lib.sv`, 30 with an indexed base, `core_ibex_base_test` has + 10 subtypes; `subtypes` 99.7 ms / 100.9 ms on the two runs, `supertypes` 3.3 + ms both — both inside the stated debug-build budget, and roughly matching + the dev's own "101 ms" debug figure). The **860-file** count reproduces + exactly via an independent `find corpus -name '*.sv' -o -name '*.svh' -o + -name '*.v' -o -name '*.vh'`. The **"0 of 309 `extends` clauses are + qualified"** claim: the "0 qualified" half reproduces — a plain `grep -c + '::'` over every `extends` occurrence in the corpus returns 0, confirming + the safety-relevant part of the claim. The **309** denominator did not: an + independent `grep -ohE '\bextends\b'` count over the same file set returns + **270**, not 309 (checked for multi-line `extends` clauses and + backtick-macro bases as possible explanations for undercounting — found + zero of either, so that gap is not explained). No script computing "309" is + checked into `tools/`. This does not change any correctness verdict (the + load-bearing claim, zero qualified, holds under both my recount and the + existing `a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with` + unit test), but the specific number in two README passages + (`docs/features/type-hierarchy/README.md:80,298` and + `docs/features/lucisv-server/README.md:49`) is currently uncited and + unreproducible — flagging for the dev to either recheck the corpus snapshot + they measured against or drop the precise figure in favor of "a small + double-digit number, all unqualified." + + **7. CLAUDE.md compliance — verified clean.** `grep -n + "unwrap()\|expect(\|panic!" crates/lucisv_server/src/type_hierarchy.rs` + shows every hit inside `#[cfg(test)] mod tests` (line ≥ 326 in the + post-QA file); none in `prepare`/`supertypes`/`subtypes` or their helpers. + Same check on `main.rs`'s `initialize_value` — clean, uses `?`. Public + items (`prepare`, `supertypes`, `subtypes`) all carry doc comments. README + sections (`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`, `Work log`, + `QA log`, `Review`) each appear exactly once. `TODO.md`'s §9c item text is + intact — checkbox flipped `[ ]` → `[x]`, original sentence unchanged, a + `→ delivered …` paragraph appended after it rather than replacing anything. + + **Beyond the list.** + - Deep chain: added `a_ten_deep_chain_answers_each_hop_without_recursing` + (`c0 extends c1 extends … extends c9`, 10 files) — walks all nine hops of + `supertypes`, one call at a time, asserting each answers exactly the next + link and the chain terminates. No recursion in the implementation (each + call is `O(1)` hops by construction), and the test's own structure never + recurses either. Passes. + - `prepare` on the `extends` **keyword** itself: added + `prepare_on_the_extends_keyword_itself_prepares_nothing` — offset inside + the literal word `extends` (not the name after it) answers `None`. + Passes, because the keyword is outside every reference span + `definition_of`/`reference_at` would match. + - Class name shadowed by a local variable: added + `a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing` + — a class `base`, a method-local `int base;`, and a use `base = base + + 1;`; `prepare` at that use answers `None` because `definition_of` + resolves it to the local variable's `Symbol` (kind `Var`, not `Class`), + and `classes_at` checks `symbol.kind != SemanticKind::Class` before ever + looking at the name. Passes — confirms the feature keys off semantic kind, + not name matching, exactly as claimed. + + **Files touched (QA only).** `crates/lucisv_server/src/type_hierarchy.rs` + (+11 tests), `crates/lucisv_server/src/main.rs` (+1 test). No production + code changed — every finding above is either a passing defensive check, a + documentation wording gap, or an unreproducible citation, none of which + rose to "small unambiguous fix" territory in the sense of a code change; + the README wording fix is left for the dev per the workflow (don't touch + files outside the stated scope of a fix that isn't mine to make). + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself +(2072 workspace tests, 0 failed), clean. The round's hard problem was +handled the right way twice over. First, the lsp-types gap: injecting +the one missing key into the serialized initialize result is the honest +minimal answer, and QA's strip-and-compare test — remove the inserted +key, assert full object equality with the plain serialization — turns +"disturbs nothing else" from a claim into a property. Second, the +last-byte offset for qualified bases: the design reasoning was good and +QA's parser trace showed the degenerate spans it guards against cannot +even be constructed, which is the best kind of defensive code. + +The supertypes/subtypes asymmetry is accepted as designed and now +pinned from both directions, including the same-name/different-file +consequence QA added a regression test for. Both QA findings were +accepted and fixed by the lead before commit: the extends-clause +denominator corrected to QA's reproducible 270 (in both READMEs), and +the generate-block justification rewritten to what the parser actually +does — the walk not recursing is a scoped choice with a pinning test, +not a fact about where classes can live. The inheritance-edge-table +want is filed beside the instantiation-edge request, correctly, as one +future index round. Interface classes stay blocked on the parser and +are pinned. Accepted as shipped.