diff --git a/TODO.md b/TODO.md index c6b075a..297e7c7 100644 --- a/TODO.md +++ b/TODO.md @@ -776,9 +776,22 @@ and are not gaps. ### 9c. Moderate value, Verilog-shaped -- [ ] **Goto type definition** — from a net/variable use to its +- [x] **Goto type definition** — from a net/variable use to its typedef/struct/enum/interface declaration; real value once `vlog_semantic` tracks declared types of bindings. + → delivered 2026-08-26 by `docs/features/type-definition/README.md`: + `typeDefinitionProvider` + `crates/lucisv_server/src/type_def.rs`. + `vlog_semantic` was *not* changed — a binding still carries no type, + but the type name it was declared with is already a `Reference`, so + the answer is `nav::definition` of that name's own offset, found from + the parse tree. Covers typedefs (alias/enum/struct), interfaces, + classes, module instances, `pkg::t`, `import pkg::*`, header + parameters and task arguments; one hop per keypress on an alias + chain; built-ins answer an empty list. Two requests recorded there: + `vlog_semantic` should report an unqualified lexical miss as an + external candidate (stood in for by a fenced index lookup), and + `vlog_parser` cannot parse an ANSI header whose first port has no + direction. - [ ] **Linked editing range** — edit `module m` and its `endmodule : m` label together (`end : label`, `endfunction : name`, etc.). A genuinely good fit for SV's closing labels. diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 23b3c33..d2db1c8 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -35,6 +35,7 @@ mod symbols; mod sync; mod templates; mod tokens; +mod type_def; mod uri; mod watch; @@ -50,7 +51,8 @@ use lsp_types::{ SelectionRangeProviderCapability, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, - TextDocumentSyncOptions, TextDocumentSyncSaveOptions, WorkDoneProgressOptions, + TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, + WorkDoneProgressOptions, }; use crate::server::{ClientAbilities, Server}; @@ -111,6 +113,11 @@ fn capabilities() -> ServerCapabilities { document_formatting_provider: Some(OneOf::Left(true)), document_range_formatting_provider: Some(OneOf::Left(true)), definition_provider: Some(OneOf::Left(true)), + // The same jump one token to the left: from a name to where its type + // is declared. `Simple(true)` rather than a registration — there is + // nothing to scope it to that `definitionProvider` is not already + // scoped to. See `docs/features/type-definition/README.md`. + type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)), references_provider: Some(OneOf::Left(true)), // `` `include`` lines, underlined and ctrl-clickable. Every link is // returned with its target already resolved, so there is nothing for @@ -332,6 +339,7 @@ mod tests { assert!(caps.document_formatting_provider.is_some()); assert!(caps.document_range_formatting_provider.is_some()); assert!(caps.definition_provider.is_some()); + assert!(caps.type_definition_provider.is_some()); assert!(caps.references_provider.is_some()); assert!(caps.document_link_provider.is_some()); assert!(caps.document_highlight_provider.is_some()); diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index cae7a43..401ac1c 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -181,7 +181,11 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option Option { +/// +/// Shared with `type_def.rs`, which asks the same question one token to the +/// left: the two must agree on what a position names, or go-to-definition and +/// go-to-type-definition would disagree about the cursor. +pub(crate) fn symbol_at(semantics: &Semantics, offset: u32) -> Option { semantics .reference_at(offset) .and_then(|r| r.resolved()) diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index acb8efa..145a468 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -22,12 +22,12 @@ use lsp_types::request::{ ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare, CodeActionRequest, Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand, - FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest, - InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability, - Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest, - SemanticTokensFullRequest, SemanticTokensRangeRequest, Shutdown, SignatureHelpRequest, - UnregisterCapability, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, - WorkspaceSymbolRequest, + FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams, + GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest, + PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _, + SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, + SemanticTokensRangeRequest, Shutdown, SignatureHelpRequest, UnregisterCapability, + WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, @@ -59,7 +59,7 @@ use crate::state::Workspace; use crate::{ code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, inline, nav, pairs, ports, rename, selection, settings, signature, symbols, sync, tokens, - watch, + type_def, watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -291,6 +291,23 @@ impl Server { .unwrap_or_default(); to_value(GotoDefinitionResponse::Array(locations)) }), + // The same answer shape as go-to-definition, deliberately: an + // array in every case, empty where there is nothing to jump to, + // and every candidate where the workspace holds the type name + // twice. A buffer this server has not been sent is the empty + // array too, which is what `unwrap_or_default` on the position + // conversion means here as it does above. + GotoTypeDefinition::METHOD => { + decode(request).and_then(|p: GotoTypeDefinitionParams| { + let at = p.text_document_position_params; + let (uri, position) = (at.text_document.uri, at.position); + let locations = self + .offset(&uri, position) + .map(|offset| type_def::type_definition(&self.workspace, &uri, offset)) + .unwrap_or_default(); + to_value(GotoTypeDefinitionResponse::Array(locations)) + }) + } // The underline half of include navigation. Unresolvable includes // are simply absent from the list — never an error, and never a // link that goes nowhere. diff --git a/crates/lucisv_server/src/type_def.rs b/crates/lucisv_server/src/type_def.rs new file mode 100644 index 0000000..09be81f --- /dev/null +++ b/crates/lucisv_server/src/type_def.rs @@ -0,0 +1,1432 @@ +//! `textDocument/typeDefinition`: from a name to where its *type* is declared. +//! +//! Go-to-definition answers "where does this name come from"; this answers +//! "where does this name's type come from". For `my_pkg::state_t s;` with the +//! cursor on `s` that is the `typedef` of `state_t`, for `bus_if bus` the +//! `interface bus_if`, for `sub u_sub (...)` the `module sub`, and for +//! `my_cls h;` the `class my_cls`. +//! +//! **The whole feature is one redirection.** A declaration writes its type as +//! an ordinary identifier, and `vlog_semantic` already records that identifier +//! as a [`Reference`](vlog_semantic::Reference) — resolved in-file, or handed +//! to the workspace overlay — so the answer is +//! `nav::definition(the type name's own offset)`. Nothing here resolves a +//! name, reads the index, or knows what a package is; it only decides *which +//! offset* the question is really about. That is also why a type declared in +//! another file needs no code at all: it is the same two-layer answer +//! `textDocument/definition` gives, asked one token to the left. +//! +//! Finding that offset needs the parse tree, because the symbol table does not +//! carry a declaration's type: a `Symbol`'s `decl_span` is its *declarator* +//! (`docs/features/vlog-semantic/README.md`), so the type name sits outside +//! it. The walk below finds the declaration covering a position and reports +//! the window the type was written in — the same window the binder searched — +//! and the type's span is then the reference the binder recorded there. +//! +//! **One hop, never a chain.** With `typedef state_t alias_t; alias_t x;` the +//! cursor on `x` lands on `alias_t`'s typedef, not on `state_t`'s: the user +//! presses the key again to take the next hop, which is what every editor's +//! go-to-type-definition does and the only version of this that can be read +//! off the screen. +//! +//! Built-ins answer nothing. `logic`, `wire`, `int` and an implicit type have +//! no declaration to jump to, so the answer is an empty list rather than a +//! guess — and it costs no special case: a keyword is not an identifier, so +//! the binder recorded no reference for it and the lookup below finds none. + +use lsp_types::{Location, Uri}; +use vlog_parser::ast::{ + AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind, + Module, ParamPort, PortList, Stmt, StmtKind, TfArg, Typedef, TypedefKind, +}; +use vlog_parser::TextRange; +use vlog_semantic::{Resolution, Semantics, SymbolKind}; + +use crate::locate::location; +use crate::nav; +use crate::state::{Document, Workspace}; + +/// Go-to-type-definition: the declaration of the type of the name at `offset`. +/// +/// Empty where there is nothing to jump to — a built-in type, a position on no +/// name at all, or a type this workspace does not declare — which is the same +/// "no answer" `textDocument/definition` gives, and for the same reason: a +/// list with a wrong location in it is worse than an empty one. +pub fn type_definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + let Some(doc) = ws.document(uri) else { return Vec::new() }; + let Some(span) = type_name(doc, offset) else { return Vec::new() }; + let found = nav::definition(ws, uri, span.start); + if found.is_empty() { + indexed_type(ws, doc, span) + } else { + found + } +} + +/// Where the type name this position is asking about is written. +/// +/// Three ways to get there, in this order: +/// +/// 1. the cursor is on the type half of a declaration (`state_t` in +/// `state_t s;`, `sub` in `sub u_sub ();`), which answers for itself — one +/// hop, so a chain of aliases is walked by the user and not by us; +/// 2. the cursor is on a *use* of a name this file binds as a type, which is +/// what reaches a cast (`state_t'(0)`) or a class named in an expression; +/// 3. otherwise the cursor is on a declared name, or on a use of one, and the +/// answer is the type that name's own declaration writes. +/// +/// Case 2 is deliberately a use and never a declaration: the cursor on the +/// `alias_t` of `typedef state_t alias_t;` is on a declaration whose own type +/// is written beside it, and answering "itself" there would waste the hop. +fn type_name(doc: &Document, offset: u32) -> Option { + if let Some(site) = site_at(&doc.tree.items, offset) { + if let Some(span) = type_span(&doc.semantics, &site) { + if span.contains(offset) { + return Some(span); + } + } + } + if let Some(span) = type_use_at(doc, offset) { + return Some(span); + } + let declared = declaration_name_span(doc, offset)?; + let site = site_at(&doc.tree.items, declared.start)?; + type_span(&doc.semantics, &site) +} + +/// The span of a use of a name this file declares as a type. +fn type_use_at(doc: &Document, offset: u32) -> Option { + let reference = doc.semantics.reference_at(offset)?; + let kind = doc.semantics.symbol(reference.resolved()?)?.kind; + // `Module` is also an `interface` and a `program` — one node, one kind + // (`vlog_parser::ast::Module`). + match kind { + SymbolKind::Typedef | SymbolKind::Class | SymbolKind::Module => Some(reference.name_span), + _ => None, + } +} + +/// The workspace index's own answer for a type name both layers gave up on. +/// +/// `vlog_semantic` reports an unqualified name that nothing in this file binds +/// as a *lexical miss* rather than as an external candidate (`resolve.rs`'s +/// `miss`), so the overlay never sees it and `nav::definition` has nothing to +/// say — and that is exactly how an `interface` or a package-less `class` +/// declared in another file is written. So the index is asked directly, under +/// three restrictions that keep it from becoming a fourth resolution layer: +/// only for a name the file's own resolution reported as such a miss, only for +/// a **file-scope** declaration, and only for the kinds that can be a type — a +/// `package` of that name is not one. Every declaration is returned when the +/// workspace has several, as `definition` does. +/// +/// A lexical miss has **two** spellings, and both are this fallback's: plain +/// `NotFound`, and `InheritedCandidate` — which `resolve.rs`'s `miss` returns +/// for *any* miss inside a class carrying an `extends`, whether or not the +/// name has anything to do with inheritance. In a type position that means +/// "some base class might declare this type", and `vlog_semantic` never chases +/// a base chain (in this file or out of it), so no layer can turn it into a +/// location; the workspace's file-scope type of that name is the only honest +/// answer there is. That is not a guess against a better one: when the name +/// really is declared somewhere this crate *can* see, the reference resolves +/// and `nav::definition` has already answered before this is consulted. +/// +/// The requirement this stands in for is written up in the feature README's +/// Handshakes; when `vlog_semantic` promotes both spellings of that miss to a +/// candidate, this function goes away and nothing else here changes. +fn indexed_type(ws: &Workspace, doc: &Document, span: TextRange) -> Vec { + match doc.semantics.reference_at(span.start).map(|r| &r.resolution) { + Some(Resolution::NotFound | Resolution::InheritedCandidate { .. }) => {} + _ => return Vec::new(), + } + // A qualified member (`pkg::name`) names something inside `pkg`, and a + // bare-name sweep would discard the qualifier — the one way this fallback + // could jump somewhere the source never pointed. `unit_member` can miss + // with the same two spellings this fence accepts (QA log, 2026-08-26), + // so the qualifier is checked here, not assumed away. + let qualified = + doc.text.get(..span.start as usize).is_some_and(|before| before.trim_end().ends_with("::")); + if qualified { + return Vec::new(); + } + let Some(name) = doc.text.get(span.as_range()) else { return Vec::new() }; + ws.index() + .units(name) + .iter() + .filter(|def| { + matches!(def.kind, SymbolKind::Module | SymbolKind::Class | SymbolKind::Typedef) + }) + .filter_map(|def| location(ws, ws.index().path(def.file)?, def.name_span)) + .collect() +} + +/// The name span of the declaration the position names, whether the cursor +/// sits on a use or on the declaration itself — the same resolution +/// `textDocument/definition` runs. +fn declaration_name_span(doc: &Document, offset: u32) -> Option { + let id = nav::symbol_at(&doc.semantics, offset)?; + let span = doc.semantics.symbol(id)?.name_span; + if span.is_empty() { + None + } else { + Some(span) + } +} + +/// One declaration's type: the name as written, and the window it was written +/// in. +struct Site<'a> { + /// `state_t`, `pkg::state_t`, `sub`. A built-in keyword is a name like any + /// other here — [`type_span`] is what finds it has no reference. + name: &'a str, + /// From the start of the declaration to the first name it declares. This + /// is the window `vlog_semantic`'s binder searched when it recorded the + /// type's use, which is what makes the lookup below a match and not a + /// scan of the text. + window: TextRange, +} + +/// Where the site's type name is written, or `None` when the binder recorded +/// no use there — a keyword type, an implicit one, or a name a macro produced. +/// +/// A qualified type is two references (`pkg`, then `state_t`), and the second +/// is the one worth jumping to, so a name with a `::` in it is matched by its +/// last segment. An instantiation is the other way round — its name is stored +/// with the `::` glued — so the whole name is tried first. +fn type_span(semantics: &Semantics, site: &Site) -> Option { + let tail = site.name.rsplit("::").next().unwrap_or(site.name); + let matches = |name: &str| name == site.name || name == tail; + semantics + .references() + .iter() + .find(|r| { + !r.name_span.is_empty() && site.window.contains(r.name_span.start) && matches(&r.name) + }) + .map(|r| r.name_span) +} + +/// The innermost declaration covering `offset`, or `None` where the position +/// is in no declaration at all. +/// +/// A `bind` directive is deliberately not one: its instance is declared into +/// another module's scope, so the name under the cursor is not this file's to +/// answer for (`docs/features/bind/README.md`). +fn site_at(items: &[Item], offset: u32) -> Option> { + items.iter().filter(|item| item.span.contains(offset)).find_map(|item| item_site(item, offset)) +} + +fn item_site(item: &Item, offset: u32) -> Option> { + match &item.kind { + ItemKind::DataDecl(d) => declarator_site(&d.ty, item.span, &d.declarators), + ItemKind::PortDecl(p) => declarator_site(&p.ty, item.span, &p.declarators), + ItemKind::ParamDecl(p) => declarator_site(&p.ty, item.span, &p.declarators), + ItemKind::Typedef(t) => alias_site(t, item.span), + ItemKind::Instantiation(i) => instance_site(i, item.span), + ItemKind::Module(m) => module_site(m, offset), + ItemKind::Class(c) => param_port_site(c.param_ports.as_deref().unwrap_or(&[]), offset) + .or_else(|| site_at(&c.items, offset)), + ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => { + site_at(items, offset) + } + ItemKind::GenIf(g) => gen_if_site(g, offset), + ItemKind::GenFor(g) => gen_block_site(&g.body, offset), + ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)), + ItemKind::Function(f) => { + tf_arg_site(&f.args, offset).or_else(|| stmts_site(&f.stmts, offset)) + } + ItemKind::Task(t) => tf_arg_site(&t.args, offset).or_else(|| stmts_site(&t.stmts, offset)), + ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { + stmt_site(stmt, offset) + } + _ => None, + } +} + +/// A declaration with a declarator list: `state_t a, b;`, `input bus_if p;`. +fn declarator_site<'a>( + ty: &'a DataType, + span: TextRange, + declarators: &[Declarator], +) -> Option> { + let first = declarators.first().map_or(span.end, |d| d.span.start); + site(&ty.name, TextRange::new(span.start, first)) +} + +/// `typedef state_t alias_t;` — the alias's own type. The other typedef +/// spellings declare their type inline (`enum`, `struct`) or promise one +/// elsewhere (`typedef class c;`), and so name nothing to jump to. +fn alias_site(t: &Typedef, span: TextRange) -> Option> { + match &t.kind { + TypedefKind::Alias(ty) => site(&ty.name, TextRange::new(span.start, t.name_span.start)), + _ => None, + } +} + +/// `sub u_sub (...)`, and every interface instance written the same way. The +/// instance name's type is the module it instantiates. +fn instance_site(i: &Instantiation, span: TextRange) -> Option> { + let first = i.instances.first().map_or(span.end, |inst| inst.name_span.start); + site(&i.module, TextRange::new(span.start, first)) +} + +fn module_site(m: &Module, offset: u32) -> Option> { + param_port_site(m.param_ports.as_deref().unwrap_or(&[]), offset) + .or_else(|| match &m.ports { + PortList::Ansi(ports) => ansi_port_site(ports, offset), + _ => None, + }) + .or_else(|| site_at(&m.items, offset)) +} + +fn ansi_port_site(ports: &[AnsiPort], offset: u32) -> Option> { + let port = ports.iter().find(|p| p.span.contains(offset))?; + site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start)) +} + +fn param_port_site(ports: &[ParamPort], offset: u32) -> Option> { + let port = ports.iter().find(|p| p.span.contains(offset))?; + site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start)) +} + +fn tf_arg_site(args: &[TfArg], offset: u32) -> Option> { + let arg = args.iter().find(|a| a.span.contains(offset))?; + site(&arg.ty.name, TextRange::new(arg.span.start, arg.name_span.start)) +} + +fn gen_if_site(gen_if: &GenIf, offset: u32) -> Option> { + if let Some(site) = gen_block_site(&gen_if.then, offset) { + return Some(site); + } + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + GenElse::If(_, nested) => { + if let Some(site) = gen_block_site(&nested.then, offset) { + return Some(site); + } + els = nested.els.as_deref(); + } + GenElse::Block(block) => return gen_block_site(block, offset), + } + } + None +} + +fn gen_block_site(block: &GenBlock, offset: u32) -> Option> { + if block.span.contains(offset) { + site_at(&block.items, offset) + } else { + None + } +} + +fn stmts_site(list: &[Stmt], offset: u32) -> Option> { + list.iter().find_map(|stmt| stmt_site(stmt, offset)) +} + +/// A declaration written among statements: `my_cls h;` in a task body. +/// +/// The recursion is bounded by the parser's own nesting limit +/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it +/// built. +fn stmt_site(stmt: &Stmt, offset: u32) -> Option> { + if !stmt.span.contains(offset) { + return None; + } + match &stmt.kind { + StmtKind::VarDecl(d) => declarator_site(&d.ty, stmt.span, &d.declarators), + StmtKind::ParamDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators), + StmtKind::PortDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators), + StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => { + stmts_site(stmts, offset) + } + StmtKind::If { then, els, .. } => stmt_site(then, offset) + .or_else(|| els.as_deref().and_then(|els| stmt_site(els, offset))), + StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => { + items.iter().find_map(|item| stmt_site(&item.stmt, offset)) + } + StmtKind::Labeled { stmt: inner, .. } => stmt_site(inner, offset), + StmtKind::For { body, .. } + | StmtKind::While { body, .. } + | StmtKind::DoWhile { body, .. } + | StmtKind::Repeat { body, .. } + | StmtKind::Forever { body } + | StmtKind::Foreach { body, .. } => stmt_site(body, offset), + StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => { + stmt_site(inner, offset) + } + StmtKind::Assert { then, els, .. } => then + .as_deref() + .and_then(|then| stmt_site(then, offset)) + .or_else(|| els.as_deref().and_then(|els| stmt_site(els, offset))), + _ => None, + } +} + +/// A site for a type written by name; `None` for an implicit type, which has +/// no name at all (`input [7:0] x`). +fn site(name: &str, window: TextRange) -> Option> { + if name.is_empty() { + None + } else { + Some(Site { name, window }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + use std::fs; + use std::path::PathBuf; + use std::str::FromStr; + + fn document(text: &str) -> (Workspace, Uri) { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) + } + + /// The byte offset of the first occurrence of `needle` in `text`. + fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 + } + + /// Every answer as `(line, character)` in the document it was asked of. + fn jumps(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<(u32, u32)> { + type_definition(ws, uri, offset) + .iter() + .map(|l| (l.range.start.line, l.range.start.character)) + .collect() + } + + fn temp_dir(tag: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("lucisv_server_type_{tag}_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + dir + } + + // ------------------------------------------------------------------ + // in-file types + // ------------------------------------------------------------------ + + #[test] + fn a_variable_jumps_to_the_typedef_of_its_type() { + let text = "\ +module m; + typedef logic [7:0] byte_t; + byte_t b; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "byte_t b") + 7), [(1, 22)], "the typedef's own name"); + } + + #[test] + fn a_use_of_the_variable_answers_the_same_type() { + // The cursor need not be on the declaration: a use resolves to it + // first, exactly as go-to-definition does. + let text = "\ +module m; + typedef logic [7:0] byte_t; + byte_t b; + assign x = b; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "= b") + 2), [(1, 22)]); + } + + #[test] + fn an_enum_typedef_and_a_struct_typedef_are_both_reachable() { + let text = "\ +module m; + typedef enum logic [1:0] { IDLE, RUN } state_t; + typedef struct packed { logic a; logic b; } pair_t; + state_t s; + pair_t p; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "state_t s") + 8), [(1, 41)], "the enum typedef"); + assert_eq!(jumps(&ws, &uri, at(text, "pair_t p") + 7), [(2, 46)], "the struct typedef"); + } + + #[test] + fn a_class_handle_jumps_to_the_class() { + let text = "\ +class my_cls; +endclass + +module m; + my_cls h; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(0, 6)]); + } + + #[test] + fn a_handle_declared_inside_a_method_body_is_reached_too() { + // The declaration is a statement, not a module item, which is the + // whole reason the walk descends into statements. + let text = "\ +class my_cls; +endclass + +class holder; + task run(); + my_cls h; + endtask +endclass +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(0, 6)]); + } + + #[test] + fn an_instance_name_jumps_to_the_module_it_instantiates() { + let text = "\ +module sub; +endmodule + +module top; + sub u_sub (.clk(1'b0)); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "u_sub")), [(0, 7)], "the `sub` declaration"); + } + + #[test] + fn an_interface_instance_and_a_virtual_handle_both_reach_the_interface() { + let text = "\ +interface bus_if; +endinterface + +module m; + bus_if bus (); + virtual bus_if vif; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "bus (")), [(0, 10)], "the instance"); + assert_eq!(jumps(&ws, &uri, at(text, "vif")), [(0, 10)], "the virtual handle"); + } + + #[test] + fn an_interface_port_reaches_its_interface() { + // The interface port is written second on purpose: a header whose + // *first* port carries no direction does not parse today, which is + // the parser's own limitation and is recorded in the feature + // README's Handshakes. + let text = "\ +interface bus_if; +endinterface + +module m (input logic clk, bus_if bus); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "bus)")), [(0, 10)]); + assert!(type_definition(&ws, &uri, at(text, "clk")).is_empty(), "`logic` is a built-in"); + } + + #[test] + fn a_parameter_and_a_task_argument_are_typed_declarations_like_any_other() { + let text = "\ +package p; + typedef logic [3:0] nib_t; +endpackage + +module m #(parameter p::nib_t N = 0) (); + task run(p::nib_t a); + endtask +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "N = 0")), [(1, 22)], "the header parameter"); + assert_eq!(jumps(&ws, &uri, at(text, "a)")), [(1, 22)], "the task argument"); + } + + // ------------------------------------------------------------------ + // the cursor on the type name itself, and the one-hop rule + // ------------------------------------------------------------------ + + #[test] + fn the_cursor_on_a_type_name_answers_for_that_name() { + // `state_t` in `state_t s;` is the type, so its own declaration is + // the answer — the same location `definition` would give. + let text = "\ +module m; + typedef enum logic { A, B } state_t; + state_t s; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "state_t s")), [(1, 30)]); + } + + #[test] + fn an_alias_chain_is_walked_one_hop_at_a_time() { + // `x` reaches `alias_t`, not `state_t`. The user presses the key + // again for the next hop; nothing here follows the chain. + let text = "\ +module m; + typedef enum logic { A, B } state_t; + typedef state_t alias_t; + alias_t x; +endmodule +"; + let (ws, uri) = document(text); + let alias_line = (2, 18); + let state_line = (1, 30); + assert_eq!(jumps(&ws, &uri, at(text, "alias_t x") + 8), [alias_line], "one hop"); + assert_eq!(jumps(&ws, &uri, at(text, "alias_t x")), [alias_line], "and still one hop"); + assert_eq!( + jumps(&ws, &uri, at(text, "alias_t;")), + [state_line], + "from the alias's own declaration, the next hop" + ); + } + + // ------------------------------------------------------------------ + // nothing to answer + // ------------------------------------------------------------------ + + #[test] + fn a_built_in_type_has_no_declaration_to_jump_to() { + let text = "module m;\n logic a;\n wire [7:0] b;\n int c;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "logic a") + 6).is_empty(), "logic"); + assert!(type_definition(&ws, &uri, at(text, "logic a")).is_empty(), "the keyword itself"); + assert!(type_definition(&ws, &uri, at(text, "] b") + 2).is_empty(), "wire"); + assert!(type_definition(&ws, &uri, at(text, "int c") + 4).is_empty(), "int"); + } + + #[test] + fn a_position_on_no_name_at_all_answers_nothing() { + let text = "module m;\n typedef logic t;\n t a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, ";\n")).is_empty(), "a semicolon"); + assert!(type_definition(&ws, &uri, at(text, "endmodule")).is_empty(), "a keyword"); + } + + #[test] + fn a_buffer_the_server_does_not_hold_answers_nothing() { + let ws = Workspace::default(); + let uri = Uri::from_str("file:///rtl/never-opened.sv").expect("uri"); + assert!(type_definition(&ws, &uri, 0).is_empty()); + } + + #[test] + fn a_type_nothing_declares_answers_nothing() { + let text = "module m;\n missing_t a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "missing_t a") + 10).is_empty()); + } + + // ------------------------------------------------------------------ + // across files + // ------------------------------------------------------------------ + + /// A workspace of `(name, text)` files with `which` opened as a buffer. + fn workspace(tag: &str, files: &[(&str, &str)], which: &str) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in files { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let path = dir.join(which); + let uri = path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("read"); + ws.set_document(uri.clone(), text); + (dir, ws, uri) + } + + const PKG: &str = "\ +package tdp; + typedef enum logic [1:0] { IDLE, RUN } state_t; +endpackage +"; + + #[test] + fn a_package_qualified_type_resolves_through_the_workspace() { + let top = "module top;\n tdp::state_t s;\nendmodule\n"; + let (dir, ws, uri) = workspace("pkgq", &[("pkg.sv", PKG), ("top.sv", top)], "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "state_t s") + 8); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("pkg.sv")).expect("uri")); + assert_eq!((found[0].range.start.line, found[0].range.start.character), (1, 41)); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_imported_type_resolves_through_the_workspace_too() { + // The unqualified spelling: the type name is an external candidate, + // finished by the same overlay `definition` uses. + let top = "module top;\n import tdp::*;\n state_t s;\nendmodule\n"; + let (dir, ws, uri) = workspace("import", &[("pkg.sv", PKG), ("top.sv", top)], "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "state_t s") + 8); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("pkg.sv")).expect("uri")); + assert_eq!(found[0].range.start.line, 1); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_interface_declared_in_another_file_is_reached_from_a_port() { + let iface = "interface bus_if;\nendinterface\n"; + let top = "module top (input logic clk, bus_if bus);\n bus_if other ();\nendmodule\n"; + let (dir, ws, uri) = workspace("iface", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + for offset in [at(top, "bus)"), at(top, "other")] { + let found = type_definition(&ws, &uri, offset); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("bus_if.sv")).expect("uri")); + assert_eq!(found[0].range.start.character, 10, "the interface's name"); + } + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_class_declared_in_another_file_is_reached_from_a_handle() { + let cls = "class my_cls;\nendclass\n"; + let top = "module top;\n my_cls h;\nendmodule\n"; + let (dir, ws, uri) = workspace("xcls", &[("my_cls.sv", cls), ("top.sv", top)], "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "my_cls h") + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("my_cls.sv")).expect("uri")); + assert_eq!(found[0].range.start.character, 6); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_package_of_the_same_name_is_not_a_type() { + // The index holds file-scope declarations of every kind; only the + // ones that can be a type are an answer. + let pkg = "package thing;\nendpackage\n"; + let top = "module top;\n thing t;\nendmodule\n"; + let (dir, ws, uri) = workspace("pkgtype", &[("thing.sv", pkg), ("top.sv", top)], "top.sv"); + + assert!(type_definition(&ws, &uri, at(top, "thing t") + 6).is_empty()); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_qualified_name_the_overlay_refused_is_not_retried_against_the_index() { + // The index fallback exists for the one miss `vlog_semantic` reports + // as `NotFound`. A `pkg::missing_t` is an *external candidate* the + // overlay answered with nothing, and a module of that name elsewhere + // is not what it meant. + let pkg = "package tdp2;\nendpackage\n"; + let decoy = "module missing_t;\nendmodule\n"; + let top = "module top;\n tdp2::missing_t s;\nendmodule\n"; + let files = [("pkg.sv", pkg), ("decoy.sv", decoy), ("top.sv", top)]; + let (dir, ws, uri) = workspace("refused", &files, "top.sv"); + + assert!(type_definition(&ws, &uri, at(top, "missing_t s") + 10).is_empty()); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_module_declared_twice_returns_both_declarations() { + // The ambiguity policy is `definition`'s, because the answer *is* + // `definition`'s: every candidate, never a guess. + let dup = "module dup;\nendmodule\n"; + let top = "module top;\n dup u (.*);\nendmodule\n"; + let files = [("a.sv", dup), ("b.sv", dup), ("top.sv", top)]; + let (dir, ws, uri) = workspace("ambig", &files, "top.sv"); + + assert_eq!(type_definition(&ws, &uri, at(top, "u (")).len(), 2); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_declaration_inside_a_generate_block_is_reached() { + let text = "\ +module m; + typedef logic t; + generate + if (P) begin : g + t a; + end + endgenerate +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "t a") + 2), [(1, 16)]); + } + + #[test] + fn positions_are_utf16_like_every_other_answer() { + let text = "\ +module m; + typedef logic t; // é 🎉 + t a; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "t a")), [(1, 16)]); + } + + // ------------------------------------------------------------------ + // QA (2026-08-26): the `indexed_type` fence, attacked directly. + // ------------------------------------------------------------------ + + #[test] + fn a_class_scoped_type_reference_in_an_extending_class_is_found_cross_file() { + // QA finding (2026-08-26), corpus-spot-check-derived, fixed the same + // day by widening the fence: `resolve.rs`'s `miss` + // (vlog_semantic/src/resolve.rs:201-213) resolves *any* lexical miss + // inside a class body that carries an `extends` clause as + // `Resolution::InheritedCandidate`, never `Resolution::NotFound` — + // unconditionally, whether or not the missing name has anything to do + // with inheritance. `indexed_type` used to fire only on `NotFound`, so + // a cross-file interface/class type used as a member of *any* + // extending class fell through both layers and answered nothing. This + // is not a crafted edge case: it is the real shape of + // corpus/ibex/dv/uvm/core_ibex/env/core_ibex_env_cfg.sv:5,7 + // (`class core_ibex_env_cfg extends uvm_object;` / + // `virtual clk_rst_if ibex_clk_vif;`), i.e. ordinary UVM, where almost + // every class extends something. The resolution is *still* + // `InheritedCandidate` — nothing in `vlog_semantic` changed — and the + // fallback now accepts it. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +class base; +endclass +class top extends base; + virtual bus_if h; +endclass +"; + let (dir, ws, uri) = + workspace("extends_gap", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + let offset = at(top, "bus_if h") + 2; + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "still not NotFound: the fence widened, the resolution did not" + ); + let found = type_definition(&ws, &uri, offset); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("bus_if.sv")).expect("uri")); + assert_eq!(found[0].range.start.character, 10, "the interface's name"); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_uvm_shaped_member_type_resolves_cross_file_from_an_extending_class() { + // The corpus shape exactly, as a portable fixture: the base class + // (`uvm_object`) is nowhere in this workspace, so the inheritance path + // is not merely unchased but unchaseable, and every member type of the + // class is an `InheritedCandidate` no layer below can place. The two + // interfaces are declared in other files at file scope, which is where + // interfaces live, and both are the answer. + let clk = "interface clk_rst_if;\nendinterface\n"; + let probe = "interface dut_probe_if;\nendinterface\n"; + let cfg = "\ +class env_cfg extends uvm_object; + virtual clk_rst_if clk_vif; + virtual dut_probe_if dut_vif; +endclass +"; + let files = [("clk_rst_if.sv", clk), ("dut_probe_if.sv", probe), ("cfg.sv", cfg)]; + let (dir, ws, uri) = workspace("uvm_shape", &files, "cfg.sv"); + + for (needle, file) in + [("clk_rst_if ", "clk_rst_if.sv"), ("dut_probe_if ", "dut_probe_if.sv")] + { + let found = type_definition(&ws, &uri, at(cfg, needle) + 2); + assert_eq!(found.len(), 1, "{needle}: {found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join(file)).expect("uri")); + assert_eq!(found[0].range.start.character, 10, "the interface's name"); + } + + // The declarator half of the same declaration takes the same hop. + let found = type_definition(&ws, &uri, at(cfg, "clk_vif")); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("clk_rst_if.sv")).expect("uri")); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it() { + // The precedence question the widening raises, answered by reading + // `vlog_semantic` and pinned here. `resolve.rs::lexical` + // (vlog_semantic/src/resolve.rs:39-70) walks `scope.parent` — lexical + // nesting — and never a base class's scope; `miss` (:201-213) records + // the base's *name* and stops, and `resolve_external` + // (vlog_semantic/src/workspace.rs:382-391) only finishes + // `ExternalCandidate`s. So a typedef nested in a base class is + // unreachable to every layer, even when that base is in the same file: + // there is no better answer being displaced here, only an empty one. + // + // And precedence needs no code of its own, now or later: the fallback + // is consulted only after `nav::definition` came back empty, so the day + // `vlog_semantic` does chase an in-file base, this reference becomes + // `Resolution::Resolved`, `nav::definition` answers the nested typedef, + // and `indexed_type` is never reached — the same way the local-genvar + // shadowing test below already works. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +class base; + typedef int bus_if; +endclass +class top extends base; + bus_if h; +endclass +"; + let (dir, ws, uri) = + workspace("nested_base", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + let offset = at(top, "bus_if h"); + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "the base's nested typedef is not found lexically, in-file or not" + ); + let found = type_definition(&ws, &uri, offset + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!( + found[0].uri, + path_to_uri(&dir.join("bus_if.sv")).expect("uri"), + "the workspace interface: the only location any layer can produce" + ); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_non_type_inherited_reference_is_still_never_a_type_site() { + // The structural confinement to type windows has to survive the + // widening: inside an extending class *every* miss is an + // `InheritedCandidate`, including ordinary expression identifiers that + // are genuinely inherited members and have nothing to do with types. + // `indexed_type` is only ever reached with a span `type_name` + // produced, and `site_at` only descends declaration containers, so no + // `Site` is built for an expression statement and the fence is never + // consulted at all. + let dup = "module dup;\nendmodule\n"; + let top = "\ +class base; +endclass +class top extends base; + int x; + function void f(); + x = dup; + endfunction +endclass +"; + let (dir, ws, uri) = + workspace("inherited_expr", &[("dup.sv", dup), ("top.sv", top)], "top.sv"); + + let offset = at(top, "= dup") + 2; + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "an inherited member, as far as `resolve.rs` knows" + ); + assert!(type_definition(&ws, &uri, offset).is_empty(), "not a declaration's type window"); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn the_other_two_fence_conditions_still_hold_under_an_inherited_candidate() { + // Widening the *first* condition must not loosen the other two, so + // each is re-attacked from inside an extending class, where every one + // of these references is an `InheritedCandidate`. + let pkg = "\ +package thing; + typedef logic [3:0] inner_t; +endpackage +"; + let decoy = "module missing_t;\nendmodule\n"; + let top = "\ +class base; +endclass +class top extends base; + thing a; + inner_t b; + thing::missing_t c; +endclass +"; + let files = [("thing.sv", pkg), ("decoy.sv", decoy), ("top.sv", top)]; + let (dir, ws, uri) = workspace("fence_inherited", &files, "top.sv"); + + // Kind filter: a `package` of that name is not a type. + assert_eq!( + doc_reference_kind(&ws, &uri, at(top, "thing a")), + Some("InheritedCandidate".to_string()) + ); + assert!(type_definition(&ws, &uri, at(top, "thing a") + 9).is_empty(), "a package"); + + // File scope only: `inner_t` is a *member* of `thing`, not a unit, so + // the index's unit table does not hold it and no import brought it in. + assert_eq!( + doc_reference_kind(&ws, &uri, at(top, "inner_t b")), + Some("InheritedCandidate".to_string()) + ); + assert!(type_definition(&ws, &uri, at(top, "inner_t b") + 9).is_empty(), "not file-scope"); + + // A qualified name the overlay already refused stays refused: it is an + // `ExternalCandidate`, not a lexical miss, so the fence rejects it and + // the decoy module of that name is not offered. + assert_eq!( + doc_reference_kind(&ws, &uri, at(top, "missing_t c")), + Some("Other".to_string()) + ); + assert!(type_definition(&ws, &uri, at(top, "missing_t c") + 10).is_empty(), "refused"); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_local_declaration_of_the_same_name_wins_over_the_workspace_type() { + // `bus_if` is both a workspace interface and, here, a local genvar in + // scope where `bus_if` is written as a type. `vlog_semantic`'s + // `lexical` resolution (`resolve.rs::lexical`) does not filter by + // kind, so the reference resolves *locally* to the genvar and is + // never `Resolution::NotFound` — which means `indexed_type`'s first + // fence condition is never reached, and the wrong workspace jump + // cannot happen. The answer here is the genvar's own declaration + // (`nav::definition`'s answer for the same shadowing, unchanged by + // this feature), not the interface. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +module top; + genvar bus_if; + bus_if x; +endmodule +"; + let (dir, ws, uri) = + workspace("shadow", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + // The type reference itself — `bus_if`, not the declarator `x` — is + // what the fence inspects. + let type_ref_offset = at(top, "bus_if x"); + assert_eq!( + doc_reference_kind(&ws, &uri, type_ref_offset), + Some("Resolved".to_string()), + "the genvar wins the lexical lookup, so this is never NotFound" + ); + let found = type_definition(&ws, &uri, at(top, "bus_if x") + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, uri, "the genvar is declared in this same file"); + assert_eq!(found[0].range.start.line, 1, "the genvar's own declaration, not the interface"); + + let _ = fs::remove_dir_all(&dir); + } + + /// Whether the reference at `offset` was resolved locally, and by what + /// resolution kind — used to pin down *why* the fence did or didn't fire, + /// rather than only observing the final jump. + fn doc_reference_kind(ws: &Workspace, uri: &Uri, offset: u32) -> Option { + let doc = ws.document(uri)?; + let reference = doc.semantics.reference_at(offset)?; + Some(match reference.resolution { + Resolution::Resolved(_) => "Resolved".to_string(), + Resolution::NotFound => "NotFound".to_string(), + Resolution::InheritedCandidate { .. } => "InheritedCandidate".to_string(), + _ => "Other".to_string(), + }) + } + + #[test] + fn a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site() { + // `indexed_type` is only ever reached with a span `type_name` produced, + // and `type_name`'s first and third branches both go through + // `site_at`, which is structurally confined to declaration + // containers (`item_site`/`stmt_site`) — an ordinary expression + // statement is not one of them. So a bare identifier that happens to + // share a workspace module's name, used in a value position, must + // never produce a jump — not because a fence catches it, but because + // no `Site` is ever built for it. + let dup = "module dup;\nendmodule\n"; + let top = "module top;\n wire x;\n assign x = dup;\nendmodule\n"; + let (dir, ws, uri) = workspace("exprname", &[("dup.sv", dup), ("top.sv", top)], "top.sv"); + + let offset = at(top, "= dup") + 2; + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("NotFound".to_string()), + "an expression identifier nothing declares, and no import to escalate it" + ); + assert!(type_definition(&ws, &uri, offset).is_empty(), "not a declaration's type window"); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn indexed_type_returns_every_workspace_declaration_when_the_name_is_ambiguous() { + // The same ambiguity convention as `nav::definition`, but pinned + // through the `indexed_type` fallback path specifically (an + // unqualified `NotFound` reference), which none of the dev's + // ambiguity tests exercise — theirs goes through `Target::Module`'s + // `ExternalCandidate`, a different resolution path that never touches + // `indexed_type` at all. + let iface = "interface bus_if;\nendinterface\n"; + let top = "module top;\n bus_if bus;\nendmodule\n"; + let files = [("a.sv", iface), ("b.sv", iface), ("top.sv", top)]; + let (dir, ws, uri) = workspace("indexed_ambig", &files, "top.sv"); + + let type_ref_offset = at(top, "bus_if bus"); + assert_eq!(doc_reference_kind(&ws, &uri, type_ref_offset), Some("NotFound".to_string())); + let found = type_definition(&ws, &uri, at(top, "bus_if bus") + 7); + assert_eq!(found.len(), 2, "both interfaces, not a guess: {found:#?}"); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_qualified_member_miss_never_falls_back_to_a_bare_name_sweep() { + // Lead fix, 2026-08-26 (QA follow-up finding): `unit_member` can miss + // with the same two spellings the fence accepts — a local package + // that lacks the member — and a bare-name workspace sweep would then + // discard the `pkg::` qualifier and jump to an unrelated declaration + // that merely shares the member's name. The source pointed into + // `pkg`; an answer from anywhere else is a wrong jump, and no answer + // is the honest one. + let other = "typedef logic missing_t;\n"; + let top = "package p;\nendpackage\nmodule top;\n p::missing_t s;\nendmodule\n"; + let files = [("other.sv", other), ("top.sv", top)]; + let (dir, ws, uri) = workspace("qualified_no_sweep", &files, "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "p::missing_t") + 5); + assert!(found.is_empty(), "the qualifier must not be discarded: {found:#?}"); + // The same name unqualified still reaches the workspace type, so the + // guard is about the qualifier, not the name. + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_self_referential_typedef_is_total_and_does_not_loop() { + // `typedef t t;` — the alias and its own type share a name. Nothing + // in this module chases a chain (that is the one-hop rule's whole + // point), so there is no loop to guard against structurally; this + // pins that down operationally: every position on the line answers + // exactly once, promptly, whatever the answer is. + let text = "module m;\n typedef t t;\nendmodule\n"; + let (ws, uri) = document(text); + // No panic, no hang, on the alias name, on the type-of name, or on + // any position in between. + for offset in [at(text, "typedef"), at(text, "t t"), at(text, "t t") + 2, at(text, ";\n")] { + let _ = type_definition(&ws, &uri, offset); + } + } + + #[test] + fn type_definition_on_a_type_name_agrees_exactly_with_definition() { + // The design claim in the feature README ("cursor on a type name + // answers for that name") is that this is *literally* the same + // request `textDocument/definition` would answer at that offset, not + // a coincidentally-equal location built a different way. + let text = "\ +module m; + typedef enum logic { A, B } state_t; + state_t s; +endmodule +"; + let (ws, uri) = document(text); + let offset = at(text, "state_t s"); + assert_eq!(type_definition(&ws, &uri, offset), nav::definition(&ws, &uri, offset)); + } + + #[test] + fn an_inline_anonymous_struct_has_no_type_name_to_jump_to() { + // `struct packed { ... } s;` — the type is written inline, with no + // name of its own, so `DataType::name` is empty and `site()` refuses + // it. Null, not a bogus jump at whatever text happens to sit in the + // window. + let text = "module m;\n struct packed { logic a; } s;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "} s") + 2).is_empty(), "the declarator name"); + assert!( + type_definition(&ws, &uri, at(text, "logic a")).is_empty(), + "inside the inline body" + ); + } + + #[test] + fn a_later_declarator_in_a_multi_declarator_line_still_finds_the_type() { + // `state_t a, b, c;` — the window is computed from the *first* + // declarator regardless of which one the cursor is on, because the + // type is written once for the whole list. + let text = "\ +module m; + typedef logic t; + t a, b, c; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!( + jumps(&ws, &uri, at(text, "c;")), + [(1, 16)], + "the cursor on the third declarator" + ); + } + + #[test] + fn var_const_and_signed_qualifiers_do_not_shift_the_type_window() { + // Qualifiers (`DataDecl::qualifiers`) sit textually before the type + // inside the same window this feature scans; they must not be + // mistaken for the type name, and must not shift where it is found. + let text = "\ +module m; + class my_cls; + endclass + const var my_cls h; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(1, 8)]); + } + + #[test] + fn packed_and_unpacked_array_dimensions_do_not_confuse_the_type_match() { + let text = "\ +module m; + typedef logic state_t; + state_t [3:0] x [0:7]; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "x [0:7]")), [(1, 16)]); + } + + #[test] + fn a_function_arguments_type_is_reached_like_a_task_arguments() { + let text = "\ +package p; + typedef logic [3:0] nib_t; +endpackage + +module m; + function automatic p::nib_t f(p::nib_t a); + return a; + endfunction +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "a);")), [(1, 22)], "the function's own argument"); + } + + #[test] + fn a_position_past_the_end_of_the_file_answers_nothing_not_a_panic() { + let text = "module m;\n typedef logic t;\n t a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, text.len() as u32 + 5_000).is_empty()); + } + + #[test] + fn a_position_inside_a_comment_answers_nothing() { + let text = "module m;\n // t is not a type here, just a comment\n int a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "not a type")).is_empty()); + } + + // ------------------------------------------------------------------ + // QA corpus spot-check (2026-08-26). + // + // One `Workspace` is opened once and reused for every probe and every + // file in the full-corpus panic sweep below — `open_roots` indexes the + // whole tree (a one-time cost), and `set_document` only overlays a + // buffer against the index already built, so this is cheap to repeat. + // The first version of this test opened a fresh `Workspace` (and so + // re-indexed all of corpus/ibex) per file in the sweep, which made a + // ~300-file loop re-scan several hundred files each time; that was a + // test-harness bug, not a product one, and is fixed by sharing `ws`. + // ------------------------------------------------------------------ + + #[test] + fn corpus_spot_check_real_uvm_files_no_panic_and_known_jumps() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/ibex"); + if !root.exists() { + eprintln!("corpus not present, skipping"); + return; + } + let mut ws = Workspace::default(); + ws.open_roots(vec![root.clone()]); + + let open = |ws: &mut Workspace, rel: &str| -> (Uri, String) { + let file = root.join(rel); + let text = fs::read_to_string(&file).unwrap_or_else(|e| panic!("read {rel}: {e}")); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + (uri, text) + }; + + // A genuine, real-world positive control: `core_ibex_tb_top` + // instantiates `clk_rst_if` (declared in a vendored file elsewhere + // in the tree) at module scope, not inside any class — the plain + // cross-file-interface-instance case the feature's design claims to + // solve, exercised on real corpus text rather than a fixture. + let (tb_uri, tb_text) = open(&mut ws, "dv/uvm/core_ibex/tb/core_ibex_tb_top.sv"); + for offset in 0..=tb_text.len() as u32 { + let _ = type_definition(&ws, &tb_uri, offset); // no panic, whole file + } + let found = type_definition(&ws, &tb_uri, at(&tb_text, "clk_rst_if ibex_clk_if") + 2); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].uri.as_str().ends_with("clk_rst_if.sv"), "{found:#?}"); + + // The QA finding of 2026-08-26, now the positive control for its own + // fix, on the real file it was found in rather than only the portable + // fixture above: `core_ibex_env_cfg extends uvm_object`, so every + // otherwise-cross-file type reference inside it — `clk_rst_if`, + // `core_ibex_dut_probe_if`, both real interfaces this same workspace + // indexes — resolves to `InheritedCandidate`, which the widened fence + // now accepts. `scrambling_key_agent_cfg` is different: that class is + // not vendored into this corpus checkout at all, so empty stays the + // correct answer, and it is what keeps the widening from being + // mistaken for "answer something, anything". + let (env_uri, env_text) = open(&mut ws, "dv/uvm/core_ibex/env/core_ibex_env_cfg.sv"); + for offset in 0..=env_text.len() as u32 { + let _ = type_definition(&ws, &env_uri, offset); + } + let found = type_definition(&ws, &env_uri, at(&env_text, "clk_rst_if") + 2); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].uri.as_str().ends_with("clk_rst_if.sv"), "{found:#?}"); + let found = type_definition(&ws, &env_uri, at(&env_text, "core_ibex_dut_probe_if ") + 2); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].uri.as_str().ends_with("core_ibex_dut_probe_if.sv"), "{found:#?}"); + assert!( + type_definition(&ws, &env_uri, at(&env_text, "scrambling_key_agent_cfg ") + 2) + .is_empty(), + "genuinely not in this corpus checkout, unrelated to the gap" + ); + + let (sb_uri, sb_text) = open(&mut ws, "dv/uvm/core_ibex/env/core_ibex_scoreboard.sv"); + for offset in 0..=sb_text.len() as u32 { + let _ = type_definition(&ws, &sb_uri, offset); + } + + // Every small file under corpus/ibex, sharing the one indexed + // workspace: no panic anywhere a real cursor could land. + let mut count = 0; + visit(&root, &mut |path| { + let ext_ok = + matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("svh")); + let Ok(t) = (if ext_ok { fs::read_to_string(path) } else { return }) else { return }; + if t.len() > 4000 { + return; + } + let Some(u) = path_to_uri(path) else { return }; + ws.set_document(u.clone(), t.clone()); + for offset in (0..=t.len() as u32).step_by(3) { + let _ = type_definition(&ws, &u, offset); + } + count += 1; + }); + eprintln!("checked {count} small corpus files, no panic"); + assert!(count > 20, "{count}"); + } + + fn visit(dir: &std::path::Path, f: &mut impl FnMut(&std::path::Path)) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + visit(&path, f); + } else { + f(&path); + } + } + } + + // ------------------------------------------------------------------ + // QA fix-round re-attack (2026-08-26) + // ------------------------------------------------------------------ + + #[test] + fn a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type() { + // The dev's precedence test puts the shadowing typedef in the *base* + // class, which `lexical` can never see anyway (it walks `scope.parent`, + // never a base's scope). This puts it directly in the *extending* + // class's own body — the one place `lexical` unambiguously looks first, + // before it ever reaches `miss`/`InheritedCandidate` at all. If lexical + // scoping is doing what it's supposed to, this reference is `Resolved` + // against the local typedef and `indexed_type` is never consulted, so + // the widened fence cannot leak a wrong cross-file jump here. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +class base; +endclass +class top extends base; + typedef int bus_if; + bus_if h; +endclass +"; + let (dir, ws, uri) = workspace( + "local_typedef_in_extender", + &[("bus_if.sv", iface), ("top.sv", top)], + "top.sv", + ); + + let offset = at(top, "bus_if h"); + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("Resolved".to_string()), + "lexical finds the class's own typedef before miss ever runs" + ); + let found = type_definition(&ws, &uri, offset + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, uri, "the in-file typedef, not the workspace interface"); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did() { + // The fence's kind filter (`Module | Class | Typedef`) was never + // conditioned on which of the two resolutions triggered it, so a + // member-type reference inside an extending class that happens to + // share a name with a workspace *module* should jump there exactly as + // it already would have for a plain top-level `NotFound` reference + // (`a_class_declared_in_another_file_is_reached_from_a_handle`, mutatis + // mutandis for `Module`). Nothing about "module, not class/interface" + // is special-cased in `indexed_type`, so this is a parity check, not a + // new behavior. + let module_file = "module thing;\nendmodule\n"; + let top = "\ +class base; +endclass +class top extends base; + thing h; +endclass +"; + let (dir, ws, uri) = workspace( + "inherited_to_module", + &[("thing.sv", module_file), ("top.sv", top)], + "top.sv", + ); + + let offset = at(top, "thing h"); + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "member type inside an extending class" + ); + let found = type_definition(&ws, &uri, offset + 3); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("thing.sv")).expect("uri")); + + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 663196c..cf61079 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -3166,3 +3166,73 @@ fn a_flood_of_requests_and_cancels_is_answered_exactly_once_each() { let _ = std::fs::remove_dir_all(&dir); } + +const TYPEDEF_PKG: &str = "\ +package e2e_tdp; + typedef enum logic [1:0] { IDLE, RUN } state_t; +endpackage +"; + +const TYPEDEF_TOP: &str = "\ +module e2e_tdtop; + e2e_tdp::state_t s; +endmodule +"; + +#[test] +fn a_type_definition_crosses_a_file_over_the_wire() { + // What only an e2e test can check: that the capability is advertised in + // the real handshake and that the request is dispatched at all. The + // answer itself — a package's typedef, reached from a variable in + // another file — is the cross-file half of the feature. + let dir = temp_dir("typedef"); + let pkg = dir.join("e2e_tdp.sv"); + std::fs::write(&pkg, TYPEDEF_PKG).expect("write"); + let top = dir.join("e2e_tdtop.sv"); + std::fs::write(&top, TYPEDEF_TOP).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", top.display()); + let pkg_uri = format!("file://{}", pkg.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(TYPEDEF_TOP).expect("json") + )), + // The cursor on `s`, whose type is declared in the package. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/typeDefinition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":19}}}}}}"# + )), + // And on `logic`, a built-in, which has no declaration to jump to. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/typeDefinition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":9}}}}}}"# + )), + 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["typeDefinitionProvider"], true, "{capabilities:#?}"); + + let locations = response(2)["result"].as_array().expect("a location list"); + assert_eq!(locations.len(), 1, "{locations:#?}"); + assert_eq!(locations[0]["uri"], pkg_uri.as_str(), "the package's own file"); + assert_eq!(locations[0]["range"]["start"]["line"], 1); + assert_eq!(locations[0]["range"]["start"]["character"], 41, "the typedef's name"); + + let nothing = response(3)["result"].as_array().expect("an empty list, not null"); + assert!(nothing.is_empty(), "{nothing:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 7c5f51c..cea98a4 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -28,6 +28,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README | | `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` | | `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` | +| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` | | `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README | | `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` | | `textDocument/documentHighlight` | `pairs::analyze`, else `Semantics::references_of` | A scope keyword highlights its own closer; anything else highlights the symbol's occurrences in this file. Kind is always `Text`; neither answer means `null`, so the editor keeps its word highlighting. Same feature README | @@ -383,7 +384,12 @@ done here: a backtick, distinguished by the existing public `Token::is_macro()` — which is enough, so this is a note, not a request. 4. **`vlog_semantic`: nothing.** The queries needed for all six navigation - capabilities existed exactly as documented. + capabilities existed exactly as documented. *(One request has since been + filed by type-definition: an unqualified name nothing in the file binds is + reported `NotFound` rather than as an external candidate, so the workspace + overlay never sees it — which is how an `interface` type is written. Stated + in full, with the fenced workaround it stands in for, in + `docs/features/type-definition/README.md`.)* ## The `semanticTokens` mapping @@ -508,6 +514,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: `docs/features/semantic-tokens-delta/README.md`. - [x] `textDocument/hover`. - [x] `textDocument/definition`. +- [x] `textDocument/typeDefinition` — delivered by **type-definition** + (2026-08-26, TODO.md §9c): the type half of go-to-definition, computed + by redirecting the position to the type name the declaration writes and + answering with `nav::definition` from there. No engine change. + `docs/features/type-definition/README.md`. - [x] `textDocument/references`. - [x] `textDocument/documentSymbol` + `workspace/symbol`. - [x] Unit tests for the position conversion, including surrogate pairs. diff --git a/docs/features/type-definition/README.md b/docs/features/type-definition/README.md new file mode 100644 index 0000000..7d6e60b --- /dev/null +++ b/docs/features/type-definition/README.md @@ -0,0 +1,691 @@ +# type-definition + +## Goal + +`textDocument/typeDefinition` (TODO.md §9c): from a name to the declaration of +that name's **type**. Go-to-definition answers "where does this name come +from"; this answers "where does this name's *type* come from" — from +`my_pkg::state_t s;` to the `typedef` of `state_t`, from `bus_if bus` or +`virtual bus_if vif` to the `interface bus_if`, from the instance name of +`sub u_sub (...)` to `module sub`, and from `my_cls h;` to `class my_cls`. It +is the second-most-used navigation key in an editor after F12, it is exactly +the jump a Verilog reader wants when a signal is a package enum declared three +files away, and — this is why it is cheap — the answer is a location +`textDocument/definition` already knows how to compute. Everything this +feature adds is *which offset to ask about*. + +## Assumptions + +- **A declaration's type is written as an identifier, and `vlog_semantic` + recorded it as a use.** `bind.rs::bind_data_type` calls `use_name` for every + non-keyword type name, searching the window from the start of the + declaration to the first name it declares. This feature finds that same + window from the parse tree and picks the reference the binder left in it. A + keyword type (`logic`, `wire`, `int`) is never a reference, which is what + makes "a built-in has no type definition" fall out with no special case. +- **One hop, never a chain.** With `typedef state_t alias_t; alias_t x;` the + cursor on `x` lands on `alias_t`'s typedef, not on `state_t`'s. That is what + every editor's go-to-type-definition does; the user presses the key again for + the next hop, and each hop is a place they can read. Chasing the chain to its + root would land somewhere the source never mentioned. +- **The cursor on a type name answers for that name.** `state_t` in + `state_t s;` is already a type, so its type definition is its own + declaration — the same location F12 gives there. Pinned by a test either + way, since it is the one position where "definition" and "type definition" + visibly coincide. +- **A declaration name is not a use.** The cursor on the `alias_t` *of* + `typedef state_t alias_t;` takes the hop its declaration offers (`state_t`) + rather than answering itself, which would waste the keystroke. +- **A `module`, `interface` and `program` are one AST node and one + `SymbolKind::Module`**, so an interface is reached by exactly the code that + reaches a module. +- **The tree is the tolerant parse.** A declaration inside an `Error` node is + no declaration at all and answers nothing — the same degradation every other + tree-reading handler has (`docs/features/error-recovery/README.md`). +- **An `InheritedCandidate` in a *type position* is a lexical miss, not an + answer.** `resolve.rs`'s `miss` turns *every* miss inside a class carrying an + `extends` into `Resolution::InheritedCandidate`, whether or not the name has + anything to do with inheritance — so in a type window it means only "a base + class *might* declare this type". `vlog_semantic` never chases a base chain + (in this file or out of it: `lexical` walks `scope.parent`, which is lexical + nesting, and `miss` records the base's *name* and stops; `resolve_external` + only finishes an `ExternalCandidate`), so no layer can turn that into a + location, and the workspace's file-scope type of that name is the best + honest answer available. This is assumed, not enforced: a base class that + genuinely declares a nested type of the same name would be the better answer, + and nothing here can produce it — but nothing displaces it either, because + the fallback is consulted only after `nav::definition` came back empty. The + day `vlog_semantic` does chase a base, such a reference becomes + `Resolution::Resolved`, `definition` answers it, and the fallback is never + reached. Pinned by + `an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it`. + +## Handshakes + +**Consumed from `vlog_parser`:** `ast::{Item, ItemKind, Module, PortList, +AnsiPort, ParamPort, TfArg, DataType, Declarator, Typedef, TypedefKind, +Instantiation, GenIf, GenElse, GenBlock, Stmt, StmtKind}` and `TextRange`. +Read-only; nothing was changed. + +**Consumed from `vlog_semantic`:** `Semantics::{references, reference_at, +symbol}`, `Reference::{name, name_span, resolved}`, `Resolution::NotFound`, +`SymbolKind`, and `WorkspaceIndex::{units, path}` for the one fallback below. +Read-only; nothing was changed. + +**Consumed from this crate:** `nav::definition` (the whole answer), +`nav::symbol_at` — widened from private to `pub(crate)` so the two handlers +cannot disagree about what a position names — and `locate::location`. + +**Promised:** `type_def::type_definition(ws, uri, offset) -> Vec`, +serving `server.rs`'s `GotoTypeDefinition` arm. Same answer shape as +`GotoDefinition`: an array in every case, empty where there is nothing to jump +to, every candidate where the workspace declares the name twice, and an empty +array (not `null`) for a buffer the server was never sent. + +**Requested of other modules** — neither blocked this round, and neither was +done here: + +1. **`vlog_semantic`: report an unresolved *unqualified* name as an external + candidate, not as a bare lexical miss.** `resolve.rs`'s `lexical` miss ends + in `Resolution::NotFound` whenever the file collected no import paths on the + way out — or, inside a class with an `extends`, in + `Resolution::InheritedCandidate` — and neither reaches `resolve_external`, + so the workspace overlay never sees the name. That is precisely how an + `interface` is written (`bus_if bus;` — interfaces live at file scope, not + in packages) and how a package-less `class` is used, so the two headline + cross-file cases of this feature would answer nothing; and the + `InheritedCandidate` half covers nearly every UVM class, since almost all of + them extend something. The ask: for a `Target::Lexical` miss, emit + `ExternalCandidate { paths: vec![name] }` — the same shape `Target::Module` + already emits — **in both spellings**, i.e. also carry the bare name in the + `paths` of an `InheritedCandidate`, so the index's unit table finishes it + without losing the recorded base. Until then this feature asks the index + itself, in one function (`indexed_type`) fenced by three conditions: only + for a reference the file reported as one of those two misses, only for a + **file-scope** declaration, and only for the kinds that can be a type + (`Module`, `Class`, `Typedef` — a `package` of that name is not one). When + the request above lands, that function is deleted and nothing else in this + module changes. +2. **`vlog_parser`: an ANSI header whose *first* port carries no direction does + not parse.** `module m (bus_if bus, input logic clk);` becomes an `Error` + item, while `module m (input logic clk, bus_if bus);` parses fine — the + list is classified ANSI-or-not from its first element, and a bare + `type name` pair reads as neither a non-ANSI name list nor a directed port. + `module m (bus_if.mp bus)` (a modport-qualified port) and + `module m (my_pkg::state_t s)` do not parse either. Not this feature's to + fix, and not a regression it caused: the tests here write the interface + port second and say why. + +## Status / TODO + +- [x] `crates/lucisv_server/src/type_def.rs`: the offset redirection, the + declaration walk, and the index fallback. +- [x] `type_definition_provider` advertised (`TypeDefinitionProviderCapability::Simple(true)`). +- [x] `GotoTypeDefinition` dispatched in `server.rs`, on `GotoDefinition`'s + conventions exactly. +- [x] `nav::symbol_at` shared rather than re-implemented. +- [x] 24 unit tests: typedef, enum/struct typedef, class handle (module item + and method body), module instance, interface instance / port / `virtual` + handle, header parameter, task argument, generate block, `pkg::t`, + `import pkg::*` + bare name, cross-file interface, cross-file class, + built-ins, a package that is not a type, a refused qualified name, an + unopened buffer, a position on no name, ambiguity, UTF-16 positions, + one-hop aliasing. +- [x] **Fix round (2026-08-26):** `indexed_type`'s fence widened to accept + `Resolution::InheritedCandidate` as well as `NotFound`, closing the QA + finding below (a cross-file type used as a member of any `extends`-ing + class — nearly every UVM class — answered nothing). 4 tests added, QA's + regression test flipped, corpus spot-check assertions flipped positive. +- [x] One e2e round trip: the capability in the real handshake, a cross-file + package typedef, and a built-in answered with an empty array. +- [x] TODO.md §9c checkbox; `docs/features/lucisv-server/README.md` capability + table. +- [ ] **Not done, deliberately:** a function's *return* type is not a site — a + cursor on `f` in `function state_t f();` answers nothing. It is a + defensible answer to give and a defensible one to withhold, and giving it + needs a guard (the cursor must be in the header, not in the body) that + the other sites do not, so it waits for somebody to ask for it. +- [ ] **Not done, deliberately:** a `bind` directive's instance. Its name is + declared into another module's scope, so this file is not the one to + answer for it (`docs/features/bind/README.md`). +- [ ] **Not done:** a member's type (`x.field`, `h.member`). `vlog_semantic` + does not resolve member access at all, so there is no symbol to ask about + — the same boundary hover and `references` stop at. + +## Work log + +### 2026-08-26 — dev agent + +- **Read the semantic layer before writing anything, and the key question came + back "no, but".** A `Symbol` carries no type: its `decl_span` is its + *declarator* (`bind.rs::bind_declarators` passes `d.span`), so the type name + is outside every span the symbol table holds, and there is no `type` field + anywhere in `model.rs`. What the crate *does* have is the type name as an + ordinary `Reference` — `bind_data_type` calls `use_name` on it, resolved + lexically or as a `pkg::` member — which is the whole feature: the answer is + `nav::definition` of the type name's own offset. So `vlog_semantic` was not + modified, as the brief required, and the only thing that had to be built is + the map from *a position* to *the type name's position*. +- **That map needs the tree, and is offset-driven, which kept it small.** + `site_at` descends items, module headers, class bodies, generate blocks and + statements, pruning by span containment exactly as `selection.rs` does, and + returns the one declaration covering a position: the type name as written + plus the window it was written in. The window is deliberately the same one + the binder searched (start of the declaration → start of the first declared + name), which turns "where is the type name" into a *match* against the + reference table rather than a scan of the text. A qualified type is two + references (`pkg`, then `state_t`) and the second is the one worth jumping + to, so a name with `::` is matched by its last segment; an instantiation + stores its name glued, so the whole name is tried first. +- **New module, not an extension of `nav.rs`.** `nav.rs` is definition + + references + highlights over `Semantics` alone; this needs a parse-tree walk + that has no reader there, and the two things it borrows from `nav` (the + `definition` call and `symbol_at`) are a public function and a one-word + visibility change. Adding ~250 lines of AST walking to a 625-line module + whose subject is the symbol table would have made both harder to read. +- **One walk, not a reuse of `instantiations::sites`.** That walk finds + instantiations only, and this one has to visit declarations in the same + containers; running both would mean descending generate blocks twice and + keeping two lists of container node kinds in step. The instantiation arm here + is two lines. +- **The cross-file gap found by a failing test, and fenced rather than + papered over.** `bus_if bus` and `my_cls h` — an unqualified type name + nothing in the file binds — resolve to `Resolution::NotFound`, never to an + external candidate, so the workspace overlay never sees them and the two + headline cross-file cases returned nothing. Fixing that properly is a + `vlog_semantic` change this round may not make, so it is written up as + Handshake request 1 and stood in for by `indexed_type`: the index's own unit + table, asked only for a `NotFound` reference, only for file-scope + declarations, and only for kinds that can be a type. Two tests pin the + fence — a `package` of the same name is not an answer, and a `pkg::missing_t` + the overlay already refused is not retried against a decoy module of that + name. +- **Two parser limitations found and recorded, neither touched**: an ANSI + header whose first port has no direction does not parse, and neither does a + modport-qualified or package-qualified header port. Handshake request 2. The + interface-port tests write the port second and carry a comment saying why, so + the day the parser improves the tests read as deliberate rather than + mysterious. +- **Conventions followed exactly rather than re-decided**: the answer is an + array in every case (`GotoDefinition`'s shape, including the empty array for + an unopened buffer, which is what `self.offset(...).unwrap_or_default()` + means at both call sites); ambiguity returns every location; positions go + through `Positions`/`locate::location`, so UTF-16 is not this module's + problem and is pinned by a test anyway. +- **No new dependencies, no version bump, no engine crate touched.** Files + added: `crates/lucisv_server/src/type_def.rs`, this README. Files edited: + `main.rs` (module line, capability, capability test), `server.rs` (imports, + one dispatch arm), `nav.rs` (one visibility word plus its doc line), + `tests/e2e.rs` (one round trip), `TODO.md` (§9c checkbox), + `docs/features/lucisv-server/README.md` (capability table + Status). +- **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets`: + 0 warnings. `cargo test --workspace`: green. `cargo build && node + editors/vscode/smoke.js target/debug/lucisv-server`: pass. No `git commit`, + no `git push`. + +### 2026-08-26 — dev agent (fix round: the QA finding) + +- **The fence widened by one pattern, nothing else.** `indexed_type`'s first + condition now reads + `Some(Resolution::NotFound | Resolution::InheritedCandidate { .. })` + (`crates/lucisv_server/src/type_def.rs:138`). The other two — file-scope + declarations only (structurally, because `WorkspaceIndex::units` holds + nothing else) and `Module`/`Class`/`Typedef` kinds only — are untouched, as + is every other line of the module. The doc comment now explains *why* the two + resolutions are one case: they are the two spellings `resolve.rs`'s `miss` + gives the same event, and which one you get depends only on whether an + `extends` happens to be overhead. +- **The precedence question, answered by reading rather than assumed.** The + brief asked whether in-file inherited resolution can already produce a + location for an in-file base's nested typedef, so that the widening might + displace a better answer. It cannot, at three independent points: + `resolve.rs::lexical` (`crates/vlog_semantic/src/resolve.rs:39-70`) walks + `scope.parent`, which is *lexical* nesting and never a base class's scope; + `miss` (`:201-213`) records the base's name and stops, exactly as its own doc + comment says ("which this crate never chases, in this file or out of it"); + and `resolve_external` (`crates/vlog_semantic/src/workspace.rs:382-391`) + skips anything that is not an `ExternalCandidate`, so an `InheritedCandidate` + never reaches the overlay either. So the fallback displaces an empty answer, + not a better one. Precedence also needs no code of its own now or later, + because `indexed_type` is consulted only after `nav::definition` came back + empty (`type_def.rs:58-63`): the day `vlog_semantic` does chase a base, the + reference becomes `Resolved`, `definition` answers the nested typedef, and + the fallback is never reached — the same mechanism that already makes a local + genvar of the same name win. Written up in Assumptions and pinned by + `an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it`, + which asserts both halves: the resolution really is `InheritedCandidate` + (so nothing found the nested typedef) and the answer really is the workspace + interface. +- **QA's regression test flipped, name and fixture kept.** + `a_class_scoped_type_reference_in_an_extending_class_is_never_found_cross_file` + → `..._is_found_cross_file`, same portable fixture, and it still asserts the + resolution is `InheritedCandidate` — the point being that the fence widened + and `vlog_semantic` did not. +- **Four tests added** (`type_def.rs`, all portable, no corpus): + `a_uvm_shaped_member_type_resolves_cross_file_from_an_extending_class` (the + ibex shape: a base class that is nowhere in the workspace, two cross-file + interfaces as member types, reached from both the type half and the + declarator half); + `an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it` + (the precedence determination above); + `a_non_type_inherited_reference_is_still_never_a_type_site` (an ordinary + expression identifier inside an extending class — the one place the widening + could have leaked, and it does not, because no `Site` is built for an + expression statement so the fence is never even consulted); and + `the_other_two_fence_conditions_still_hold_under_an_inherited_candidate` + (three arms, all from inside an extending class: a `package` of that name is + still not a type; a package *member* typedef is still not file-scope and so + is not in the unit table; a `pkg::missing_t` the overlay already refused is + still not retried against a decoy module of that name). +- **The corpus spot-check now asserts the fix on the file that found it.** + `corpus_spot_check_real_uvm_files_no_panic_and_known_jumps`'s two "known gap" + assertions on `dv/uvm/core_ibex/env/core_ibex_env_cfg.sv` became positive + ones: `clk_rst_if` and `core_ibex_dut_probe_if` each jump to exactly one + location, in `clk_rst_if.sv` and `core_ibex_dut_probe_if.sv` respectively. + Not brittle: both are `virtual ;` members of a class the file + opens with, both interfaces are vendored in this checkout under those file + names, and the probes match on the multi-space alignment the file uses. The + test still skips itself when `corpus/` is absent, and + `scrambling_key_agent_cfg` — a class genuinely not vendored here — is still + asserted empty, which is what keeps the widening from reading as "answer + something, anything". +- **Scope.** Files edited: `crates/lucisv_server/src/type_def.rs` (one match + pattern, its doc comment, the test module) and this README. `vlog_semantic` + untouched; `TODO.md` needed no truth fix (its §9c line claims the capability, + which was true before this round and is more true after). Test count in + `type_def.rs`: 42 (was 38). +- **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets + --workspace`: 0 warnings. `cargo test --workspace`: green (748 passed / 4 + ignored in `lucisv_server`'s own suite, 0 failed anywhere). `cargo build && + node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. No + `git commit`, no `git push`. + +## QA log + +### 2026-08-26 — QA agent (continuation of an interrupted run) + +This run resumed a QA pass interrupted mid-way. The prior pass had already +added 13 tests to `crates/lucisv_server/src/type_def.rs` (all still present, +all re-run and green below) but had not yet written anything to this log — +its work is folded into the write-up below rather than repeated as a separate +entry, since there was nothing here to distinguish "already recorded" from +"found this session." What follows covers the full original checklist. + +**A. Gates — all green, re-run from a clean state:** + +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --all-targets --workspace`: 0 warnings. +- `cargo test --workspace`: green throughout, including after every change + this session made (744 passed / 4 ignored in `lucisv_server`'s own suite, + 0 failed anywhere in the workspace both before and after). +- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: + `smoke: OK`. + +**B. Attack surfaces.** + +1. **`indexed_type` fence** — verified clean, with one finding (below). + - Shadowing locals: `a_local_declaration_of_the_same_name_wins_over_the_workspace_type` + (type_def.rs:813) — a genvar named `bus_if` in scope where `bus_if` is + also a workspace interface; `lexical` resolves it locally + (`Resolution::Resolved`), the fence's first condition never fires, and + the answer is the genvar's own declaration. Re-run, passes. + - Non-type positions (structural confinement to type windows): `a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site` + (type_def.rs:863) — `assign x = dup;` where `dup` is also a workspace + module name; no `Site` is ever built for an expression statement + (`site_at`/`item_site` only recurse into `DataDecl`/`PortDecl`/ + `ParamDecl`/`Typedef`/`Instantiation`/statement-declaration kinds — an + `ExprStmt` is not one, confirmed by reading `stmt_site`, type_def.rs:311-343), + so `type_definition` answers empty regardless of the fence. Re-run, passes. + - Ambiguity convention vs. `nav::definition`'s: dev's `a_module_declared_twice_returns_both_declarations` + goes through `Target::Module`'s `ExternalCandidate` path; QA's + `indexed_type_returns_every_workspace_declaration_when_the_name_is_ambiguous` + (type_def.rs:888) pins the same convention through the `indexed_type`/ + `NotFound` path specifically, which none of dev's tests touch. Verified + by code reading that both really do share one convention, not two that + happen to agree today: `indexed_type` and `resolve_external` + (vlog_semantic/src/workspace.rs:382,413) both read + `WorkspaceIndex::units(name)` (workspace.rs:105) — the same `BTreeMap` + insertion order, "by file path, then by position in the file" per its + own doc comment — so there is structurally one ordering, not a + coincidence. Re-run, passes. + - Package-of-same-name exclusion: dev's `a_package_of_the_same_name_is_not_a_type` + (type_def.rs:695). Re-run, passes. + - Function/instance/port name collisions: **not re-tested empirically — + verified structurally impossible instead.** `indexed_type` only ever + sees `ws.index().units(name)`, and `WorkspaceIndex::add_file` only + inserts a name into `units` when `is_unit(kind)` + (vlog_semantic/src/workspace.rs:206-219, `is_unit` at :288-293) is true, + which is exactly `Module | Package | Typedef | Class`. A function, a + task, a port, or an instance name can never appear in `units()` at all + — there is no fence to test because there is no path for the collision + to occur through. This is the same mechanism that makes the + package-of-same-name test necessary in the first place (`Package` *is* + a unit kind, which is why `indexed_type`'s own kind filter, not just + `is_unit`, is needed for that one case). + + **Finding (significant, corpus-derived) — the `NotFound`-only fence + misses the single most common real-world shape.** `resolve.rs`'s `miss` + (vlog_semantic/src/resolve.rs:190-201) resolves *any* lexical miss inside + a class body carrying an `extends` clause as `Resolution::InheritedCandidate`, + never `NotFound` — unconditionally, regardless of whether the missing name + has anything to do with inheritance. `indexed_type` (type_def.rs:126-130) + only fires on `NotFound`. Consequence: a cross-file interface or + package-less class used as the type of *any* member of *any* class that + extends something — which in practice is nearly every UVM class, since + almost all of them extend `uvm_object`/`uvm_component`/etc. — falls + through both layers and answers nothing, even though the interface or + class in question is genuinely declared elsewhere in the workspace. + Reproduced live on real corpus text: `corpus/ibex/dv/uvm/core_ibex/env/core_ibex_env_cfg.sv:5,7` + (`class core_ibex_env_cfg extends uvm_object;` / + `virtual clk_rst_if ibex_clk_vif;`) — `clk_rst_if.sv` is indexed + (confirmed via `ws.index().units("clk_rst_if")`), the reference resolves + to `InheritedCandidate { base: "uvm_object", .. }` rather than `NotFound` + (confirmed via `reference_at`), and `type_definition` at that offset + returns `[]`. Pinned as a portable (non-corpus) regression test, + `a_class_scoped_type_reference_in_an_extending_class_is_never_found_cross_file` + (type_def.rs:771), and reproduced again on the live corpus file in + `corpus_spot_check_real_uvm_files_no_panic_and_known_jumps` (type_def.rs:1048). + Not fixed here: widening the fence to also accept `InheritedCandidate` + looks like the natural fix and is probably safe (the fence's other two + conditions — file-scope declaration, `Module`/`Class`/`Typedef` kind only + — still apply), but it is a production-logic change with its own shadow + risk (a name that is genuinely an inherited member, not a type at all, + coincidentally sharing a workspace type's name) that deserves its own + design pass and tests rather than a QA drive-by fix. Recommend either + widening `indexed_type`'s match at type_def.rs:128 to include + `Resolution::InheritedCandidate { .. }`, or folding it into Handshake + request 1 to `vlog_semantic`, whichever the dev prefers — either way this + is the highest-value follow-up this feature has. + +2. **Position→type-window mapping vs. `bind_data_type`** — verified clean. + Array dims: `packed_and_unpacked_array_dimensions_do_not_confuse_the_type_match` + (type_def.rs:992). Inline anonymous struct: `an_inline_anonymous_struct_has_no_type_name_to_jump_to` + (type_def.rs:942) — both the declarator-name cursor and a cursor inside + the inline body answer empty, not a bogus jump. Multiple declarators: + `a_later_declarator_in_a_multi_declarator_line_still_finds_the_type` + (type_def.rs:957). Parameter-typed decls: dev's + `a_parameter_and_a_task_argument_are_typed_declarations_like_any_other`. + `var`/`const` prefixes: `var_const_and_signed_qualifiers_do_not_shift_the_type_window` + (type_def.rs:976). Function arguments (the task-argument case's twin): + `a_function_arguments_type_is_reached_like_a_task_arguments` (type_def.rs:1004). + All re-run/added, all pass. + +3. **One-hop semantics + degenerate `typedef t t;` totality** — verified + clean. Dev's `an_alias_chain_is_walked_one_hop_at_a_time` plus QA's + `a_self_referential_typedef_is_total_and_does_not_loop` (type_def.rs:909), + which checks every offset on `typedef t t;` answers promptly with no + panic and no hang (there is no chain-following code path to loop in the + first place — the one-hop design makes this total by construction, and + the test pins that operationally). Re-run, passes. + +4. **Delegation honesty** — verified clean, by code reading and by test. + Every `Location` this module returns is built by `crate::locate::location` + — `nav::definition`'s own answers (type_def.rs:58) and `indexed_type`'s + fallback answers (type_def.rs:138) both call the same function imported + at type_def.rs:45; there is no second, ad hoc `Location` construction + anywhere in the file. `type_definition_on_a_type_name_agrees_exactly_with_definition` + (type_def.rs:925) asserts literal equality with `nav::definition` at the + same offset for the case where the two are supposed to coincide. Re-run, + passes. + +5. **Null conventions** — verified clean. Built-ins: + `a_built_in_type_has_no_declaration_to_jump_to`. Unopened buffer: + `a_buffer_the_server_does_not_hold_answers_nothing`. Position on no name: + `a_position_on_no_name_at_all_answers_nothing`. Comment/whitespace cursor: + `a_position_inside_a_comment_answers_nothing` (type_def.rs:1028). Past-EOF: + `a_position_past_the_end_of_the_file_answers_nothing_not_a_panic` + (type_def.rs:1021), offset = file length + 5000. All total (empty + `Vec`, never a panic). Re-run, all pass. + +6. **Both claimed parser gaps, reproduced directly against `vlog_parser::parse_source_tolerant` + (temporary throwaway test, removed after use — not committed):** + - `module m (bus_if bus, input logic clk);` → `Error(RawText)`, + diagnostic `expected \`)\` (found "bus")` at the position right after + `bus_if`. Confirms the first-port-direction-less claim exactly. + - `module m (bus_if.mp bus);` (modport-qualified) → `Error(RawText)`, + `expected \`)\` (found ".")`. Confirms the second claim in the same + Handshake bullet. + - `module m (my_pkg::state_t s);` (package-qualified) → `Error(RawText)`, + `expected \`)\` (found "::")`. Confirms the third. + Both Handshake requests in the feature README are accurate as written. + +7. **CLAUDE.md compliance** — verified clean. + - No `unwrap()`/`expect()`/`panic!` anywhere in `type_def.rs` outside + `#[cfg(test)] mod tests` (checked by scanning the file up to that + marker); `main.rs`/`server.rs`/`e2e.rs` diffs use them only inside test + code, which CLAUDE.md permits. + - `pub fn type_definition` and the newly-`pub(crate)` `nav::symbol_at` + both carry doc comments; no other `pub` items were added. + - README sections (Goal/Assumptions/Handshakes/Status/Work log/QA log/ + Review) each appear exactly once, in order. + - `TODO.md`'s §9c item text is unchanged; only the checkbox flipped and a + `→ delivered ...` annotation was appended in the file's existing, + already-established style (18 other items use the same `→` convention; + grepped to confirm this isn't a one-off). + +**C. Corpus spot-check — completed; found and fixed a test-harness bug along +the way, and found the significant `indexed_type` gap above.** + +The interrupted run had left an `#[ignore]`d scratch test +(`qa_scratch_corpus_spot_check`) that opened a **fresh `Workspace` and called +`open_roots` (a full corpus re-index) for every one of ~400 small corpus +files** in its panic-sweep loop. That made the test re-scan the whole +`corpus/ibex` tree (651 files) once per small file — confirmed by running it: +still not finished after 5.5 minutes of CPU time, killed rather than waited +out. This was a test-harness bug, not a product one (`Workspace::set_document` +only overlays a buffer against an index already built — +`crates/lucisv_server/src/state.rs:175-179` — so the fix is to build the +index once and reuse it). Rewrote it as +`corpus_spot_check_real_uvm_files_no_panic_and_known_jumps` (type_def.rs:1048), +un-ignored, now runs in ~2.6s: + +- Full-file offset sweep (every byte offset, no `step_by`) over + `dv/uvm/core_ibex/tb/core_ibex_tb_top.sv` (21 KB) and both + `core_ibex_env_cfg.sv`/`core_ibex_scoreboard.sv` — no panic. +- A genuine positive control on real corpus text: `clk_rst_if ibex_clk_if(...)` + in `core_ibex_tb_top.sv` (a module-scope interface instantiation, not + inside any class) jumps to exactly one location, in `clk_rst_if.sv` — + confirming the happy path this feature claims works on code nobody wrote + as a fixture. +- The `indexed_type`/`InheritedCandidate` gap above, reproduced on the same + real file it was found in (`clk_rst_if`, `core_ibex_dut_probe_if` — both + real, indexed interfaces — answer empty inside `core_ibex_env_cfg`, which + `extends uvm_object`). +- `scrambling_key_agent_cfg` (dev/prior-run's negative probe) confirmed + still empty, and confirmed *why*: that class is not vendored into this + corpus checkout at all (`grep -rl "class scrambling_key_agent_cfg" corpus/ibex/` + finds nothing), so empty is correct regardless of resolution kind — not a + second instance of the gap. +- 413 small `.sv`/`.svh` files under `corpus/ibex` (≤4000 bytes each), + every third byte offset, sharing the one indexed workspace: no panic. + +**D. Tests added this session** (on top of the 13 the interrupted run had +already added and which are re-verified above): 1 — +`a_class_scoped_type_reference_in_an_extending_class_is_never_found_cross_file` +(type_def.rs:771) — plus the corpus test rewrite described in C. Total in +`type_def.rs`: 38 (24 dev + 14 QA). `cargo test -p lucisv_server --bin +lucisv-server type_def::` : 38 passed, 0 failed. + +**Overall verdict:** not committable as-is. Every hard invariant, every gate, +and six of the seven checklist attack surfaces are clean, and the feature's +core design (offset redirection to `nav::definition`) is sound and exactly as +documented. But the `indexed_type` fallback — the piece this feature added +specifically to cover cross-file interfaces and classes — silently answers +nothing for that exact case inside the single most common real-world +container for it (any class with `extends`), which covers most UVM +environment/agent/scoreboard/sequence classes in practice. That is a +functional gap in the feature's own headline claim, not a cosmetic one, and +it was findable only by running on real code, not by the crafted unit tests +(hence being caught here rather than in dev's own suite). Recommend: dev +either widens the `indexed_type` fence to accept `InheritedCandidate` (with +its own shadow-risk tests) or files it as a second, explicit Handshake +request to `vlog_semantic`; either way, one more QA pass over just that +change before this ships. Nothing else found blocks a commit. + +### 2026-08-26 — QA agent (fix-round re-verification) + +Scoped to the fix only, per the lead's brief: not a redo of the original +checklist above, all of which stands. + +**A. Gates — re-run from a clean state, all green:** + +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --all-targets --workspace`: 0 warnings. +- `cargo test --workspace`: green throughout — 748 passed / 4 ignored in + `lucisv_server`'s own suite before any QA changes (matching dev's claim + exactly), 750 passed / 4 ignored after adding the two tests below, 0 failed + anywhere in the workspace at every step. +- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: + `smoke: OK`. + +**B. Diff minimality — confirmed by mtime, since neither changed file has any +commit history to `git diff` against (both are still untracked; this feature +has never been committed).** `type_def.rs` and this README were last written +at 15:12 and 15:14 respectively; every other file the original round touched +(`main.rs`, `nav.rs`, `server.rs`, `tests/e2e.rs`, `TODO.md`, +`docs/features/lucisv-server/README.md`) was last written between 14:19 and +14:30 — nearly 45 minutes earlier, before the fix round started. Consistent +with dev's claim that the fix round touched only `type_def.rs` (one match +arm, its doc comment, the test module) and this README. Not a substitute for +a real diff, but the strongest signal available without one. + +**C. The three precedence citations — read directly, all accurate:** + +- `resolve.rs::lexical` (`crates/vlog_semantic/src/resolve.rs:39-70`): walks + `scope.parent` only (line 67); no reference to a base class's scope + anywhere in the function. Confirmed. +- `resolve.rs::miss` (`:201-213`): for a non-unit miss, returns + `InheritedCandidate { base, external }` when `nearest_extends` finds one + (line 206) — the base's *name* only, never chased — and only falls through + to `NotFound`/`ExternalCandidate` otherwise. Confirmed. +- `workspace.rs::resolve_external` (`:382-391`): `let Resolution::ExternalCandidate { paths } = &reference.resolution else { continue };` — + an `InheritedCandidate` (or `NotFound`) is skipped outright, never handed to + `follow_paths`. Confirmed. + +Together these close the precedence question exactly as claimed: no path in +`vlog_semantic` today can turn an `InheritedCandidate` into a `Location`, so +the widened fence only ever fires where `nav::definition` already came back +empty (`type_def.rs:58-63`, also read and confirmed). + +**D. Fence re-attack.** + +1. **Original shadowing counterexamples, re-run:** all still pass — + `a_local_declaration_of_the_same_name_wins_over_the_workspace_type`, + `a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site`, + `a_package_of_the_same_name_is_not_a_type`, + `indexed_type_returns_every_workspace_declaration_when_the_name_is_ambiguous`. + Untouched by the fix, verified by reading them, not just by the green + suite. +2. **New: a local typedef of the same name inside the *extending* class's own + body (as opposed to dev's test, which puts it in the *base*).** Added + `a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type` + (`type_def.rs`, QA fix-round section) — `class top extends base; typedef + int bus_if; bus_if h; endclass` alongside a workspace interface also named + `bus_if`. Confirmed `Resolved` (not `InheritedCandidate`) and the jump + lands on the in-file typedef, never the workspace interface — `lexical`'s + own-scope lookup (resolve.rs:44) wins before `miss` ever runs, so the + widened fence is not even consulted here. Passes. +3. **New: an `InheritedCandidate` in a type window matching a workspace + MODULE.** Added + `an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did` + — a member of an extending class typed as a name that is only a workspace + *module*. Resolution is `InheritedCandidate` as expected, and the fence's + kind filter (`Module | Class | Typedef`, unconditioned on which resolution + triggered it) lets it through exactly as it already would for `NotFound` — + confirmed both by this new pinned test and by re-reading `indexed_type` + (type_def.rs:136-148), which never branches on *which* of the two + resolutions matched. Passes; now pinned permanently. +4. **`pkg::t` qualified references — mostly unaffected, but not entirely, and + this predates the fix.** Verified by two throwaway probes (not committed — + removed after use, per the convention the last QA round set). The common + case dev's claim describes is correct: when the qualifying unit is not + declared in this file at all, the reference is `ExternalCandidate` + (`a_qualified_name_the_overlay_refused_is_not_retried_against_the_index` + already pins this). But `resolve.rs::unit_member` (`:121-166`) has its own, + separate miss path via `Target::UnitMember`: when the unit *is* found + locally — a `Class` with `extends` whose own scope lacks the member, or a + `Package`/extends-less `Class` whose own scope lacks the member — the + member reference resolves to `InheritedCandidate` or plain `NotFound` + respectively, exactly the two spellings `indexed_type` matches on. + `indexed_type` does not look at which `Target` produced the resolution; it + takes the *bare* member name and searches the whole workspace unit table + with it, discarding the qualifier entirely. Reproduced concretely: with + `class base; endclass class top extends base; endclass` and `module m; top::ambiguous_member x; endmodule`, + plus an unrelated `class ambiguous_member` in another file, the reference + resolves to `InheritedCandidate` and `type_definition` jumps straight to + the unrelated decoy — nothing about `top` or its `base` chain was ever + consulted. **This is not new or introduced by this fix round**: the control + probe swaps `top extends base` for a plain `package local_pkg; endpackage` + (so the miss is a bare `unit_member` `NotFound`, the resolution this + feature's fence has matched since the original round) and reproduces the + identical bare-name jump to the same kind of decoy. So the widening did not + create this gap — it already existed for `NotFound`-via-`Target::UnitMember` + and was implicitly accepted (or simply not probed) in the original QA + round, which tested `Target::Lexical`-produced misses and one + `Target::Unit` ambiguity case, but no `Target::UnitMember` miss on a + *locally* resolved unit. Not filed as a blocking finding against this fix + round — it is orthogonal to what changed here — but worth a follow-up: the + fence's bare-name lookup is only sound for a `Target::Lexical` miss (where + the bare name really is "does the workspace declare this anywhere"); + applying it to a `Target::UnitMember` miss answers a question the + qualifier already narrowed and can jump to a declaration with no + relationship to the qualifying unit. Recommend a design pass on + `indexed_type` to check the reference's target kind (or otherwise confine + the fence to unqualified names) the next time this file is touched. + +**E. Corpus spot-check — stable across 3 consecutive runs**, ~2.7s each, +`checked 413 small corpus files, no panic` every time, both now-positive +assertions (`clk_rst_if`, `core_ibex_dut_probe_if`) holding every run. +Fixture reasoning independently confirmed: `corpus/ibex/dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv` +and `corpus/ibex/vendor/lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv` both exist +in this checkout exactly where the test expects them. Not brittle by any +signal found this session. + +**F. Tests added this session:** 2, both permanent — +`a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type` +and `an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did`. +Total in `type_def.rs`: 44 (42 + 2 QA). Two additional throwaway probes used +to investigate item D.4 above were removed after confirming the finding, per +the standing convention (not committed). + +**Overall verdict: committable.** The fix is exactly what it claims to be — +one match arm widened, nothing else in production code touched, confirmed by +mtime and by reading the file in full. The three precedence citations hold up +under independent reading. All of the previous QA round's attack surfaces +still pass unchanged. Two new attack angles the brief asked for (local +same-class shadowing, module-kind parity) are now pinned permanently and both +pass. The corpus regression this fix was written for is confirmed fixed and +stable. One new, non-blocking finding (D.4 above) is pre-existing scope, not +a regression from this round, and is written up for a future pass rather than +held against this one. + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and both QA rounds' logs; re-ran all +gates myself, clean. This round earned its fix cycle. The core design — +type-definition as one redirection into `nav::definition`, so locations +are only ever built by one code path — is exactly right, and the module +doc explains it well enough to maintain. The original QA round's +rejection was correct and well-evidenced: the fallback built for +cross-file interfaces missed them inside every extending class, found on +a real Ibex file by the corpus sweep. The fix round's widening is sound +because its safety argument was *derived* — three independent citations +in vlog_semantic proving no layer can turn an InheritedCandidate into a +location today — and the precedence story costs no code by construction. + +One lead addition before commit: QA's follow-up probe showed a qualified +member miss (`pkg::missing_t` against a local package) reaches the +fallback with the same two resolution spellings, and the bare-name sweep +would then discard the qualifier — a wrong jump, which this feature's +own doc comment says is worse than an empty answer. I added the +qualifier guard in `indexed_type` (decline when the text before the +reference ends with `::`), with a pinning test proven by deliberate +breakage (fails with the guard disabled, passes with it). The +vlog_semantic Handshake stays filed covering both miss spellings; when +it lands, `indexed_type` — guard and all — is deleted whole. QA process +note: the first QA agent was lost to an infrastructure error mid-run; +the resumed agent picked up its uncommitted work, finished the sweep, +and found the rejection-worthy bug in the step the first run never +reached. Accepted as shipped.