diff --git a/TODO.md b/TODO.md index e647032..f0a95c0 100644 --- a/TODO.md +++ b/TODO.md @@ -287,11 +287,22 @@ later: gaps — no `` `ifdef`` evaluation, no cross-file `` `include`` — in `docs/features/define-table/README.md`. Hover itself waits on `vfmt_server`; this is only the table. -- [ ] **Workspace index for cross-file navigation.** Map module/package/ +- [x] **Workspace index for cross-file navigation.** Map module/package/ typedef names → (file, span) across all workspace files, so header imports (`import pkg::*;`) and instantiations resolve to definitions in other files. Start as a full-scan-on-startup index (Verilog codebases are small); incrementality comes with salsa later. + → `vlog_semantic::WorkspaceIndex::build(files) `+ + `resolve_external(&Semantics, &WorkspaceIndex) -> ExternalResolutions`, + a two-layer design: the index is a full scan (860 corpus files in 0.7 s), + the answers arrive as an overlay keyed by `ReferenceId` and `Semantics` + is never mutated. Package/module members and per-file `` `define`` + tables are indexed too, so `import p::*`, `p::x` and `.port(...)` all + reach into the other file. On cleanly-parsed corpus files the workspace + answers **87 % of the external candidates**, taking the unresolved- + external rate from 19.6 % to 2.6 % of all references. Duplicate-name + policy, `` `define`` lookup (no include graph → no resolution order) and + the honest gaps in `docs/features/workspace-index/README.md`. - [ ] **New crate `vfmt_server`** (analog of `ruff_server`): LSP over stdio via `tower-lsp` or `lsp-server`. Order of capabilities: 1. `textDocument/formatting` + `rangeFormatting` (reuses §2 `--lines`), diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index e73643c..08b1b7e 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -500,7 +500,7 @@ impl<'a> Fmt<'a> { fn item_kind(&self, kind: &ItemKind) -> Doc { match kind { ItemKind::Module(m) => self.module(m), - ItemKind::Package { kw, name, items, dangling, end_label } => { + ItemKind::Package { kw, name, items, dangling, end_label, .. } => { let mut docs = vec![text(format!("{kw} {name};"))]; let mut body = Vec::new(); if !items.is_empty() { @@ -518,7 +518,7 @@ impl<'a> Fmt<'a> { // parses strictly, so this arm exists to keep the match total. ItemKind::Error(d) => self.raw_text(d), ItemKind::MacroItem(m) => self.macro_call(m), - ItemKind::Import(paths) => text(format!("import {};", paths.join(", "))), + ItemKind::Import(paths) => text(format!("import {};", join_paths(paths))), ItemKind::Timeunit(t) => text(format!("{t};")), ItemKind::Typedef(t) => self.typedef(t), ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d), text(";")]), @@ -530,7 +530,7 @@ impl<'a> Fmt<'a> { ItemKind::Final(s) => self.stmt_as_body(text("final"), s), ItemKind::Instantiation(inst) => self.instantiation(inst), ItemKind::GateInstantiation(g) => self.gate_instantiation(g), - ItemKind::Genvar(names) => text(format!("genvar {};", names.join(", "))), + ItemKind::Genvar(names) => text(format!("genvar {};", join_names(names))), ItemKind::GenerateRegion { items, dangling } => { let mut body = Vec::new(); if !items.is_empty() { @@ -572,7 +572,7 @@ impl<'a> Fmt<'a> { for imp in &m.imports { lines.push(Doc::HardLine); lines.extend(self.leading(&imp.meta)); - lines.push(text(format!("import {};", imp.paths.join(", ")))); + lines.push(text(format!("import {};", join_paths(&imp.paths)))); lines.extend(self.trailing(&imp.meta)); } docs.push(indent(lines)); @@ -1358,7 +1358,7 @@ impl<'a> Fmt<'a> { /// line if they fit, otherwise indented on the next line. fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc { match &s.kind { - StmtKind::Block { label, stmts, dangling, end_label } => { + StmtKind::Block { label, stmts, dangling, end_label, .. } => { let mut docs = vec![prefix, text(" ")]; docs.extend(self.leading(&s.meta)); docs.push(self.block_doc(label, stmts, dangling, end_label)); @@ -1473,10 +1473,10 @@ impl<'a> Fmt<'a> { fn stmt_kind(&self, kind: &StmtKind) -> Doc { match kind { - StmtKind::Block { label, stmts, dangling, end_label } => { + StmtKind::Block { label, stmts, dangling, end_label, .. } => { self.block_doc(label, stmts, dangling, end_label) } - StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label } => { + StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label, .. } => { let mut docs = vec![match label { Some(l) => text(format!("fork : {l}")), None => text("fork"), @@ -1550,7 +1550,7 @@ impl<'a> Fmt<'a> { StmtKind::DoWhile { body, cond } => { let mut docs = vec![text("do")]; match &body.kind { - StmtKind::Block { label, stmts, dangling, end_label } => { + StmtKind::Block { label, stmts, dangling, end_label, .. } => { docs.push(text(" ")); docs.push(self.block_doc(label, stmts, dangling, end_label)); docs.push(text(" while ")); @@ -1573,7 +1573,7 @@ impl<'a> Fmt<'a> { let head = concat(vec![ text("foreach ("), self.expr(target), - text(format!("[{}])", vars.join(", "))), + text(format!("[{}])", join_names(vars))), ]); self.stmt_as_body(head, body) } @@ -1949,6 +1949,18 @@ impl<'a> Fmt<'a> { } } +/// A comma-separated list of names, as the source wrote them. The parser +/// keeps each name's byte range alongside its text, so the joined spelling is +/// rebuilt here rather than stored. +fn join_names(names: &[Name]) -> String { + names.iter().map(|n| n.text.as_str()).collect::>().join(", ") +} + +/// The same for a list of `pkg::item` import paths. +fn join_paths(paths: &[ImportPath]) -> String { + paths.iter().map(ImportPath::text).collect::>().join(", ") +} + /// Drop up to `n` leading spaces or tabs. /// True if any line break in `text` falls inside a string literal, making /// every byte of the following line part of that string's value rather than diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 6d98897..cc586ef 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -9,10 +9,46 @@ //! carry their own spans on [`Comment`]; attribute instances `(* ... *)` are //! real tokens and *are* inside it. See `docs/features/spans/README.md` for //! which node types carry a span and why the rest do not. +//! +//! Names: a node that declares a name keeps the name as a `String` and the +//! byte range of the identifier that spells it in a sibling field — +//! `name_span` for the declared name, `label_span` / `end_label_span` / +//! `module_span` for the other names a node can carry — so +//! `src[name_span] == name`. Where a node holds a *list* of names the two are +//! bundled into a [`Name`] instead, because parallel `Vec`s cannot be kept in +//! step by construction. See `docs/features/name-spans/README.md`. use crate::span::TextRange; use crate::token::Comment; +/// A name as written, together with the byte range it occupies: +/// `src[span] == text`. +/// +/// Used where a node holds a *list* of names; a node with a single name keeps +/// it as a `String` plus a sibling `name_span`. +#[derive(Debug, Clone)] +pub struct Name { + pub text: String, + pub span: TextRange, +} + +/// One `pkg::item` (or `pkg::*`) path of an `import`, each half with its own +/// range — a language server resolves the package and the imported name +/// separately. +#[derive(Debug, Clone)] +pub struct ImportPath { + pub pkg: Name, + /// The imported name, or `*` for a wildcard (whose span is the `*`). + pub item: Name, +} + +impl ImportPath { + /// The path as it is written: `pkg::item`. + pub fn text(&self) -> String { + format!("{}::{}", self.pkg.text, self.item.text) + } +} + #[derive(Debug, Clone, Default)] pub struct Meta { pub leading: Vec, @@ -80,15 +116,19 @@ pub enum ItemKind { Package { kw: String, name: String, + /// Byte range of `name`. + name_span: TextRange, items: Vec, dangling: Vec, /// Label after `endpackage :`. end_label: Option, + /// Byte range of `end_label`. + end_label_span: Option, }, Directive(RawText), /// Macro invocation used as a module item. MacroItem(MacroCall), - Import(Vec), + Import(Vec), Timeunit(String), Typedef(Typedef), ParamDecl(ParamDecl), @@ -105,7 +145,7 @@ pub enum ItemKind { Final(Stmt), Instantiation(Instantiation), GateInstantiation(GateInstantiation), - Genvar(Vec), + Genvar(Vec), GenerateRegion { items: Vec, dangling: Vec, @@ -129,6 +169,8 @@ pub enum ItemKind { pub struct Module { pub kw: String, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, /// One entry per `import` statement written in the header. A header may /// write several (`module m import a::*; import b::t; (...)`), and merging /// them into one statement would replace a `;` with a `,`. @@ -144,6 +186,8 @@ pub struct Module { pub items: Vec, pub dangling: Vec, pub end_label: Option, + /// Byte range of `end_label`. + pub end_label_span: Option, } /// One `import` statement in a module header, with the comments written @@ -153,7 +197,7 @@ pub struct Module { pub struct HeaderImport { pub meta: Meta, /// The comma-separated paths of this one statement. - pub paths: Vec, + pub paths: Vec, } #[derive(Debug)] @@ -168,6 +212,8 @@ pub enum PortList { NonAnsi(Vec), } +/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no +/// `name_span`: the port *is* its name, so `span` already is that range. #[derive(Debug)] pub struct NonAnsiPort { pub meta: Meta, @@ -183,6 +229,8 @@ pub struct AnsiPort { pub net: Option, pub ty: DataType, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, pub unpacked: Vec, pub default: Option, /// Code extent of the port declaration. @@ -197,6 +245,8 @@ pub struct ParamPort { pub ty: DataType, pub is_type: bool, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, pub unpacked: Vec, pub default: Option, /// Code extent of the parameter port. @@ -230,6 +280,8 @@ pub struct Dim { #[derive(Debug)] pub struct Typedef { pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, pub unpacked: Vec, pub kind: TypedefKind, } @@ -252,6 +304,8 @@ pub struct EnumType { pub struct EnumMember { pub meta: Meta, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, pub value: Option, /// Code extent of the member. pub span: TextRange, @@ -308,6 +362,8 @@ pub struct PortDecl { pub struct Declarator { pub meta: Meta, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, pub unpacked: Vec, /// `=` for variables; net declarations also use this for the initial /// continuous assignment. @@ -374,6 +430,10 @@ pub enum SensSep { #[derive(Debug)] pub struct Instantiation { pub module: String, + /// Byte range of `module`. A scope-qualified name (`pkg::mod`) is stored + /// with its `::` glued, so there the slice matches `module` only modulo + /// the whitespace the source may have written around the `::`. + pub module_span: TextRange, /// The parameter override list, `None` when the source wrote no `#(...)` /// at all. An empty `Some` is a written-but-empty `#()`, which must be /// printed back: dropping it would lose two tokens. @@ -385,6 +445,8 @@ pub struct Instantiation { pub struct Instance { pub meta: Meta, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, pub dims: Vec, pub conns: Connections, /// Code extent of the instance, its connection list included. @@ -410,6 +472,9 @@ pub struct Connection { pub meta: Meta, /// Port/parameter name; `*` for the SystemVerilog `.*` wildcard. pub name: String, + /// Byte range of `name`; empty for a positional connection, which has no + /// name to point at. + pub name_span: TextRange, /// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`. /// An explicitly empty connection `.name()` is `Some(Expr::Empty)`. pub expr: Option, @@ -433,6 +498,8 @@ pub struct GateInstantiation { pub struct GateInstance { pub meta: Meta, pub name: Option, + /// Byte range of `name`. + pub name_span: Option, pub args: Vec, /// Code extent of the gate instance. pub span: TextRange, @@ -487,11 +554,15 @@ pub struct GenCaseItem { #[derive(Debug)] pub struct GenBlock { pub label: Option, + /// Byte range of `label`. + pub label_span: Option, pub is_block: bool, pub items: Vec, pub dangling: Vec, /// Label after `end :`. pub end_label: Option, + /// Byte range of `end_label`. + pub end_label_span: Option, /// Code extent of the block or of the single item it holds. pub span: TextRange, } @@ -501,6 +572,8 @@ pub struct FunctionDecl { pub qualifiers: Vec, pub ret: Option, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, /// False for old-style `function f;` declarations without a port list. pub has_parens: bool, pub args: Vec, @@ -508,12 +581,16 @@ pub struct FunctionDecl { pub dangling: Vec, /// Label after `endfunction :`. pub end_label: Option, + /// Byte range of `end_label`. + pub end_label_span: Option, } #[derive(Debug)] pub struct TaskDecl { pub qualifiers: Vec, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, /// False for old-style `task t;` declarations without a port list. pub has_parens: bool, pub args: Vec, @@ -521,6 +598,8 @@ pub struct TaskDecl { pub dangling: Vec, /// Label after `endtask :`. pub end_label: Option, + /// Byte range of `end_label`. + pub end_label_span: Option, } #[derive(Debug)] @@ -529,6 +608,8 @@ pub struct TfArg { pub dir: Option, pub ty: DataType, pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, pub unpacked: Vec, pub default: Option, /// Code extent of the argument declaration. @@ -547,18 +628,26 @@ pub struct Stmt { pub enum StmtKind { Block { label: Option, + /// Byte range of `label`. + label_span: Option, stmts: Vec, dangling: Vec, /// Label after `end :`. end_label: Option, + /// Byte range of `end_label`. + end_label_span: Option, }, ForkJoin { label: Option, + /// Byte range of `label`. + label_span: Option, join_kw: String, stmts: Vec, dangling: Vec, /// Label after `join :` (any join kind). end_label: Option, + /// Byte range of `end_label`. + end_label_span: Option, }, If { qualifier: Option, @@ -596,7 +685,7 @@ pub enum StmtKind { }, Foreach { target: Expr, - vars: Vec, + vars: Vec, body: Box, }, /// Blocking/nonblocking/compound assignment. diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index d8e3ac8..4c6187a 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -196,6 +196,15 @@ pub(crate) fn error_file(source: &str) -> SourceFile { SourceFile { items: vec![item], dangling: Vec::new(), span } } +/// Split an optional [`Name`] into the `(text, span)` pair the nodes that keep +/// a name in a `String` field store it as. +fn split_label(name: Option) -> (Option, Option) { + match name { + Some(n) => (Some(n.text), Some(n.span)), + None => (None, None), + } +} + impl<'a> Parser<'a> { fn new(tokens: Vec, source: &'a str, tolerant: bool) -> Self { Parser { @@ -489,8 +498,16 @@ impl<'a> Parser<'a> { } fn expect_ident(&mut self) -> PResult { + Ok(self.expect_name()?.text) + } + + /// The identifier at the cursor, with the byte range it occupies. The + /// parser sits on the token that spells the name, so this is where a + /// declared name's `name_span` comes from. + fn expect_name(&mut self) -> PResult { if self.cur().kind == TokenKind::Ident { - Ok(self.bump().text) + let span = self.cur().span; + Ok(Name { text: self.bump().text, span }) } else { self.error("expected identifier") } @@ -694,11 +711,12 @@ impl<'a> Parser<'a> { } } - /// The `: name` after a closing keyword (`end`, `join`, `endfunction`, - /// ...), if present. Kept on the node so the formatter can print it back. - fn parse_end_label(&mut self) -> PResult> { + /// The `: name` written after a `begin`/`fork`, or after a closing + /// keyword (`end`, `join`, `endfunction`, ...), if present. Kept on the + /// node so the formatter can print it back. + fn parse_label(&mut self) -> PResult> { if self.eat_sym(":") { - Ok(Some(self.expect_ident()?)) + Ok(Some(self.expect_name()?)) } else { Ok(None) } @@ -810,9 +828,9 @@ impl<'a> Parser<'a> { } "genvar" => { self.bump(); - let mut names = vec![self.expect_ident()?]; + let mut names = vec![self.expect_name()?]; while self.eat_sym(",") { - names.push(self.expect_ident()?); + names.push(self.expect_name()?); } self.expect_sym(";")?; Ok(ItemKind::Genvar(names)) @@ -911,7 +929,7 @@ impl<'a> Parser<'a> { fn parse_package(&mut self) -> PResult { let kw = self.bump().text; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; self.expect_sym(";")?; let mut items = Vec::new(); while !self.at_body_end("endpackage") { @@ -919,18 +937,23 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_closer("endpackage")?; - let end_label = self.parse_end_label()?; - Ok(ItemKind::Package { kw, name, items, dangling, end_label }) + let (end_label, end_label_span) = split_label(self.parse_label()?); + Ok(ItemKind::Package { kw, name, name_span, items, dangling, end_label, end_label_span }) } - fn parse_import_list(&mut self) -> PResult> { + fn parse_import_list(&mut self) -> PResult> { self.expect_kw("import")?; let mut paths = Vec::new(); loop { - let pkg = self.expect_ident()?; + let pkg = self.expect_name()?; self.expect_sym("::")?; - let sym = if self.eat_sym("*") { "*".to_string() } else { self.expect_ident()? }; - paths.push(format!("{pkg}::{sym}")); + let star = self.cur().span; + let item = if self.eat_sym("*") { + Name { text: "*".to_string(), span: star } + } else { + self.expect_name()? + }; + paths.push(ImportPath { pkg, item }); if !self.eat_sym(",") { break; } @@ -945,7 +968,7 @@ impl<'a> Parser<'a> { fn parse_module(&mut self) -> PResult { let kw = self.bump().text; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let mut imports = Vec::new(); while self.cur().is_kw("import") { let mut meta = self.take_meta(); @@ -987,10 +1010,11 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_closer("endmodule")?; - let end_label = self.parse_end_label()?; + let (end_label, end_label_span) = split_label(self.parse_label()?); Ok(Module { kw, name, + name_span, imports, param_ports, param_dangling, @@ -999,6 +1023,7 @@ impl<'a> Parser<'a> { items, dangling, end_label, + end_label_span, }) } @@ -1011,7 +1036,7 @@ impl<'a> Parser<'a> { None }; if self.eat_kw("type") { - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let default = if self.eat_sym("=") { Some(self.parse_type_expr()?) } else { None }; let span = self.span_from(start); meta.trailing = self.take_trailing(); @@ -1021,18 +1046,19 @@ impl<'a> Parser<'a> { ty: DataType::default(), is_type: true, name, + name_span, unpacked: Vec::new(), default, span, }); } let ty = self.parse_opt_data_type()?; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(ParamPort { meta, kw, ty, is_type: false, name, unpacked, default, span }) + Ok(ParamPort { meta, kw, ty, is_type: false, name, name_span, unpacked, default, span }) } /// The header port list plus the comments written before its closing `)`. @@ -1124,12 +1150,12 @@ impl<'a> Parser<'a> { } }; let ty = self.parse_opt_data_type()?; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(AnsiPort { meta, dir, net, ty, name, unpacked, default, span }) + Ok(AnsiPort { meta, dir, net, ty, name, name_span, unpacked, default, span }) } /// Parse a possibly-implicit data type. Stops before the declarator name. @@ -1214,7 +1240,7 @@ impl<'a> Parser<'a> { loop { let start = self.here(); let mut meta = self.take_meta(); - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; let init = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); @@ -1225,7 +1251,7 @@ impl<'a> Parser<'a> { // declaration, and the `;` has not been consumed yet, so nothing // written after it can be picked up here. meta.trailing = self.take_trailing(); - out.push(Declarator { meta, name, unpacked, init, span }); + out.push(Declarator { meta, name, name_span, unpacked, init, span }); if !more { break; } @@ -1296,25 +1322,26 @@ impl<'a> Parser<'a> { loop { let start = self.here(); let mut meta = self.take_meta(); - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; // Enum member ranges (`VAL[4]`) are rare; unsupported. let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); - members.push(EnumMember { meta, name, value, span }); + members.push(EnumMember { meta, name, name_span, value, span }); if !more { break; } } let dangling = self.take_dangling(); self.expect_sym("}")?; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; self.expect_sym(";")?; return Ok(Typedef { name, + name_span, unpacked, kind: TypedefKind::Enum(EnumType { base, members, dangling }), }); @@ -1341,20 +1368,21 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_sym("}")?; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; self.expect_sym(";")?; return Ok(Typedef { name, + name_span, unpacked, kind: TypedefKind::Struct(StructType { kw, packed, signing, members, dangling }), }); } let ty = self.parse_opt_data_type()?; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; self.expect_sym(";")?; - Ok(Typedef { name, unpacked, kind: TypedefKind::Alias(ty) }) + Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Alias(ty) }) } // ------------------------------------------------------------------ @@ -1429,12 +1457,14 @@ impl<'a> Parser<'a> { } fn parse_instantiation(&mut self) -> PResult { + let module_start = self.here(); let mut module = self.expect_ident()?; while self.cur().is_sym("::") { self.bump(); module.push_str("::"); module.push_str(&self.expect_ident()?); } + let module_span = self.span_from(module_start); let mut params = None; if self.cur().is_sym("#") { self.bump(); @@ -1467,7 +1497,7 @@ impl<'a> Parser<'a> { loop { let start = self.here(); let mut meta = self.take_meta(); - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let dims = self.parse_dims()?; self.expect_sym("(")?; let conns = self.parse_connections()?; @@ -1478,13 +1508,13 @@ impl<'a> Parser<'a> { if more { meta.trailing = self.take_trailing(); } - instances.push(Instance { meta, name, dims, conns, span }); + instances.push(Instance { meta, name, name_span, dims, conns, span }); if !more { break; } } self.expect_sym(";")?; - Ok(Instantiation { module, params, instances }) + Ok(Instantiation { module, module_span, params, instances }) } fn parse_connections(&mut self) -> PResult { @@ -1550,17 +1580,19 @@ impl<'a> Parser<'a> { let start = self.here(); let mut meta = self.take_meta(); if self.eat_sym(".") { + let star = self.cur().span; if self.eat_sym("*") { let span = self.span_from(start); return Ok(Connection { meta, name: "*".to_string(), + name_span: star, expr: None, close_comments: Vec::new(), span, }); } - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let mark = self.pending_trailing.len(); let paren_start = self.here(); let mut close_comments = Vec::new(); @@ -1585,7 +1617,7 @@ impl<'a> Parser<'a> { }; let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(Connection { meta, name, expr, close_comments, span }) + Ok(Connection { meta, name, name_span, expr, close_comments, span }) } else { let e = self.parse_expr_or_type()?; let span = self.span_from(start); @@ -1593,6 +1625,7 @@ impl<'a> Parser<'a> { Ok(Connection { meta, name: String::new(), + name_span: TextRange::empty(span.start), expr: Some(e), close_comments: Vec::new(), span, @@ -1625,7 +1658,8 @@ impl<'a> Parser<'a> { let start = self.here(); let mut meta = self.take_meta(); let name = - if self.cur().kind == TokenKind::Ident { Some(self.bump().text) } else { None }; + if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None }; + let (name, name_span) = split_label(name); self.expect_sym("(")?; let mut args = Vec::new(); if !self.cur().is_sym(")") { @@ -1639,7 +1673,7 @@ impl<'a> Parser<'a> { if more { meta.trailing = self.take_trailing(); } - instances.push(GateInstance { meta, name, args, span }); + instances.push(GateInstance { meta, name, name_span, args, span }); if !more { break; } @@ -1731,20 +1765,22 @@ impl<'a> Parser<'a> { let start = self.here(); if self.cur().is_kw("begin") { self.bump(); - let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; + let (label, label_span) = split_label(self.parse_label()?); let mut items = Vec::new(); while !self.at_body_end("end") { items.push(self.item_or_recover()?); } let dangling = self.take_dangling(); self.expect_closer("end")?; - let end_label = self.parse_end_label()?; + let (end_label, end_label_span) = split_label(self.parse_label()?); Ok(GenBlock { label, + label_span, is_block: true, items, dangling, end_label, + end_label_span, span: self.span_from(start), }) } else { @@ -1752,10 +1788,12 @@ impl<'a> Parser<'a> { let span = item.span; Ok(GenBlock { label: None, + label_span: None, is_block: false, items: vec![item], dangling: Vec::new(), end_label: None, + end_label_span: None, span, }) } @@ -1785,12 +1823,24 @@ impl<'a> Parser<'a> { } } }; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let has_parens = self.cur().is_sym("("); let args = self.parse_tf_ports()?; self.expect_sym(";")?; - let (stmts, dangling, end_label) = self.parse_tf_body("endfunction")?; - Ok(FunctionDecl { qualifiers, ret, name, has_parens, args, stmts, dangling, end_label }) + let (stmts, dangling, end) = self.parse_tf_body("endfunction")?; + let (end_label, end_label_span) = split_label(end); + Ok(FunctionDecl { + qualifiers, + ret, + name, + name_span, + has_parens, + args, + stmts, + dangling, + end_label, + end_label_span, + }) } fn parse_task(&mut self) -> PResult { @@ -1799,12 +1849,23 @@ impl<'a> Parser<'a> { while self.cur().is_kw("automatic") || self.cur().is_kw("static") { qualifiers.push(self.bump().text); } - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let has_parens = self.cur().is_sym("("); let args = self.parse_tf_ports()?; self.expect_sym(";")?; - let (stmts, dangling, end_label) = self.parse_tf_body("endtask")?; - Ok(TaskDecl { qualifiers, name, has_parens, args, stmts, dangling, end_label }) + let (stmts, dangling, end) = self.parse_tf_body("endtask")?; + let (end_label, end_label_span) = split_label(end); + Ok(TaskDecl { + qualifiers, + name, + name_span, + has_parens, + args, + stmts, + dangling, + end_label, + end_label_span, + }) } fn parse_tf_ports(&mut self) -> PResult> { @@ -1828,14 +1889,14 @@ impl<'a> Parser<'a> { } }; let ty = self.parse_opt_data_type()?; - let name = self.expect_ident()?; + let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); - args.push(TfArg { meta, dir, ty, name, unpacked, default, span }); + args.push(TfArg { meta, dir, ty, name, name_span, unpacked, default, span }); if !more { break; } @@ -1844,18 +1905,14 @@ impl<'a> Parser<'a> { Ok(args) } - fn parse_tf_body( - &mut self, - end_kw: &str, - ) -> PResult<(Vec, Vec, Option)> { + fn parse_tf_body(&mut self, end_kw: &str) -> PResult<(Vec, Vec, Option)> { let mut stmts = Vec::new(); while !self.at_body_end(end_kw) { stmts.push(self.stmt_or_recover()?); } let dangling = self.take_dangling(); self.expect_closer(end_kw)?; - let end_label = self.parse_end_label()?; - Ok((stmts, dangling, end_label)) + Ok((stmts, dangling, self.parse_label()?)) } // ------------------------------------------------------------------ @@ -1928,19 +1985,26 @@ impl<'a> Parser<'a> { match kw.as_str() { "begin" => { self.bump(); - let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; + let (label, label_span) = split_label(self.parse_label()?); let mut stmts = Vec::new(); while !self.at_body_end("end") { stmts.push(self.stmt_or_recover()?); } let dangling = self.take_dangling(); self.expect_closer("end")?; - let end_label = self.parse_end_label()?; - Ok(StmtKind::Block { label, stmts, dangling, end_label }) + let (end_label, end_label_span) = split_label(self.parse_label()?); + Ok(StmtKind::Block { + label, + label_span, + stmts, + dangling, + end_label, + end_label_span, + }) } "fork" => { self.bump(); - let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; + let (label, label_span) = split_label(self.parse_label()?); let mut stmts = Vec::new(); while !self.at_eof() && !self.at_join_kw() @@ -1955,8 +2019,16 @@ impl<'a> Parser<'a> { } else { self.bump().text }; - let end_label = self.parse_end_label()?; - Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label }) + let (end_label, end_label_span) = split_label(self.parse_label()?); + Ok(StmtKind::ForkJoin { + label, + label_span, + join_kw, + stmts, + dangling, + end_label, + end_label_span, + }) } "unique" | "unique0" | "priority" => { let qualifier = Some(self.bump().text); @@ -2053,9 +2125,9 @@ impl<'a> Parser<'a> { self.expect_sym("[")?; let mut vars = Vec::new(); if !self.cur().is_sym("]") { - vars.push(self.expect_ident()?); + vars.push(self.expect_name()?); while self.eat_sym(",") { - vars.push(self.expect_ident()?); + vars.push(self.expect_name()?); } } self.expect_sym("]")?; @@ -3112,8 +3184,9 @@ mod tests { let file = parse_ok("module m\n import a::*;\n import b::t, c::u;\n(input clk);\nendmodule"); let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; - let paths: Vec<&[String]> = m.imports.iter().map(|i| &i.paths[..]).collect(); - assert_eq!(paths, vec![&["a::*".to_string()][..], &["b::t".into(), "c::u".into()][..]]); + let paths: Vec> = + m.imports.iter().map(|i| i.paths.iter().map(ImportPath::text).collect()).collect(); + assert_eq!(paths, vec![vec!["a::*".to_string()], vec!["b::t".into(), "c::u".into()]]); } #[test] diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 3fc7fa4..1a1de5f 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -5,6 +5,11 @@ //! TODO.md §6 asks for. The AST-level half needs a printer that walks the tree //! emitting spans, which does not exist yet; what is testable today is that no //! source byte is unreachable from the token stream, and that node spans nest. +//! +//! Name spans are held to a stronger rule than containment: every `name_span` +//! must slice back to *exactly* the name it claims. That is the property +//! `vlog_semantic` used to re-derive by scanning source text, and it is what +//! makes a declared name addressable without the source. use vlog_parser::ast::*; use vlog_parser::span::TextRange; @@ -315,6 +320,40 @@ fn recovered_error_nodes_nest_inside_their_parent() { } } +/// A name span is pinned to its content, not just contained: it must slice +/// back to exactly the name, and nest inside the node that declares it. +fn check_name(src: &str, what: &str, name: &str, span: TextRange, parent: TextRange) { + assert_inside(src, what, span, parent); + assert_eq!(slice(src, span), name, "the {what} span does not slice back to its name"); +} + +fn check_opt_name( + src: &str, + what: &str, + name: Option<&String>, + span: Option, + parent: TextRange, +) { + match (name, span) { + (Some(n), Some(s)) => check_name(src, what, n, s, parent), + (None, None) => {} + _ => panic!("{what}: the name and its span disagree about whether there is one"), + } +} + +fn check_names(src: &str, what: &str, names: &[Name], parent: TextRange) { + for n in names { + check_name(src, what, &n.text, n.span, parent); + } +} + +fn check_import_paths(src: &str, paths: &[ImportPath], parent: TextRange) { + for p in paths { + check_name(src, "import package", &p.pkg.text, p.pkg.span, parent); + check_name(src, "imported name", &p.item.text, p.item.span, parent); + } +} + fn assert_inside(src: &str, what: &str, inner: TextRange, outer: TextRange) { assert!( outer.start <= inner.start && inner.end <= outer.end, @@ -334,9 +373,15 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { let here = item.span; match &item.kind { ItemKind::Module(m) => { + check_name(src, "module name", &m.name, m.name_span, here); + check_opt_name(src, "endmodule label", m.end_label.as_ref(), m.end_label_span, here); + for imp in &m.imports { + check_import_paths(src, &imp.paths, here); + } if let Some(params) = &m.param_ports { for p in params { assert_inside(src, "parameter port", p.span, here); + check_name(src, "parameter port name", &p.name, p.name_span, p.span); check_opt_expr(src, p.default.as_ref(), p.span); } } @@ -344,11 +389,14 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { PortList::Ansi(ports) => { for p in ports { assert_inside(src, "port", p.span, here); + check_name(src, "port name", &p.name, p.name_span, p.span); } } PortList::NonAnsi(ports) => { for p in ports { assert_inside(src, "port", p.span, here); + // A non-ANSI port *is* its name, so `span` is the range. + check_name(src, "port name", &p.name, p.span, here); } } PortList::None | PortList::Empty => {} @@ -357,7 +405,14 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { check_item(src, i, here); } } - ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => { + ItemKind::Package { name, name_span, items, end_label, end_label_span, .. } => { + check_name(src, "package name", name, *name_span, here); + check_opt_name(src, "endpackage label", end_label.as_ref(), *end_label_span, here); + for i in items { + check_item(src, i, here); + } + } + ItemKind::GenerateRegion { items, .. } => { for i in items { check_item(src, i, here); } @@ -366,17 +421,23 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { assert_inside(src, "raw text", raw.span, here); } ItemKind::Typedef(t) => { + check_name(src, "typedef name", &t.name, t.name_span, here); if let TypedefKind::Enum(e) = &t.kind { for member in &e.members { assert_inside(src, "enum member", member.span, here); + check_name( + src, + "enum member name", + &member.name, + member.name_span, + member.span, + ); } } if let TypedefKind::Struct(s) = &t.kind { for member in &s.members { assert_inside(src, "struct member", member.span, here); - for d in &member.declarators { - assert_inside(src, "declarator", d.span, member.span); - } + check_declarators(src, &member.declarators, member.span); } } } @@ -394,16 +455,27 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { check_stmt(src, stmt, here); } ItemKind::Instantiation(inst) => { + // A scope-qualified module name (`pkg::mod`) is stored with its + // `::` glued, so the slice matches it modulo that whitespace. + assert_inside(src, "module name", inst.module_span, here); + assert_eq!( + despace(slice(src, inst.module_span)), + despace(&inst.module), + "the instantiated module span does not slice back to its name" + ); for c in inst.params.iter().flatten() { assert_inside(src, "parameter override", c.span, here); + check_name(src, "parameter override name", &c.name, c.name_span, c.span); check_opt_expr(src, c.expr.as_ref(), c.span); } for i in &inst.instances { assert_inside(src, "instance", i.span, here); + check_name(src, "instance name", &i.name, i.name_span, i.span); match &i.conns { Connections::Named(cs) => { for c in cs { assert_inside(src, "connection", c.span, i.span); + check_name(src, "connection name", &c.name, c.name_span, c.span); check_opt_expr(src, c.expr.as_ref(), c.span); } } @@ -419,6 +491,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { ItemKind::GateInstantiation(g) => { for i in &g.instances { assert_inside(src, "gate instance", i.span, here); + check_opt_name(src, "gate instance name", i.name.as_ref(), i.name_span, i.span); for a in &i.args { assert_inside(src, "element", a.span, i.span); check_expr(src, &a.expr, i.span); @@ -438,16 +511,22 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { } } ItemKind::Function(f) => { + check_name(src, "function name", &f.name, f.name_span, here); + check_opt_name(src, "endfunction label", f.end_label.as_ref(), f.end_label_span, here); for a in &f.args { assert_inside(src, "argument", a.span, here); + check_name(src, "argument name", &a.name, a.name_span, a.span); } for s in &f.stmts { check_stmt(src, s, here); } } ItemKind::Task(t) => { + check_name(src, "task name", &t.name, t.name_span, here); + check_opt_name(src, "endtask label", t.end_label.as_ref(), t.end_label_span, here); for a in &t.args { assert_inside(src, "argument", a.span, here); + check_name(src, "argument name", &a.name, a.name_span, a.span); } for s in &t.stmts { check_stmt(src, s, here); @@ -459,7 +538,9 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { check_expr(src, rhs, here); } } - ItemKind::Import(_) | ItemKind::Timeunit(_) | ItemKind::Genvar(_) => {} + ItemKind::Import(paths) => check_import_paths(src, paths, here), + ItemKind::Genvar(names) => check_names(src, "genvar name", names, here), + ItemKind::Timeunit(_) => {} // Leaves; only error-tolerant parsing produces the last one, which // `tests/error_recovery.rs` checks the spans of. ItemKind::Error(_) => {} @@ -479,6 +560,8 @@ fn check_gen_if(src: &str, gi: &GenIf, parent: TextRange) { fn check_gen_block(src: &str, b: &GenBlock, parent: TextRange) { assert_inside(src, "generate block", b.span, parent); + check_opt_name(src, "generate block label", b.label.as_ref(), b.label_span, b.span); + check_opt_name(src, "generate end label", b.end_label.as_ref(), b.end_label_span, b.span); for i in &b.items { check_item(src, i, b.span); } @@ -487,6 +570,7 @@ fn check_gen_block(src: &str, b: &GenBlock, parent: TextRange) { fn check_declarators(src: &str, declarators: &[Declarator], parent: TextRange) { for d in declarators { assert_inside(src, "declarator", d.span, parent); + check_name(src, "declarator name", &d.name, d.name_span, d.span); check_opt_expr(src, d.init.as_ref(), d.span); for dim in &d.unpacked { assert_inside(src, "dimension", dim.span, d.span); @@ -498,7 +582,10 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { assert_inside(src, "statement", stmt.span, parent); let here = stmt.span; match &stmt.kind { - StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => { + StmtKind::Block { label, label_span, stmts, end_label, end_label_span, .. } + | StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. } => { + check_opt_name(src, "block label", label.as_ref(), *label_span, here); + check_opt_name(src, "block end label", end_label.as_ref(), *end_label_span, here); for s in stmts { check_stmt(src, s, here); } @@ -529,10 +616,15 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { check_expr(src, cond, here); check_stmt(src, body, here); } - StmtKind::Repeat { count: e, body } | StmtKind::Foreach { target: e, body, .. } => { + StmtKind::Repeat { count: e, body } => { check_expr(src, e, here); check_stmt(src, body, here); } + StmtKind::Foreach { target, vars, body } => { + check_expr(src, target, here); + check_names(src, "foreach variable", vars, here); + check_stmt(src, body, here); + } StmtKind::Forever { body } => check_stmt(src, body, here), StmtKind::Assign { lhs, rhs, .. } => { check_expr(src, lhs, here); @@ -652,3 +744,228 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { ExprKind::Ident(_) | ExprKind::Number(_) | ExprKind::Str(_) | ExprKind::Empty(_) => {} } } + +// ------------------------------------------------------------------ +// Name spans +// ------------------------------------------------------------------ + +/// One source dense enough to reach every node that carries a name span, with +/// each name asserted by hand. The walker above proves the *invariant* over +/// many sources; this proves the fields are wired to the right token, which is +/// the mistake containment cannot catch (the `GenIf` precedent). +const DENSE: &str = "\ +package pkg_a; + typedef enum logic [1:0] {RED = 0, GREEN} color_e; + typedef struct packed {logic [3:0] hi; logic lo;} pair_t; + typedef logic [7:0] byte_t; +endpackage : pkg_a + +module top import pkg_a::*, pkg_a::color_e; #( + parameter int W = 8, + parameter type T = logic +) ( + input logic clk_i, + output byte_t data_o +); + genvar gi, gj; + wire w_a, w_b = 1'b0; + sub #(.PW(W)) u_sub (.clk(clk_i), .*); + and g_and (o, a, b); + generate + if (W > 1) begin : g_wide + wire inner; + end : g_wide + endgenerate + initial begin : b_init + foreach (arr[fi, fj]) x = fi + fj; + fork : f_par + join : f_par + end : b_init + function automatic int fn_add(input int a_i, int b_i); + return a_i + b_i; + endfunction : fn_add + task tsk_go(output int r_o); + endtask : tsk_go +endmodule : top +"; + +#[test] +fn every_name_span_slices_back_to_its_name() { + let src = DENSE; + let file = parse_source(src).expect("parse error"); + + // The package, its end label, and the three typedefs in it. + let ItemKind::Package { name, name_span, items, end_label, end_label_span, .. } = + &file.items[0].kind + else { + panic!("expected a package") + }; + assert_eq!(name, "pkg_a"); + assert_eq!(slice(src, *name_span), "pkg_a"); + assert_eq!(slice(src, end_label_span.expect("an endpackage label")), "pkg_a"); + assert_eq!(end_label.as_deref(), Some("pkg_a")); + + let ItemKind::Typedef(en) = &items[0].kind else { panic!("expected the enum typedef") }; + assert_eq!(slice(src, en.name_span), "color_e"); + let TypedefKind::Enum(e) = &en.kind else { panic!("expected an enum") }; + assert_eq!(slice(src, e.members[0].name_span), "RED"); + assert_eq!(slice(src, e.members[1].name_span), "GREEN"); + + let ItemKind::Typedef(st) = &items[1].kind else { panic!("expected the struct typedef") }; + assert_eq!(slice(src, st.name_span), "pair_t"); + let TypedefKind::Struct(s) = &st.kind else { panic!("expected a struct") }; + assert_eq!(slice(src, s.members[0].declarators[0].name_span), "hi"); + assert_eq!(slice(src, s.members[1].declarators[0].name_span), "lo"); + + let ItemKind::Typedef(al) = &items[2].kind else { panic!("expected the alias typedef") }; + assert_eq!(slice(src, al.name_span), "byte_t"); + + // The module header: name, end label, imports, parameters, ports. + let ItemKind::Module(m) = &file.items[1].kind else { panic!("expected a module") }; + assert_eq!(slice(src, m.name_span), "top"); + assert_eq!(slice(src, m.end_label_span.expect("an endmodule label")), "top"); + let paths = &m.imports[0].paths; + assert_eq!(slice(src, paths[0].pkg.span), "pkg_a"); + assert_eq!(slice(src, paths[0].item.span), "*"); + assert_eq!(slice(src, paths[1].pkg.span), "pkg_a"); + assert_eq!(slice(src, paths[1].item.span), "color_e"); + + let params = m.param_ports.as_ref().expect("a parameter port list"); + assert_eq!(slice(src, params[0].name_span), "W"); + // The `parameter type T` arm is a separate construction site. + assert!(params[1].is_type); + assert_eq!(slice(src, params[1].name_span), "T"); + + let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") }; + assert_eq!(slice(src, ports[0].name_span), "clk_i"); + assert_eq!(slice(src, ports[1].name_span), "data_o"); + + // Body: genvars, declarators, instantiation, gate, generate, statements. + let ItemKind::Genvar(gs) = &m.items[0].kind else { panic!("expected genvars") }; + assert_eq!(slice(src, gs[0].span), "gi"); + assert_eq!(slice(src, gs[1].span), "gj"); + + let ItemKind::DataDecl(d) = &m.items[1].kind else { panic!("expected a wire declaration") }; + assert_eq!(slice(src, d.declarators[0].name_span), "w_a"); + assert_eq!(slice(src, d.declarators[1].name_span), "w_b"); + + let ItemKind::Instantiation(inst) = &m.items[2].kind else { panic!("expected an instance") }; + assert_eq!(slice(src, inst.module_span), "sub"); + assert_eq!(slice(src, inst.params.as_ref().expect("a parameter override")[0].name_span), "PW"); + assert_eq!(slice(src, inst.instances[0].name_span), "u_sub"); + let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") }; + assert_eq!(slice(src, conns[0].name_span), "clk"); + // `.*` has no name of its own; its span is the wildcard token. + assert_eq!(slice(src, conns[1].name_span), "*"); + + let ItemKind::GateInstantiation(g) = &m.items[3].kind else { panic!("expected a gate") }; + assert_eq!(slice(src, g.instances[0].name_span.expect("a gate name")), "g_and"); + + let ItemKind::GenerateRegion { items: gen, .. } = &m.items[4].kind else { + panic!("expected a generate region") + }; + let ItemKind::GenIf(gi) = &gen[0].kind else { panic!("expected a generate if") }; + assert_eq!(slice(src, gi.then.label_span.expect("a block label")), "g_wide"); + assert_eq!(slice(src, gi.then.end_label_span.expect("an end label")), "g_wide"); + + let ItemKind::Initial(init) = &m.items[5].kind else { panic!("expected an initial") }; + let StmtKind::Block { label_span, stmts, end_label_span, .. } = &init.kind else { + panic!("expected a block") + }; + assert_eq!(slice(src, label_span.expect("a block label")), "b_init"); + assert_eq!(slice(src, end_label_span.expect("an end label")), "b_init"); + let StmtKind::Foreach { vars, .. } = &stmts[0].kind else { panic!("expected a foreach") }; + assert_eq!(slice(src, vars[0].span), "fi"); + assert_eq!(slice(src, vars[1].span), "fj"); + let StmtKind::ForkJoin { label_span, end_label_span, .. } = &stmts[1].kind else { + panic!("expected a fork") + }; + assert_eq!(slice(src, label_span.expect("a fork label")), "f_par"); + assert_eq!(slice(src, end_label_span.expect("a join label")), "f_par"); + + let ItemKind::Function(f) = &m.items[6].kind else { panic!("expected a function") }; + assert_eq!(slice(src, f.name_span), "fn_add"); + assert_eq!(slice(src, f.end_label_span.expect("an endfunction label")), "fn_add"); + assert_eq!(slice(src, f.args[0].name_span), "a_i"); + assert_eq!(slice(src, f.args[1].name_span), "b_i"); + + let ItemKind::Task(t) = &m.items[7].kind else { panic!("expected a task") }; + assert_eq!(slice(src, t.name_span), "tsk_go"); + assert_eq!(slice(src, t.end_label_span.expect("an endtask label")), "tsk_go"); + assert_eq!(slice(src, t.args[0].name_span), "r_o"); +} + +#[test] +fn name_spans_hold_across_the_formatter_fixtures() { + // The same walker as `every_node_span_nests_inside_its_parent`, over the + // real Verilog next door: it asserts `src[name_span] == name` on every + // declaration in every fixture, which is the corpus this crate has. + let dir = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../vlog_formatter/tests/fixtures"); + let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); + let mut seen = 0; + for entry in entries { + let path = entry.expect("dir entry").path(); + if !matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("v")) { + continue; + } + let src = std::fs::read_to_string(&path).expect("read fixture"); + let Ok(file) = parse_source(&src) else { continue }; + for item in &file.items { + check_item(&src, item, file.span); + } + seen += 1; + } + assert!(seen > 0, "no fixtures found in {}", dir.display()); +} + +#[test] +fn a_multi_byte_name_gets_its_exact_byte_range() { + // Escaped identifiers run to the next whitespace, so they are the one way + // a Verilog name carries multi-byte text. Multi-byte comments before each + // name also shift every offset that follows them. + let src = "// αβγ\nmodule \\mödule✓ ;\n // ünïcode λ\n wire \\wïre✓ ;\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert_eq!(m.name, "\\mödule✓"); + assert_eq!(slice(src, m.name_span), "\\mödule✓"); + assert_eq!(m.name_span.len(), 11, "6 ASCII (\\mdule) + ö (2) + ✓ (3)"); + let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a wire") }; + assert_eq!(slice(src, d.declarators[0].name_span), "\\wïre✓"); +} + +#[test] +fn a_name_after_attributes_and_comments_is_still_pinned() { + // `(* ... *)` is code inside the item's span, and comments sit between the + // keyword and the name; neither may drag the name span along. + let src = "(* keep = \"true\" *)\nmodule /* c1 */ m /* c2 */ ;\n (* dont_touch *) wire // c3\n w;\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert_eq!(slice(src, m.name_span), "m"); + assert!( + file.items[0].span.start < m.name_span.start, + "the attribute is inside the item span and before the name" + ); + let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a wire") }; + assert_eq!(slice(src, d.declarators[0].name_span), "w"); +} + +#[test] +fn a_label_and_its_end_label_get_separate_spans() { + // Two occurrences of the same text: a span that found the first one where + // it should have found the second still slices back to the right string, + // so the two must be distinguished by position. + let src = "module m;\n initial begin : same\n x = 1;\n end : same\nendmodule : m\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let ItemKind::Initial(s) = &m.items[0].kind else { panic!("expected an initial") }; + let StmtKind::Block { label_span, end_label_span, .. } = &s.kind else { + panic!("expected a block") + }; + let open = label_span.expect("a block label"); + let close = end_label_span.expect("an end label"); + assert_eq!(slice(src, open), "same"); + assert_eq!(slice(src, close), "same"); + assert!(open.end < close.start, "the two labels are different occurrences"); + assert_eq!(open.start as usize, src.find("begin : same").expect("the begin") + 8); +} diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 9f7f4f1..c5c3335 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -198,8 +198,8 @@ impl<'a> Binder<'a> { ItemKind::Genvar(names) => { let mut scanner = NameScanner::new(self.src, item.span); for name in names { - let ns = scanner.find(name).unwrap_or(TextRange::empty(item.span.start)); - self.declare(scope, name, SymbolKind::Genvar, ns, item.span); + let ns = scanner.find(&name.text).unwrap_or(TextRange::empty(item.span.start)); + self.declare(scope, &name.text, SymbolKind::Genvar, ns, item.span); } } ItemKind::GenerateRegion { items, .. } => { @@ -249,7 +249,7 @@ impl<'a> Binder<'a> { let mut scanner = NameScanner::new(self.src, header); for import in &m.imports { for path in &import.paths { - self.bind_import_path(path, &mut scanner, inner); + self.bind_import_path(&path.text(), &mut scanner, inner); } } for p in m.param_ports.iter().flatten() { @@ -280,10 +280,10 @@ impl<'a> Binder<'a> { self.bind_items(&m.items, inner); } - fn bind_imports(&mut self, paths: &[String], span: TextRange, scope: ScopeId) { + fn bind_imports(&mut self, paths: &[ImportPath], span: TextRange, scope: ScopeId) { let mut scanner = NameScanner::new(self.src, span); for path in paths { - self.bind_import_path(path, &mut scanner, scope); + self.bind_import_path(&path.text(), &mut scanner, scope); } } @@ -614,8 +614,8 @@ impl<'a> Binder<'a> { let mut scanner = NameScanner::new(self.src, TextRange::new(target.span.end, stmt.span.end)); for v in vars { - let ns = scanner.find(v).unwrap_or(TextRange::empty(target.span.end)); - self.declare(inner, v, SymbolKind::Var, ns, ns); + let ns = scanner.find(&v.text).unwrap_or(TextRange::empty(target.span.end)); + self.declare(inner, &v.text, SymbolKind::Var, ns, ns); } self.bind_stmt(body, inner); } diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index 8116188..7be0de7 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -5,9 +5,11 @@ //! it takes the AST `vlog_parser` produced for **one** file and answers the //! questions a language server asks — what is declared here, what does this //! identifier name, where else is it used, what is the outline of this file. -//! It resolves nothing across files; a name that only another file can supply -//! is reported as [`Resolution::ExternalCandidate`] for the workspace index -//! (TODO.md §6) to finish. +//! [`analyze`] itself resolves nothing across files; a name that only another +//! file can supply is reported as [`Resolution::ExternalCandidate`]. The +//! second layer, [`WorkspaceIndex`] + [`resolve_external`], scans the whole +//! workspace and finishes those references in an overlay beside the +//! single-file tables — see `docs/features/workspace-index/README.md`. //! //! [`analyze`] never fails and never panics: an error-tolerant parse's //! `Error` nodes are opaque leaves, exactly like macro invocations. @@ -18,10 +20,15 @@ mod bind; mod model; mod resolve; mod scan; +mod workspace; pub use model::{ - DocumentSymbol, Import, Reference, Resolution, Scope, ScopeId, ScopeKind, Symbol, SymbolId, - SymbolKind, + DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol, + SymbolId, SymbolKind, +}; +pub use workspace::{ + resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId, IndexCounts, + WorkspaceIndex, WorkspaceSymbol, }; use std::collections::HashMap; @@ -123,6 +130,20 @@ impl Semantics { self.references.iter().find(|r| r.name_span.contains(offset)) } + /// The id of the use whose name covers `offset` — the key the workspace + /// index's overlay uses. + pub fn reference_id_at(&self, offset: u32) -> Option { + self.references + .iter() + .position(|r| r.name_span.contains(offset)) + .map(|i| ReferenceId(i as u32)) + } + + /// One use by id. + pub fn reference(&self, id: ReferenceId) -> Option<&Reference> { + self.references.get(id.0 as usize) + } + /// Go-to-definition: the declaration named at `offset`, whether the /// cursor sits on a use or on the declaration itself. pub fn definition_of(&self, offset: u32) -> Option<&Symbol> { diff --git a/crates/vlog_semantic/src/model.rs b/crates/vlog_semantic/src/model.rs index 264644c..e2e75d9 100644 --- a/crates/vlog_semantic/src/model.rs +++ b/crates/vlog_semantic/src/model.rs @@ -11,6 +11,12 @@ pub struct ScopeId(pub u32); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct SymbolId(pub u32); +/// Index of a [`Reference`] in +/// [`Semantics::references`](crate::Semantics::references). The workspace +/// index keys its overlay by this. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ReferenceId(pub u32); + /// What kind of declaration a [`Symbol`] came from. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SymbolKind { diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs new file mode 100644 index 0000000..788b986 --- /dev/null +++ b/crates/vlog_semantic/src/workspace.rs @@ -0,0 +1,430 @@ +//! The workspace index: the second layer of name resolution, the one that +//! finishes what [`analyze`](crate::analyze) deliberately leaves open. +//! +//! `analyze` is single-file by design, so a name only another file can supply +//! comes back as [`Resolution::ExternalCandidate`] carrying the import paths +//! that could finish it. [`WorkspaceIndex`] scans every file in the workspace +//! once and records what each one *declares*; [`resolve_external`] walks one +//! file's external candidates against that index and produces an **overlay** +//! keyed by reference id. The overlay is a separate value: `Semantics` is +//! never mutated, so a file's analysis stays valid when the workspace around +//! it changes, and a server can recompute either layer alone. +//! +//! See `docs/features/workspace-index/README.md` for the resolution order, +//! the duplicate-name policy and the corpus numbers. + +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; + +use vlog_parser::defines::{collect_defines, Define, DefineTable}; +use vlog_parser::span::TextRange; +use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize}; + +use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind}; +use crate::{analyze, Semantics}; + +/// Index of a file in a [`WorkspaceIndex`], assigned in sorted path order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct FileId(pub u32); + +/// A declaration the index can point an editor at. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Def { + /// The file the declaration is written in. + pub file: FileId, + /// Byte range of the declared name inside that file. + pub name_span: TextRange, + /// What kind of declaration it is, for an icon and for hover text. + pub kind: SymbolKind, +} + +/// One hit of [`WorkspaceIndex::workspace_symbols`]. +#[derive(Debug, Clone)] +pub struct WorkspaceSymbol<'a> { + /// The declared name, as written. + pub name: &'a str, + /// The unit the name is declared in, for a package/module member. + pub container: Option<&'a str>, + /// Where it is declared. + pub def: &'a Def, +} + +/// What every file in the workspace declares: the units other files can name, +/// their exported members, and their `` `define`` tables. +#[derive(Debug, Clone, Default)] +pub struct WorkspaceIndex { + /// Indexed by [`FileId`], sorted by path. + files: Vec, + /// File-scope name → every declaration of it, in disambiguation order. + units: BTreeMap>, + /// Unit name → member name → every declaration of it. + members: BTreeMap>>, + /// Indexed by [`FileId`], parallel to `files`. + defines: Vec, +} + +impl WorkspaceIndex { + /// Scan a whole workspace. The caller does the I/O and hands over + /// `(path, source)` pairs; tokenizing and parsing happen here, with + /// `parse_source_tolerant`, so a file that does not parse still + /// contributes every declaration that *did* parse. + /// + /// Pure: the same inputs always give the same index, whatever order they + /// arrive in. Re-scanning a changed workspace means calling this again — + /// there is no incremental update (TODO.md §6 defers that to salsa). + pub fn build<'a>(files: impl IntoIterator) -> WorkspaceIndex { + let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect(); + sources.sort_by(|a, b| a.0.cmp(&b.0)); + // A path handed over twice is one file; the first copy wins. + sources.dedup_by(|a, b| a.0 == b.0); + + let mut index = WorkspaceIndex::default(); + for (path, src) in sources { + let file = FileId(index.files.len() as u32); + index.files.push(path); + let (tree, defines) = parse_and_collect(src); + index.defines.push(defines); + index.add_file(file, &analyze(&tree, src)); + } + index + } + + /// Every file the index covers, by [`FileId`]. + pub fn files(&self) -> &[PathBuf] { + &self.files + } + + /// The path of one file. + pub fn path(&self, file: FileId) -> Option<&Path> { + self.files.get(file.0 as usize).map(PathBuf::as_path) + } + + /// Every file-scope declaration of `name` — module, package or typedef — + /// in disambiguation order (by file path, then by position in the file). + /// More than one means the workspace really does declare the name twice. + pub fn units(&self, name: &str) -> &[Def] { + self.units.get(name).map_or(&[], Vec::as_slice) + } + + /// Every declaration of `member` exported by `unit`. This is what makes + /// `p::x` and `import p::*` reach into another file, and what makes a + /// `.port` connection reach into the instantiated module. + pub fn member(&self, unit: &str, member: &str) -> &[Def] { + self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice) + } + + /// Every exported member of `unit`, sorted by name — the completion list + /// behind `p::` and behind an instantiation's connection list. + pub fn members_of(&self, unit: &str) -> impl Iterator { + self.members + .get(unit) + .into_iter() + .flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice()))) + } + + /// The `` `define`` table of one file. + pub fn defines(&self, file: FileId) -> Option<&DefineTable> { + self.defines.get(file.0 as usize) + } + + /// Every definition of a macro name anywhere in the workspace, in file + /// order. **No resolution order is implied**: which one a given use sees + /// depends on the `` `include`` graph and on `` `ifdef``, neither of which + /// this index models. A hover showing all of them is honest; picking one + /// silently would not be. + pub fn find_define(&self, name: &str) -> Vec<(FileId, &Define)> { + let mut out = Vec::new(); + for (i, table) in self.defines.iter().enumerate() { + let file = FileId(i as u32); + out.extend(table.all(name).into_iter().map(|d| (file, d))); + } + out + } + + /// Every indexed name containing `query`, case-insensitively — LSP's + /// `workspace/symbol`. An empty query matches everything; the result is + /// sorted by name and is not truncated, so a caller with a result limit + /// applies its own. + pub fn workspace_symbols(&self, query: &str) -> Vec> { + let mut out = Vec::new(); + for (name, defs) in &self.units { + if contains_ignore_ascii_case(name, query) { + out.extend(defs.iter().map(|def| WorkspaceSymbol { name, container: None, def })); + } + } + for (unit, members) in &self.members { + for (name, defs) in members { + if contains_ignore_ascii_case(name, query) { + out.extend(defs.iter().map(|def| WorkspaceSymbol { + name, + container: Some(unit), + def, + })); + } + } + } + out.sort_by(|a, b| { + (a.name, a.container, a.def.file, a.def.name_span.start).cmp(&( + b.name, + b.container, + b.def.file, + b.def.name_span.start, + )) + }); + out + } + + /// How many unit names and member names are indexed. + pub fn counts(&self) -> IndexCounts { + IndexCounts { + files: self.files.len(), + modules: self.units_of_kind(SymbolKind::Module), + packages: self.units_of_kind(SymbolKind::Package), + typedefs: self.units_of_kind(SymbolKind::Typedef), + members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(), + defines: self.defines.iter().map(|t| t.entries().len()).sum(), + } + } + + fn units_of_kind(&self, kind: SymbolKind) -> usize { + self.units.values().flatten().filter(|d| d.kind == kind).count() + } + + /// Record what one analyzed file declares. + fn add_file(&mut self, file: FileId, sem: &Semantics) { + let Some(file_scope) = sem.scope(sem.file_scope()) else { + return; + }; + for &id in &file_scope.symbols { + let Some(unit) = sem.symbol(id) else { + continue; + }; + if !is_unit(unit.kind) || unit.name_span.is_empty() { + continue; + } + self.units.entry(unit.name.clone()).or_default().push(Def { + file, + name_span: unit.name_span, + kind: unit.kind, + }); + self.add_members(file, sem, unit); + } + } + + /// Record the names another file may reach *into* this unit for. + fn add_members(&mut self, file: FileId, sem: &Semantics, unit: &Symbol) { + let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else { + return; + }; + for &id in &scope.symbols { + let Some(member) = sem.symbol(id) else { + continue; + }; + if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() { + continue; + } + self.members + .entry(unit.name.clone()) + .or_default() + .entry(member.name.clone()) + .or_default() + .push(Def { file, name_span: member.name_span, kind: member.kind }); + } + } +} + +/// The headline numbers of a built index. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct IndexCounts { + /// Files scanned, whether they parsed or not. + pub files: usize, + /// Module declarations indexed, duplicates counted separately. + pub modules: usize, + /// Package declarations indexed, duplicates counted separately. + pub packages: usize, + /// File-scope typedefs; a typedef inside a module or package is not one. + pub typedefs: usize, + /// Package and module member declarations, duplicates counted separately. + pub members: usize, + /// `` `define``/`` `undef`` directives recorded across all files. + pub defines: usize, +} + +/// Parse one file and read its `` `define`` table off the same token stream. +fn parse_and_collect(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable) { + match tokenize(src) { + Ok(tokens) => { + let defines = collect_defines(&tokens); + (parse_tolerant(tokens, src).0, defines) + } + // The lexer is all-or-nothing, so a file that does not lex contributes + // no declarations at all — but it still gets a file id, and + // `parse_source_tolerant` gives back the same one-error-node tree + // every other consumer sees. + Err(_) => (parse_source_tolerant(src).0, DefineTable::default()), + } +} + +/// The file-scope kinds another file can name. +fn is_unit(kind: SymbolKind) -> bool { + matches!(kind, SymbolKind::Module | SymbolKind::Package | SymbolKind::Typedef) +} + +/// What `unit::member` / `.member` may reach. A package exports everything +/// declared at its top level; a module exports only what a connection list can +/// name — its ports and its parameters — so an internal net is never reachable +/// from another file. +fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool { + match unit { + SymbolKind::Package => matches!( + member, + SymbolKind::Param + | SymbolKind::Typedef + | SymbolKind::EnumVariant + | SymbolKind::Function + | SymbolKind::Task + | SymbolKind::Net + | SymbolKind::Var + ), + SymbolKind::Module => matches!(member, SymbolKind::Port | SymbolKind::Param), + _ => false, + } +} + +fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool { + if needle.is_empty() { + return true; + } + let needle = needle.as_bytes(); + haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle)) +} + +// ---------------------------------------------------------------------- +// The overlay +// ---------------------------------------------------------------------- + +/// What the workspace layer made of one external-candidate reference. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ExternalTarget { + /// Exactly one workspace declaration answers it. + Resolved(Def), + /// Several files declare the name; they are listed in disambiguation + /// order (by file path), so a caller that must pick one picks the first. + Ambiguous(Vec), + /// Nothing in the workspace declares it — the package or module lives + /// outside the indexed files. + StillUnresolved, +} + +impl ExternalTarget { + /// Every declaration this reference could name, in disambiguation order. + pub fn defs(&self) -> &[Def] { + match self { + ExternalTarget::Resolved(def) => std::slice::from_ref(def), + ExternalTarget::Ambiguous(defs) => defs, + ExternalTarget::StillUnresolved => &[], + } + } + + /// The declaration to jump to: the only one, or the first of several. + pub fn best(&self) -> Option<&Def> { + self.defs().first() + } +} + +/// The workspace layer's answers for one file, keyed by reference id. +/// +/// Kept beside the file's [`Semantics`] rather than folded into it: a +/// `Semantics` describes one file and stays true while the workspace churns, +/// and an overlay is cheap to throw away and rebuild when it does. +#[derive(Debug, Clone, Default)] +pub struct ExternalResolutions { + targets: HashMap, +} + +/// Where a definition lives, once both layers have had their say. +#[derive(Debug, Clone)] +pub enum Definition<'a> { + /// Declared in the file the [`Semantics`] came from. + Local(&'a Symbol), + /// Declared in other workspace files, in disambiguation order. + External(&'a [Def]), +} + +/// Finish one file's external candidates against the workspace index. +/// +/// `sem` is not modified: the answers come back as an overlay the caller +/// composes with it (see [`ExternalResolutions::definition_of`]). +pub fn resolve_external(sem: &Semantics, index: &WorkspaceIndex) -> ExternalResolutions { + let mut targets = HashMap::new(); + for (i, reference) in sem.references().iter().enumerate() { + let Resolution::ExternalCandidate { paths } = &reference.resolution else { + continue; + }; + targets.insert(ReferenceId(i as u32), follow_paths(index, &reference.name, paths)); + } + ExternalResolutions { targets } +} + +/// Try the recorded paths in the order `analyze` wrote them — which is the +/// order the imports are written in — and take the first that has an answer. +fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> ExternalTarget { + for path in paths { + match follow_one(index, name, path) { + [] => continue, + [def] => return ExternalTarget::Resolved(def.clone()), + defs => return ExternalTarget::Ambiguous(defs.to_vec()), + } + } + ExternalTarget::StillUnresolved +} + +/// One recorded path against the index. `p::*` and `p::x` both mean "the name +/// this use spells, inside `p`". A bare path is the unit itself when the use +/// spells the unit's name (an instantiated module, an imported package), and +/// otherwise a member of it (the `.port` of a connection to that module). +fn follow_one<'i>(index: &'i WorkspaceIndex, name: &str, path: &str) -> &'i [Def] { + match path.split_once("::") { + Some((unit, _)) => index.member(unit, name), + None if path == name => index.units(name), + None => index.member(path, name), + } +} + +impl ExternalResolutions { + /// The answer for one reference, or `None` if it was not an external + /// candidate. + pub fn get(&self, id: ReferenceId) -> Option<&ExternalTarget> { + self.targets.get(&id) + } + + /// Every answer, in reference order. + pub fn iter(&self) -> impl Iterator { + let mut ids: Vec = self.targets.keys().copied().collect(); + ids.sort(); + ids.into_iter().filter_map(|id| self.targets.get(&id).map(|t| (id, t))) + } + + /// How many external candidates the workspace answered, out of how many + /// there were. + pub fn counts(&self) -> (usize, usize) { + let answered = self.targets.values().filter(|t| !t.defs().is_empty()).count(); + (answered, self.targets.len()) + } + + /// Go-to-definition across both layers: the in-file declaration when + /// there is one, else the workspace declaration, else the declaration the + /// cursor is sitting on itself. + pub fn definition_of<'a>(&'a self, sem: &'a Semantics, offset: u32) -> Option> { + if let Some(id) = sem.reference_id_at(offset) { + if let Some(symbol) = sem.reference(id).and_then(|r| r.resolved()) { + return sem.symbol(symbol).map(Definition::Local); + } + match self.targets.get(&id).map(ExternalTarget::defs) { + Some([]) | None => {} + Some(defs) => return Some(Definition::External(defs)), + } + } + sem.symbol_at(offset).and_then(|id| sem.symbol(id)).map(Definition::Local) + } +} diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs new file mode 100644 index 0000000..aac9c5b --- /dev/null +++ b/crates/vlog_semantic/tests/workspace.rs @@ -0,0 +1,566 @@ +//! Behavior of the workspace index: cross-file definitions, duplicate names, +//! package members, and the corpus acceptance run. + +use std::path::PathBuf; +use vlog_parser::parse_source_tolerant; +use vlog_semantic::{ + analyze, resolve_external, Def, Definition, ExternalTarget, FileId, Resolution, Semantics, + SymbolKind, WorkspaceIndex, +}; + +/// Build an index from `(path, source)` literals, as a server would from disk. +fn index(files: &[(&str, &str)]) -> WorkspaceIndex { + WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s))) +} + +fn semantics(src: &str) -> Semantics { + let (file, _) = parse_source_tolerant(src); + analyze(&file, src) +} + +/// The workspace declarations go-to-definition offers for `needle` — the +/// composed query, so a local hit deliberately yields no external defs. +fn external_defs(sem: &Semantics, ws: &WorkspaceIndex, src: &str, needle: &str) -> Vec { + let offset = src.find(needle).expect("needle is in the source") as u32; + let overlay = resolve_external(sem, ws); + match overlay.definition_of(sem, offset) { + Some(Definition::External(defs)) => defs.to_vec(), + _ => Vec::new(), + } +} + +/// The name a `Def` points at, read back out of the file it names. +fn slice<'a>(ws: &WorkspaceIndex, sources: &[(&str, &'a str)], def: &Def) -> &'a str { + let path = ws.path(def.file).expect("file id is in the index"); + let src = sources + .iter() + .find(|(p, _)| std::path::Path::new(*p) == path) + .expect("indexed path came from the sources") + .1; + &src[def.name_span.as_range()] +} + +// ---------------------------------------------------------------------- +// Cross-file definitions +// ---------------------------------------------------------------------- + +#[test] +fn an_instantiation_resolves_to_the_module_in_another_file() { + let sources = [ + ("a.sv", "module top; sub u_sub (.clk_i(w)); wire w; endmodule\n"), + ("b.sv", "module sub (input clk_i); endmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[0].1); + + let defs = external_defs(&sem, &ws, sources[0].1, "sub u_sub"); + assert_eq!(defs.len(), 1); + assert_eq!(defs[0].kind, SymbolKind::Module); + assert_eq!(ws.path(defs[0].file).unwrap(), PathBuf::from("b.sv")); + assert_eq!(slice(&ws, &sources, &defs[0]), "sub"); +} + +#[test] +fn a_named_connection_resolves_to_the_port_in_the_other_file() { + let sources = [ + ("a.sv", "module top; sub u_sub (.clk_i(w)); wire w; endmodule\n"), + ("b.sv", "module sub (input clk_i); endmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[0].1); + + let defs = external_defs(&sem, &ws, sources[0].1, "clk_i(w)"); + assert_eq!(defs.len(), 1, "the port of an external module resolves"); + assert_eq!(defs[0].kind, SymbolKind::Port); + assert_eq!(slice(&ws, &sources, &defs[0]), "clk_i"); +} + +#[test] +fn an_internal_net_of_another_module_is_not_reachable() { + let sources = [ + ("a.sv", "module top; sub u (.secret(w)); wire w; endmodule\n"), + ("b.sv", "module sub (input clk_i); wire secret; endmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[0].1); + assert!(external_defs(&sem, &ws, sources[0].1, "secret(w)").is_empty()); +} + +#[test] +fn a_wildcard_import_reaches_into_the_packages_file() { + let sources = [ + ("defs.sv", "package cfg_pkg;\n localparam int WIDTH = 8;\n typedef logic [1:0] mode_e;\nendpackage\n"), + ("use.sv", "import cfg_pkg::*;\nmodule m;\n wire [WIDTH-1:0] bus;\n mode_e mode;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[1].1); + + let width = external_defs(&sem, &ws, sources[1].1, "WIDTH-1"); + assert_eq!(width.len(), 1); + assert_eq!(width[0].kind, SymbolKind::Param); + assert_eq!(slice(&ws, &sources, &width[0]), "WIDTH"); + + let mode = external_defs(&sem, &ws, sources[1].1, "mode_e mode"); + assert_eq!(mode.len(), 1); + assert_eq!(mode[0].kind, SymbolKind::Typedef); +} + +#[test] +fn an_explicit_import_reaches_only_the_name_it_names() { + let sources = [ + ("defs.sv", "package cfg_pkg;\n localparam int WIDTH = 8;\n localparam int DEPTH = 4;\nendpackage\n"), + ("use.sv", "import cfg_pkg::WIDTH;\nmodule m;\n wire [WIDTH-1:0] a;\n wire [DEPTH-1:0] b;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[1].1); + + assert_eq!(external_defs(&sem, &ws, sources[1].1, "WIDTH-1").len(), 1); + assert!( + external_defs(&sem, &ws, sources[1].1, "DEPTH-1").is_empty(), + "an explicit import does not drag the rest of the package in" + ); +} + +#[test] +fn a_package_scoped_name_resolves_across_files() { + let sources = [ + ("defs.sv", "package cfg_pkg;\n localparam int WIDTH = 8;\n function int f(); return 1; endfunction\nendpackage\n"), + ("use.sv", "module m;\n wire [cfg_pkg::WIDTH-1:0] bus;\n initial x = cfg_pkg::f();\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[1].1); + + let head = external_defs(&sem, &ws, sources[1].1, "cfg_pkg::WIDTH"); + assert_eq!(head.len(), 1, "the package head resolves to the package"); + assert_eq!(head[0].kind, SymbolKind::Package); + + let tail = external_defs(&sem, &ws, sources[1].1, "WIDTH-1"); + assert_eq!(tail.len(), 1); + assert_eq!(tail[0].kind, SymbolKind::Param); + assert_eq!(slice(&ws, &sources, &tail[0]), "WIDTH"); + + let func = external_defs(&sem, &ws, sources[1].1, "f()"); + assert_eq!(func.len(), 1); + assert_eq!(func[0].kind, SymbolKind::Function); +} + +#[test] +fn an_enum_variant_declared_in_a_package_is_a_member_of_it() { + let sources = [ + ("defs.sv", "package st_pkg;\n typedef enum logic { IDLE, BUSY } state_e;\nendpackage\n"), + ("use.sv", "import st_pkg::*;\nmodule m;\n assign s = BUSY;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[1].1); + + let defs = external_defs(&sem, &ws, sources[1].1, "BUSY;"); + assert_eq!(defs.len(), 1); + assert_eq!(defs[0].kind, SymbolKind::EnumVariant); + assert_eq!(slice(&ws, &sources, &defs[0]), "BUSY"); +} + +#[test] +fn a_name_the_workspace_does_not_declare_stays_unresolved() { + let sources = [( + "use.sv", + "import nowhere_pkg::*;\nmodule m;\n wire [W-1:0] a;\n absent_mod u ();\nendmodule\n", + )]; + let ws = index(&sources); + let sem = semantics(sources[0].1); + let overlay = resolve_external(&sem, &ws); + + assert!(external_defs(&sem, &ws, sources[0].1, "W-1").is_empty()); + assert!(external_defs(&sem, &ws, sources[0].1, "absent_mod u").is_empty()); + let (answered, total) = overlay.counts(); + assert_eq!(answered, 0); + assert!(total > 0, "the file does have external candidates"); + assert!(overlay.iter().all(|(_, t)| matches!(t, ExternalTarget::StillUnresolved))); +} + +// ---------------------------------------------------------------------- +// Duplicates and ordering +// ---------------------------------------------------------------------- + +#[test] +fn a_module_declared_in_two_files_is_ambiguous_in_path_order() { + let sources = [ + ("z_late.sv", "module dup (input a); endmodule\n"), + ("a_early.sv", "module dup (input b); endmodule\n"), + ("use.sv", "module top; dup u (); endmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[2].1); + let overlay = resolve_external(&sem, &ws); + + let offset = sources[2].1.find("dup u").unwrap() as u32; + let id = sem.reference_id_at(offset).unwrap(); + let target = overlay.get(id).unwrap(); + match target { + ExternalTarget::Ambiguous(defs) => { + assert_eq!(defs.len(), 2); + assert_eq!(ws.path(defs[0].file).unwrap(), PathBuf::from("a_early.sv")); + assert_eq!(ws.path(defs[1].file).unwrap(), PathBuf::from("z_late.sv")); + } + other => panic!("expected Ambiguous, got {other:?}"), + } + assert_eq!(target.best().unwrap().file, FileId(0), "the first path sorts first"); + // Both are still offered to the editor, and both really name `dup`. + for def in target.defs() { + assert_eq!(slice(&ws, &sources, def), "dup"); + } +} + +#[test] +fn file_ids_follow_the_sorted_paths_whatever_order_they_arrive_in() { + let forward = index(&[("a.sv", "module a; endmodule\n"), ("b.sv", "module b; endmodule\n")]); + let backward = index(&[("b.sv", "module b; endmodule\n"), ("a.sv", "module a; endmodule\n")]); + assert_eq!(forward.files(), backward.files()); + assert_eq!(forward.units("a"), backward.units("a")); + assert_eq!(forward.units("a")[0].file, FileId(0)); + assert_eq!(forward.units("b")[0].file, FileId(1)); +} + +// ---------------------------------------------------------------------- +// Robustness +// ---------------------------------------------------------------------- + +#[test] +fn a_broken_file_still_contributes_what_parsed() { + let sources = [ + ("broken.sv", "module good_mod (input clk); endmodule\n@@@ !! not verilog !!\npackage good_pkg; localparam int K = 1; endpackage\n"), + ("use.sv", "module top; good_mod u (); wire [good_pkg::K-1:0] w; endmodule\n"), + ]; + let ws = index(&sources); + let (_, diags) = parse_source_tolerant(sources[0].1); + assert!(!diags.is_empty(), "the fixture really does fail to parse"); + + assert_eq!(ws.units("good_mod").len(), 1); + let sem = semantics(sources[1].1); + let defs = external_defs(&sem, &ws, sources[1].1, "good_pkg::K"); + assert_eq!(defs.len(), 1, "declarations after the error node still index"); +} + +#[test] +fn an_empty_workspace_answers_nothing_and_panics_nowhere() { + let ws = WorkspaceIndex::build(Vec::<(PathBuf, &str)>::new()); + assert!(ws.files().is_empty()); + assert!(ws.units("anything").is_empty()); + assert!(ws.member("p", "x").is_empty()); + assert!(ws.workspace_symbols("").is_empty()); + assert!(ws.find_define("WIDTH").is_empty()); + assert!(ws.path(FileId(0)).is_none()); + assert!(ws.defines(FileId(7)).is_none()); + + let src = "module m; other u (); endmodule\n"; + let sem = semantics(src); + let overlay = resolve_external(&sem, &ws); + assert_eq!(overlay.counts().0, 0); + let on_the_module_name = src.find("m;").unwrap() as u32; + assert!( + overlay.definition_of(&sem, on_the_module_name).is_some(), + "the local layer still answers with no workspace at all" + ); +} + +#[test] +fn rebuilding_after_an_edit_reflects_the_edit() { + let before = index(&[("p.sv", "package p; localparam int OLD = 1; endpackage\n")]); + assert!(!before.member("p", "OLD").is_empty()); + assert!(before.member("p", "NEW").is_empty()); + + let after = index(&[("p.sv", "package p; localparam int NEW = 2; endpackage\n")]); + assert!(after.member("p", "OLD").is_empty(), "a rebuild forgets the old text"); + assert!(!after.member("p", "NEW").is_empty()); +} + +#[test] +fn the_same_path_twice_is_one_file() { + let src = "module m; endmodule\n"; + let ws = + WorkspaceIndex::build(vec![(PathBuf::from("m.sv"), src), (PathBuf::from("m.sv"), src)]); + assert_eq!(ws.files().len(), 1); + assert_eq!(ws.units("m").len(), 1); +} + +// ---------------------------------------------------------------------- +// Queries +// ---------------------------------------------------------------------- + +#[test] +fn definition_of_prefers_the_in_file_declaration() { + let sources = [ + ("far.sv", "module sub (input clk_i); endmodule\n"), + ("near.sv", "module sub (input clk_i); endmodule\nmodule top; sub u (); endmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[1].1); + let overlay = resolve_external(&sem, &ws); + + let offset = sources[1].1.find("sub u").unwrap() as u32; + match overlay.definition_of(&sem, offset) { + Some(Definition::Local(sym)) => { + assert_eq!(sym.name, "sub"); + assert_eq!(sym.kind, SymbolKind::Module); + } + other => panic!("expected the local declaration, got {other:?}"), + } + assert!( + resolve_external(&sem, &ws).get(sem.reference_id_at(offset).unwrap()).is_none(), + "a locally resolved reference is not in the overlay at all" + ); +} + +#[test] +fn workspace_symbols_matches_names_case_insensitively() { + let ws = index(&[ + ("a.sv", "module prim_fifo_sync (input clk_i); endmodule\n"), + ("b.sv", "package prim_pkg; localparam int FifoDepth = 4; endpackage\n"), + ]); + + let hits = ws.workspace_symbols("fifo"); + let names: Vec<_> = hits.iter().map(|h| (h.name, h.container)).collect(); + assert!(names.contains(&("prim_fifo_sync", None))); + assert!(names.contains(&("FifoDepth", Some("prim_pkg")))); + + assert!(ws.workspace_symbols("zzz").is_empty()); + assert!(ws.workspace_symbols("").len() >= 4, "an empty query matches everything"); + // Sorted and stable. + let again = ws.workspace_symbols("fifo"); + assert_eq!(names, again.iter().map(|h| (h.name, h.container)).collect::>()); +} + +#[test] +fn members_of_lists_a_packages_exports() { + let ws = index(&[("p.sv", "package p;\n localparam int A = 1;\n typedef logic t;\n function int f(); return 1; endfunction\nendpackage\n")]); + let names: Vec<&str> = ws.members_of("p").map(|(n, _)| n).collect(); + assert_eq!(names, vec!["A", "f", "t"], "sorted by name"); + assert!(ws.members_of("nope").next().is_none()); +} + +#[test] +fn defines_are_indexed_per_file_and_findable_workspace_wide() { + let ws = index(&[ + ("defs.svh", "`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n"), + ("other.svh", "`define WIDTH 16\n"), + ]); + + let per_file = ws.defines(FileId(0)).expect("file 0 has a define table"); + assert_eq!(per_file.latest("WIDTH").map(|d| d.body.as_str()), Some("8")); + assert_eq!( + per_file.latest("MAX").and_then(|d| d.params.clone()), + Some(vec!["a".into(), "b".into()]) + ); + + // Both definitions are offered; no include graph exists to rank them. + let all = ws.find_define("WIDTH"); + assert_eq!(all.len(), 2); + assert_eq!(all[0].0, FileId(0)); + assert_eq!(all[1].0, FileId(1)); + assert!(ws.find_define("NOPE").is_empty()); +} + +#[test] +fn counts_report_what_was_indexed() { + let counts = index(&[ + ("a.sv", "module m; endmodule\ntypedef logic [7:0] byte_t;\n"), + ("b.sv", "`define D 1\npackage p; localparam int K = 1; endpackage\n"), + ]) + .counts(); + assert_eq!(counts.files, 2); + assert_eq!(counts.modules, 1); + assert_eq!(counts.packages, 1); + assert_eq!(counts.typedefs, 1); + assert_eq!(counts.members, 1); + assert_eq!(counts.defines, 1); +} + +// ---------------------------------------------------------------------- +// Corpus acceptance +// ---------------------------------------------------------------------- + +/// Build one index over the whole corpus, then re-resolve every file against +/// it. Reports the headline the feature exists for — how many of the +/// single-file layer's external candidates the workspace layer finishes — and +/// asserts the properties behind it: no panic, a deterministic index, and +/// every answer really pointing at the name it claims. +#[test] +fn the_corpus_index_finishes_most_external_references() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !root.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let mut paths = Vec::new(); + collect(&root, &mut paths); + paths.sort(); + let sources: Vec<(PathBuf, String)> = paths + .iter() + .filter_map(|p| std::fs::read_to_string(p).ok().map(|s| (p.clone(), s))) + .collect(); + assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog"); + + let start = std::time::Instant::now(); + let ws = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str()))); + let build = start.elapsed(); + let counts = ws.counts(); + println!( + "workspace index: {} files in {:.2}s — {} modules, {} packages, {} file-scope typedefs, \ + {} exported members, {} define directives", + counts.files, + build.as_secs_f64(), + counts.modules, + counts.packages, + counts.typedefs, + counts.members, + counts.defines, + ); + + // Deterministic: the same sources build the same index, every time. + let again = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str()))); + assert_eq!(ws.files(), again.files(), "file ids must not depend on the run"); + assert_eq!(counts, again.counts()); + let fingerprint = |w: &WorkspaceIndex| -> Vec<(String, Option, u32, u32)> { + w.workspace_symbols("") + .iter() + .map(|s| { + ( + s.name.to_string(), + s.container.map(str::to_string), + s.def.file.0, + s.def.name_span.start, + ) + }) + .collect() + }; + assert_eq!(fingerprint(&ws), fingerprint(&again), "the index is not deterministic"); + + let mut all = Tally::default(); + let mut clean = Tally::default(); + for (path, src) in &sources { + let (tree, diags) = parse_source_tolerant(src); + let sem = analyze(&tree, src); + let overlay = resolve_external(&sem, &ws); + let mut file_tally = Tally { references: sem.references().len(), ..Tally::default() }; + for (id, target) in overlay.iter() { + let reference = sem.reference(id).expect("id came from the overlay"); + let name = &reference.name; + file_tally.count(target, reference); + // Every answer must really be the name the use spells. + for def in target.defs() { + let target_path = ws.path(def.file).expect("def names an indexed file"); + let target_src = &sources + .iter() + .find(|(p, _)| p == target_path) + .expect("indexed path came from the sources") + .1; + assert_eq!( + &target_src[def.name_span.as_range()], + name, + "{}: workspace answer for {name} points at other bytes in {}", + path.display(), + target_path.display(), + ); + } + } + all.merge(&file_tally); + if diags.is_empty() { + clean.merge(&file_tally); + } + } + + all.report("corpus (every file)"); + clean.report("corpus (files that parse cleanly)"); + + assert!(build.as_secs_f64() < 5.0, "index build took {:.2}s", build.as_secs_f64()); + assert!( + 2 * clean.answered() > clean.total, + "the workspace should finish most external candidates: {} of {}", + clean.answered(), + clean.total + ); +} + +#[derive(Default)] +struct Tally { + /// Every reference the single-file layer recorded, external or not — the + /// denominator the vlog-semantic baseline reports percentages against. + references: usize, + total: usize, + resolved: usize, + ambiguous: usize, + unresolved: usize, + /// Unresolved import path → how many uses it left open, and one example + /// name each: the honest-gaps report. + misses: std::collections::BTreeMap, +} + +impl Tally { + fn count(&mut self, target: &ExternalTarget, reference: &vlog_semantic::Reference) { + self.total += 1; + match target { + ExternalTarget::Resolved(_) => self.resolved += 1, + ExternalTarget::Ambiguous(_) => self.ambiguous += 1, + ExternalTarget::StillUnresolved => { + self.unresolved += 1; + let paths = match &reference.resolution { + Resolution::ExternalCandidate { paths } => paths.join(" | "), + _ => String::new(), + }; + let entry = self.misses.entry(paths).or_insert((0, reference.name.clone())); + entry.0 += 1; + } + } + } + + fn merge(&mut self, other: &Tally) { + self.references += other.references; + self.total += other.total; + self.resolved += other.resolved; + self.ambiguous += other.ambiguous; + self.unresolved += other.unresolved; + for (path, (n, example)) in &other.misses { + let entry = self.misses.entry(path.clone()).or_insert((0, example.clone())); + entry.0 += n; + } + } + + fn answered(&self) -> usize { + self.resolved + self.ambiguous + } + + fn report(&self, label: &str) { + let pct = |n: usize, of: usize| 100.0 * n as f64 / of.max(1) as f64; + println!( + "{label}: {} references, {} external candidates ({:.1}%) — the workspace answers \ + {:.1}% of them ({:.1}% one target, {:.1}% ambiguous), {:.1}% still unresolved. \ + External-candidate rate after the workspace layer: {:.1}% of all references.", + self.references, + self.total, + pct(self.total, self.references), + pct(self.answered(), self.total), + pct(self.resolved, self.total), + pct(self.ambiguous, self.total), + pct(self.unresolved, self.total), + pct(self.unresolved, self.references), + ); + let mut top: Vec<(&String, &(usize, String))> = self.misses.iter().collect(); + top.sort_by(|a, b| b.1 .0.cmp(&a.1 .0).then(a.0.cmp(b.0))); + for (path, (n, example)) in top.iter().take(5) { + println!(" still unresolved: {path} — {n} uses (e.g. {example})"); + } + } +} + +fn collect(dir: &std::path::Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + collect(&path, out); + } else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) { + out.push(path); + } + } +} diff --git a/docs/features/name-spans/README.md b/docs/features/name-spans/README.md new file mode 100644 index 0000000..b784055 --- /dev/null +++ b/docs/features/name-spans/README.md @@ -0,0 +1,495 @@ +# name-spans + +## Goal + +The parser sits on the token that spells a declared name at the moment it +reads it, so recording that token's byte range costs one expression per site. +Before this feature it threw the range away: ~15 AST node kinds kept a +declared name as a bare `String` inside a construct-wide span, which forced +`crates/vlog_semantic/src/scan.rs` — ~150 lines of comment/string/macro-aware +source scanning — to *re-find* every name in the source text. That scan is +right in practice (95 193 spans verified against the corpus) but cannot be +right by construction: it is a search for a string inside a window, and any +node whose name is a substring of a neighbour, or is written twice inside its +own span, is a bug waiting for the right file. This feature moves the fact to +where it is known. `Symbol.name_span` is what `textDocument/definition`, +`documentSymbol`, `references` and hover all point at, so it is on the +critical path of every LSP feature in TODO.md §6. + +Nothing else changes: the formatter never reads the new fields, its output is +byte-identical, and the corpus TSV md5 is unmoved. + +## The convention + +> **A declared name keeps its `String` and gains a sibling `TextRange` field +> that is the exact byte range of the identifier spelling it, so +> `src[name_span] == name`. Where a node holds a *list* of names, the pair is +> bundled into `Name { text, span }` instead.** + +Sibling fields are named after the name they range over: `name_span` for the +declared name, `label_span` / `end_label_span` for `begin : l` … `end : l`, +`module_span` for the module an `Instantiation` names. An optional name gets +an `Option`, and the two are always `Some`/`None` together (the +walker test asserts this rather than trusting it). + +### Why siblings and not a `Name` newtype everywhere + +A `Name { text, span }` replacing every `name: String` was the other candidate +and reads better in the abstract. It was rejected on churn and on risk: + +- **Read sites, not construction sites, dominate.** `format.rs` reads a + declared name in ~35 places — `text(p.name.clone())`, `names.join(", ")`, + `format!(".{}(", c.name)`, `closing(&str, &Option)`. Every one would + need either an edit or a `Deref`/`Display`/`PartialEq` impl to paper + over, and the ones needing an edit (`clone()` returning the wrong type, + `join` on a `Vec`, the `Option` helper signature) would not + all be caught by inference — they would be rewritten by hand, in the one + file this round is required to leave behaviorally untouched. +- **Sibling fields are pure additions.** A new field on a struct breaks only + struct-literal construction, which lives entirely in `parser.rs`. The + formatter and `vlog_semantic` compiled unchanged against every one of the 24 + sibling-field additions; only the four list-shaped changes needed an edit + anywhere else. "Zero behavior change" is then a claim about a diff that + barely touches the printer, which is checkable rather than argued. +- The cost is a two-field invariant (`name` and `name_span` must agree), which + is exactly what the walker test asserts on every node of every source it + parses — including the error-recovery trees. + +### Why lists are the exception + +`ItemKind::Genvar`, `StmtKind::Foreach::vars` and the two import-path lists +hold *n* names, so the sibling shape would be a parallel `Vec` that +nothing keeps in step: a `push` to one and not the other compiles, and the +lengths only disagree at runtime. `Vec` makes that unrepresentable. This +is one rule with one stated exception, not two conventions — the exception is +where the sibling shape stops being sound, not where it stops being +convenient. + +`import p::x` needed a shape either way: the path used to be stored +pre-joined as `"p::x"`, and `vlog_semantic` resolves the two halves against +different scopes, so a single span over the whole path would not have answered +the question. `ImportPath { pkg: Name, item: Name }` carries both, with +`ImportPath::text()` rebuilding the `"p::x"` spelling the formatter prints. A +wildcard is `item.text == "*"` with the `*` token's span. + +## Fields added + +28 in all. Sibling `TextRange` unless noted. + +| node | field(s) | +|---|---| +| `Module` | `name_span`, `end_label_span` | +| `ItemKind::Package` | `name_span`, `end_label_span` | +| `ItemKind::Import` | payload is now `Vec` (2 spans per path) | +| `HeaderImport` | `paths` is now `Vec` | +| `ItemKind::Genvar` | payload is now `Vec` | +| `Typedef` | `name_span` | +| `EnumMember` | `name_span` | +| `Declarator` | `name_span` | +| `AnsiPort` | `name_span` | +| `ParamPort` | `name_span` | +| `TfArg` | `name_span` | +| `Instantiation` | `module_span` | +| `Instance` | `name_span` | +| `Connection` | `name_span` | +| `GateInstance` | `name_span: Option` | +| `GenBlock` | `label_span`, `end_label_span` | +| `FunctionDecl` | `name_span`, `end_label_span` | +| `TaskDecl` | `name_span`, `end_label_span` | +| `StmtKind::Block` | `label_span`, `end_label_span` | +| `StmtKind::ForkJoin` | `label_span`, `end_label_span` | +| `StmtKind::Foreach` | `vars` is now `Vec` | + +Deliberately **not** added: + +- **`NonAnsiPort`** — its `span` already *is* the name's range (`module m (a, + b);` writes nothing else), so a `name_span` would store the same fact twice. + Documented on the struct. The walker test checks `src[span] == name` there + too, so the equality is asserted rather than assumed. +- **`ExprKind::Member::name` / `ExprKind::Scope::name`** (handshake item 3). + The name is the construct's *last* token, so its range is exactly + `span.end - name.len() .. span.end` — derivable, and `bind.rs` already + derives it without calling `scan.rs`. Same reasoning as the spans feature's + "payload structs whose extent equals their wrapper's". +- **`DataType`** (handshake item 2). A type name is a *use*, not a + declaration, and an implicit type has no tokens at all, so the honest fix is + an `Option` on `DataType` — a separate decision, already recorded + as an open gap in `docs/features/spans/README.md`. +- **`StmtKind::Disable`** — a use, not a declaration. + +## Assumptions + +- **A declared name is one token.** True for every name in the list above: + `expect_name` reads a single `Ident`, and its span is that token's. The one + multi-token exception is called out below. +- **`Instantiation.module` may be scope-qualified.** `pkg::mod` is parsed as + three tokens and stored with the `::` glued (`"pkg::mod"`), so + `src[module_span]` equals `module` *modulo the whitespace a source may write + around the `::`*. This is the same class of divergence the lexer's + sized-literal normalization already has (`8 'h FF` → `8'hFF`, spans README): + the span is the real extent and the text is normalized. The walker asserts + the despaced equality for this one field and exact equality everywhere else. + Everything else in the tree that can be scope-qualified is a use, not a + declaration. +- **Escaped identifiers are ordinary names.** The lexer reads `\a+b ` as one + `Ident`, so its span is exact and may cover multi-byte text; nothing here + inspects the bytes. +- **The formatter still prints from the `String`.** The new fields are write- + only as far as `vlog_formatter` is concerned, which is what makes "no + behavior change" a property of the diff rather than a test result. +- **Spans are only meaningful for the exact text they were lexed from**, as + for every other span (spans README). + +## Handshakes + +**Consumed from `vlog_parser` itself:** `Parser::here()` and the token stream. +Two new private helpers do all the work — `expect_name() -> PResult` +(the identifier at the cursor plus its range; `expect_ident` now delegates to +it) and `parse_label() -> PResult>` (an optional `: name` after +`begin`/`fork` or after a closing keyword; it replaces `parse_end_label` and +now serves both the opening and the closing label, which used to be parsed by +two different snippets). + +**Promised to `vlog_semantic`** (and to the workspace index, and to +`vfmt_server` when it exists): + +- Every field in the table above is the exact byte range of the name as + written: `src[name_span] == name`, with the one documented + `Instantiation.module_span` whitespace caveat. +- Each range nests inside the span of the node that declares the name (the + spans-feature nesting invariant is unchanged and now covers these too). +- `Option` name and `Option` span are always `Some`/`None` together. +- These hold on error-tolerant trees as well: the ranges come from real + tokens, so a recovered file's names are placed exactly like a clean file's. + +> **`scan.rs` deletion unblocked; `vlog_semantic` should switch to these +> fields in its next round.** Every `scan.rs` consumer in `bind.rs` now has a +> parser-supplied span to read instead: `name_after_kw` (module/package), +> `NameScanner` (genvar, imports, foreach vars, typedef name), and +> `name_span(...)` (declarators, enum members, instances, module names, +> connections, gate instances, block labels). What is *not* covered is +> `bind_data_type`'s type-name window — that needs handshake item 2 +> (`DataType` span), which this round deliberately did not do. So `scan.rs` +> shrinks to the type-name case now and disappears when item 2 lands. + +**Promised to `vlog_formatter`:** nothing new. It ignores every field added +here; see the three compile-fixes below, all of which rebuild a string the +parser used to store pre-joined. + +**Recursion/chain budgets** (`docs/features/recursion-limit/README.md`): no +new budget, none needed. `TextRange` is a `Copy` pair of `u32`s stored inside +existing nodes; `Name` and `ImportPath` are leaves with no children. No new +recursion, no new `Box`, no added root-to-leaf depth. + +## Compile-fixes outside `vlog_parser` + +Both crates are outside this feature's scope, so each edit is listed: + +**`crates/vlog_formatter/src/format.rs`** — 8 lines, all forced by a payload +type change, none behavioral: + +1. `ItemKind::Package { .. }` and four `StmtKind::Block`/`ForkJoin` patterns + gain `..` for the new fields (5 lines). +2. `ItemKind::Import(paths)` and the header-import line: `paths.join(", ")` → + `join_paths(paths)` (2 lines). +3. `ItemKind::Genvar(names)` and `StmtKind::Foreach`'s `vars.join(", ")` → + `join_names(names)` (2 lines). + +The two new private helpers `join_names` / `join_paths` produce exactly the +strings the old `Vec` held (`ImportPath::text()` is the same +`format!("{pkg}::{sym}")` the parser used to store), which is why the corpus +TSV is byte-identical. + +**`crates/vlog_semantic/src/bind.rs`** — 7 lines, mechanical, no logic +touched. `NameScanner` is still used exactly as before; only the way the name +string is reached changed: + +1. `ItemKind::Genvar` arm: `name` → `&name.text` (2 lines). +2. `bind_imports` takes `&[ImportPath]`, and both its loop and the header- + import loop pass `&path.text()` (3 lines). +3. `StmtKind::Foreach` arm: `v` → `&v.text` (2 lines). + +No other `vlog_semantic` file was touched (the concurrent `workspace-index` +work owns `workspace.rs`, `lib.rs`, `model.rs`, `tests/workspace.rs`). The +crate's corpus test reports the identical numbers afterwards — 21 485 symbols, +73 708 references, 0 names unplaced. + +## Status / TODO + +- [x] Convention chosen and justified: sibling `TextRange`, `Name` for lists. +- [x] `Name` and `ImportPath` in `ast.rs`, with the module-level doc stating + the rule. +- [x] 28 fields across 21 node kinds (table above). +- [x] `expect_name` / `parse_label` / `split_label` in `parser.rs`; 24 + `expect_name` call sites (one of them `expect_ident`'s delegation) and + 11 `split_label` call sites. +- [x] `src[name_span] == name` and nesting asserted for **every** new field in + the exhaustive walker (`every_node_span_nests_inside_its_parent`, + `recovered_error_nodes_nest_inside_their_parent`, and a new fixture + sweep). +- [x] Content-pin test on a dense source naming every field by hand. +- [x] Multi-byte names, a name behind attributes and comments, and a label + whose text repeats as its own end label. +- [x] Mutation-tested: three deliberate mis-wirings, all caught. +- [x] Formatter output unchanged: corpus TSV md5 + `aa982463f68c1a3568c02a0fc5e0c455`, byte-identical to the baseline; no + `.cases`/fixture/snapshot churn. +- [x] `cargo fmt` clean, `cargo clippy --workspace --all-targets` silent, + `cargo test --workspace` 299 passed / 0 failed. +- [ ] Not done, deliberately: `DataType` span (handshake item 2) and the + `Member`/`Scope` tails (item 3) — reasoning above. +- [ ] Left to `vlog_semantic`: switch `bind.rs` to these fields and delete the + declaration half of `scan.rs`. +- No `TODO.md` item covers this feature; nothing there was checked. + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, the `spans` and `vlog-semantic` READMEs (the latter's + Handshake request #1 and the lead's approval of it) before touching code. + Baseline: working tree clean at `7cf657a`, corpus TSV md5 + `aa982463f68c1a3568c02a0fc5e0c455`. +- **Picked the convention by counting read sites, not construction sites.** + The task framed the choice as "whichever minimizes churn at the ~28 + construction sites"; both candidates are one line each there, so the + decision actually lives in `format.rs`'s ~35 *reads*. Sibling fields make + those zero. Recorded in full above because it is the reversible-only-at-cost + decision of this round. +- **Lists forced the one exception.** Found while wiring `ItemKind::Genvar`: + a `Vec` has no sibling to hang a range off, and a parallel + `Vec` is an invariant the compiler cannot hold. `Vec` it + is, for genvars, foreach variables, and both import-path lists. +- **`import` needed a real shape, not just a span.** The path was stored + pre-joined (`format!("{pkg}::{sym}")`) and `vlog_semantic` resolves `p` and + `x` in different scopes, so one span over `"p::x"` would have answered + neither question. `ImportPath { pkg, item }` + `text()` keeps the formatter + printing the identical string. +- **`parse_end_label` became `parse_label` and now parses both ends.** The + opening label of `begin : l` was an inline `if self.eat_sym(":")` snippet + duplicated in three places with the same body as `parse_end_label`; giving + the labels spans meant editing all four anyway, so they collapsed into one + function. `split_label` turns its `Option` into the `(Option, + Option)` pair the sibling convention stores. +- **`parse_tf_body` kept returning an `Option`** rather than the split + pair: the four-element tuple tripped `clippy::type_complexity`, and the two + callers split it themselves in one line. +- **The one honest divergence is `Instantiation.module_span`.** `pkg::mod` is + three tokens stored as one glued string, so exact slice equality is false + whenever a source writes `pkg :: mod`. Rather than special-case the parser I + documented it as the same normalization class the lexer already has for + sized literals, and made the walker assert despaced equality *only* for that + field — exact everywhere else, so the weaker assertion cannot leak. +- **Mutation-tested the new assertions before believing the green run**, since + the whole feature is one property: + 1. `expect_name` recording the *next* token's span instead of the current + one → 3 tests fail (the multi-byte, attribute and label tests). + 2. `Connection.name_span` set to the whole connection's span → 3 fail + (dense, fixtures, walker). + 3. `Instantiation.module_span` collapsed to an empty range → 3 fail. + Reverted all three; `git diff` verified byte-identical before and after. +- Did not touch `verify.rs` or `tests/verification.rs`: no normalization was + added, broadened or weakened, so CLAUDE.md invariant #4 does not apply to + this round, and the byte-identical corpus TSV is the evidence the safety net + sees exactly what it saw before. Did not run `git commit`/`git push`. +- **Concurrency note.** The `workspace-index` agent was live in + `crates/vlog_semantic` throughout (`workspace.rs`, `tests/workspace.rs`, + `lib.rs`, `model.rs`, `docs/features/workspace-index/`). I touched only + `bind.rs`, which they did not (`git diff` on it shows my 7 compile-fix lines + and nothing else). One transient failure of their + `an_empty_workspace_answers_nothing_and_panics_nowhere` was observed + mid-round; it was their file being edited between my two runs (the panic + message and line number did not match the file on disk) and was green on + re-run. A pre-existing `clippy::cmp_owned` warning in their + `tests/workspace.rs` is theirs and was left alone. + +**Results.** `cargo test --workspace` **299 passed, 0 failed**, of which +`tests/spans.rs` went from 12 to 17. One existing assertion was rewritten, not +added to: `parser.rs`'s `header_imports_stay_separate_statements` unit +test compared `Vec<&[String]>` of header-import paths, which the `ImportPath` +payload change makes ill-typed; it now compares `ImportPath::text()` against +the same expected strings. Nothing else in any existing test moved. `cargo clippy +--workspace --all-targets` silent apart from the concurrent feature's own +warning. `cargo fmt --all --check` clean. `tools/corpus_check.sh corpus` +(read-only): 820 files, **0 verification errors, 0 crashes**, TSV md5 +`aa982463f68c1a3568c02a0fc5e0c455` — byte-identical to the baseline. Corpus +repos clean apart from the pre-existing untracked `.vfmt-corpus-rev` stamps. +`cargo test -p vlog_semantic --test corpus`: 21 485 symbols, 73 708 +references, **0 names unplaced**, unchanged in every digit. + +Files touched: `crates/vlog_parser/src/{ast,parser}.rs`, +`crates/vlog_parser/tests/spans.rs`, +`crates/vlog_formatter/src/format.rs` (8 lines, listed above), +`crates/vlog_semantic/src/bind.rs` (7 lines, listed above), this README, and +one line in `docs/features/vlog-semantic/README.md`'s Handshakes. + +## QA log + +### 2026-08-19 — QA agent + +Scope: `-p vlog_parser`, `-p vlog_formatter`, `-p vlog_semantic` (workspace +run at the end only). Did not touch `crates/vlog_semantic/src/workspace.rs` +or `docs/features/workspace-index/` (concurrent agent's territory). No +commit/push. + +**Gates — all green, exact numbers.** +- `cargo test -p vlog_parser`: 24+19+17 = 60 passed (unit 24, error_recovery + 19, `tests/spans.rs` **17**, up from 12 as claimed). +- `cargo test -p vlog_formatter`, `-p vlog_semantic`, `--workspace`: all + green. Per-crate counts summed to **299 passed, 0 failed**, matching the + work log exactly (50+30+8+1+4+6+2+39 vfmt/vlog_formatter, + 53+24+19+17 vlog_parser, 6+1+19+20 vlog_semantic). +- `cargo clippy --workspace --all-targets`: silent (forced a re-check with + `touch` on `parser.rs` first, since a cached `Finished` line proves + nothing). `cargo fmt --check`: clean, exit 0. +- `tools/corpus_check.sh corpus`: TSV md5 **`aa982463f68c1a3568c02a0fc5e0c455`** + — byte-identical to the claimed baseline. `verification-error: none`, + `crash: none`. +- `cargo test -p vlog_semantic --test corpus -- --nocapture`: **21485 + symbols, 73708 references, 0 names unplaced** for "every file"; exact + match to the claim. + +**Claim 2 (despaced equality can't leak).** Read the full walker in +`tests/spans.rs`. `despace(` appears at lines 118/119 (an unrelated +number/comment-normalization check) and 462/463 (`Instantiation.module_span` +only). Every other name assertion goes through `check_name`/`check_names`/ +`check_opt_name`/`check_import_paths`, which all do exact `assert_eq!(slice, +name)`. Confirmed the weaker rule cannot leak — it is syntactically isolated +to one call site. + +**Claim 3 (skips).** Confirmed in `ast.rs` + `bind.rs`: `NonAnsiPort` has no +`name_span` field and the walker checks `p.span` itself as the name range +(spans.rs:399). `ExprKind::Member`/`Scope` carry no name-range field, and +`bind.rs:735-736` derive the tail directly from `e.span`/`base.span` without +`scan.rs`, as claimed. `DataType` (ast.rs:259-263) has no span field. +`StmtKind::Disable` untouched. + +**Field/helper counts, independently recomputed, not just read off the +README:** summed the sibling-`TextRange` additions in the `ast.rs` diff by +hand — 24 non-list fields + 4 list-shaped conversions (`Import`, +`HeaderImport`, `Genvar`, `Foreach::vars`) = 28, across 21 node kinds, +matching the table. `grep -c 'expect_name()' parser.rs` = 24 (one of them +`expect_ident`'s delegation, as claimed). `grep -c 'split_label('` = 12, +i.e. 11 call sites plus the one `fn split_label` definition — matches "11 +split_label call sites" exactly. + +**Attack tests (scratch, `crates/vlog_parser/tests/attack_spans.rs`, deleted +after — `git status` on `tests/` shows only the pre-existing `spans.rs` +diff).** 10 tests, all green on first correct attempt (two early versions +failed for reasons in my own test setup, not the feature — see below), then +`rm`'d: +1. Escaped identifiers in a module name and a non-ANSI port + (`\a+b`, `\x!y`) — spans exact. +2. `begin : same … end : same` — `label_span != end_label_span`, both slice + back to `"same"`. +3. `import p::*`, `import p::x`, and `import q::a, r::b` at both body-item + and module-header position — every `pkg`/`item` span exact, including the + wildcard's `*` token. +4. `genvar gi, gj, gk;` — 3 `Name`s, order and spans exact. +5. `foreach (arr[i, j])` — 2 vars, spans exact. +6. `Instantiation.module_span` for `sub` (plain), `pkg :: mod` (spaces + around `::`, span covers the whole glued extent including the spaces, + despaced-equal to `"pkg::mod"`), and `pkg::mod` (tight) — all three as + claimed. +7. One `and` statement with two comma-separated instances, one named one + not — `Option` `name`/`name_span` handling confirmed on both arms of the + *same* `GateInstantiation`. +8. `(* x *) wire w;` — `name_span` slices to `"w"` and excludes the + attribute's own byte range. +9. CRLF file — module and declarator name spans still exact under `\r\n`. +10. Module keyword at byte 0 — `name_span.start == 7`, exact slice. + +My first draft of tests 1, 3 and 7 failed for reasons in the test, not the +parser: test 1 put an `input` declaration in the module body and asserted it +against `PortList::NonAnsi` (there was no port list at all); test 3 checked +`m.imports` (header imports only) for body-level `import` items, which live +in `m.items` as `ItemKind::Import`; test 7 wrote two separate `and` +statements and expected them to share one `GateInstantiation`, when each +statement is its own item. Fixed all three and re-ran; all 10 green. No +feature defect found by any of the ten attacks. + +**Mutation re-verification (claim 5).** Re-collapsed +`Instantiation.module_span` to `TextRange::empty(module_start)` at +`parser.rs:1467`. Result: **3 test failures** +(`every_name_span_slices_back_to_its_name`, +`every_node_span_nests_inside_its_parent`, +`name_spans_hold_across_the_formatter_fixtures`), matching the work log's +claim exactly. Reverted; `git diff` on `parser.rs` before and after the +mutate/revert cycle is **byte-identical** (diffed the two `git diff` outputs +directly). + +**Formatter byte-identity beyond the corpus TSV (claim 4).** Built a +baseline `vfmt` release binary from a `git worktree` at `HEAD` (`7cf657a`, +the dev's stated baseline — confirmed by the worktree's own "detached HEAD +7cf657a" message). Formatted 5 corpus files with `--stdout` (non-mutating) +on both the baseline and the current worktree binary and md5'd the output: +`corpus/opentitan/hw/ip/uart/dv/{sva/uart_bind.sv, tests/uart_base_test.sv, +tests/uart_test_pkg.sv, tb/tb.sv, env/uart_env_cfg.sv}` — **all 5 identical** +between baseline and current. Removed the worktree afterward +(`git worktree remove --force`); `git worktree list` now shows only the main +tree at `7cf657a`, matching `master`'s current position (branch is `[ahead +8]` of its upstream, unrelated to this feature). + +**Process note, not a feature defect — full disclosure.** My first pass at +the byte-identity check invoked `vfmt ` (no `--stdout`/`--check`), +which writes in place; this reformatted `corpus/common_cells/src/ +binary_to_gray.sv` once. Caught it because the corpus repos under `corpus/` +are themselves real git checkouts (from `tools/corpus_fetch.sh`, gitignored +at the top level but each subdir has its own `.git`): `git status` inside +`corpus/common_cells` showed the one modified file, `git checkout -- +src/binary_to_gray.sv` restored it exactly, and a follow-up `git status` in +all four corpus repos (`common_cells`, `ibex`, `picorv32`, `opentitan`) came +back clean (only the pre-existing untracked `.vfmt-corpus-rev` stamps). The +corpus-md5 gate above and the semantic-corpus numbers were both captured +*after* this restoration, so neither is affected. Re-ran the 5-file +comparison with `--stdout` afterward, which is what the numbers above +reflect. + +**CLAUDE.md compliance.** `grep` for `unwrap()`/`expect(`/`panic!` on the +added lines of `parser.rs`, `ast.rs`, `format.rs`, `bind.rs` (diff hunks +only): none. `verify.rs` and `tests/verification.rs` diffs are both empty — +confirmed invariant #4 does not apply this round, matching the work log's +statement. New helpers (`expect_name`, `parse_label`, `split_label`, +`join_names`, `join_paths`) are all doc-commented at their definitions. +README has all seven required sections. Mutation evidence is in the work +log with concrete failing-test names, not just a pass/fail count. The +`docs/features/vlog-semantic/README.md` Handshake-1 annotation is exactly +one added sentence inside the existing numbered item, not a new section — +confirmed by reading its diff. + +**Verdict: pass on all 6 claims, no BLOCKING findings.** The one +process-level issue (accidental corpus write) was self-caused, +self-detected, and fully reverted before any reported number was captured; +noted above for the record, not filed as a finding against the feature. + +## Review + +**2026-08-19 — lead. Verdict: accepted; commits jointly with +workspace-index (round 10).** + +The convention argument — sibling fields because the real cost lives in +`format.rs`'s ~35 read sites, `Name` bundles only where parallel Vecs +could silently desync — is the kind of churn-versus-safety reasoning +that should decide every representation question, and it's written +down. The despaced-equality exception for `pkg::mod` is correctly +quarantined (QA read the whole walker to confirm exactness everywhere +else), and the `ImportPath { pkg, item }` split is precisely what the +workspace index consumes for `p::x`. + +Zero-behavior-change was proven three independent ways: corpus md5 +exact, no test churn outside spans.rs, and QA's HEAD-worktree +byte-comparison of formatted output. The three-way mutation testing +(wrong token, whole-construct span, empty span — each caught by ≥3 +tests) sets the content-pin standard the GenIf episode asked for. + +QA's process note — an in-place format of one corpus file during its +own probing, caught and restored via the per-repo git checkout — is +disclosed in the QA log as it should be; the corpus-as-git-checkouts +design absorbed the mistake exactly as intended. Future probes: always +`--stdout` or `--check`. + +Consequence for the next rounds: `scan.rs` is down to one consumer +(`bind_data_type`, blocked on handshake item 2 — a `DataType` span). +vlog_semantic should adopt these fields and shrink scan.rs in its next +touch; hover/definition on end labels (`endmodule : m`) is now free +data for the server. diff --git a/docs/features/vlog-semantic/README.md b/docs/features/vlog-semantic/README.md index 3d51060..750ac79 100644 --- a/docs/features/vlog-semantic/README.md +++ b/docs/features/vlog-semantic/README.md @@ -233,7 +233,9 @@ feature, and the crate works without it): `crates/vlog_semantic/src/scan.rs`, which is ~150 lines this crate should not own and which cannot be right by construction — only right in practice, as the corpus test shows. This is the single change that would - most simplify this crate. + most simplify this crate. **Delivered 2026-08-19 by `name-spans`** — every + declaration listed here now carries its range; see + `docs/features/name-spans/README.md`. 2. **A span for `DataType`** (and for `ExprKind::Cast::ty`), so a type reference does not need a window computed from its neighbours' spans. 3. Nice to have, much smaller: the byte range of `Member`/`Scope` tails, which diff --git a/docs/features/workspace-index/README.md b/docs/features/workspace-index/README.md new file mode 100644 index 0000000..de22ba5 --- /dev/null +++ b/docs/features/workspace-index/README.md @@ -0,0 +1,559 @@ +# workspace-index + +## Goal + +`vlog_semantic::analyze` is deliberately single-file: a name only another file +can supply comes back as `Resolution::ExternalCandidate` carrying the import +paths that could finish it — 19.6 % of every use on cleanly-parsed corpus files +(`docs/features/vlog-semantic/README.md`). This feature is the second layer +that finishes them. `WorkspaceIndex::build` scans every file in the workspace +once and records what each one *declares* — modules, packages, file-scope +typedefs, each package's and module's exported members, and each file's +`` `define`` table. `resolve_external` walks one file's external candidates +against that index and answers them in an **overlay** keyed by reference id. +That is what turns `import prim_pkg::*` and `prim_fifo_sync u_fifo (...)` into +a jump into the file that declares them — TODO.md §6's "cross-file resolution +through header imports", the last piece `textDocument/definition` needs before +`vfmt_server` can be written. + +## API as built + +```rust +// The index +impl WorkspaceIndex { + fn build<'a>(files: impl IntoIterator) -> WorkspaceIndex; + + fn files(&self) -> &[PathBuf]; // indexed by FileId + fn path(&self, FileId) -> Option<&Path>; + fn units(&self, name: &str) -> &[Def]; // module | package | file-scope typedef + fn member(&self, unit: &str, member: &str) -> &[Def]; + fn members_of(&self, unit: &str) -> impl Iterator; + fn defines(&self, FileId) -> Option<&DefineTable>; + fn find_define(&self, name: &str) -> Vec<(FileId, &Define)>; + fn workspace_symbols(&self, query: &str) -> Vec>; + fn counts(&self) -> IndexCounts; +} + +struct Def { file: FileId, name_span: TextRange, kind: SymbolKind } +struct WorkspaceSymbol<'a> { name: &'a str, container: Option<&'a str>, def: &'a Def } +struct IndexCounts { files, modules, packages, typedefs, members, defines } + +// The overlay +fn resolve_external(&Semantics, &WorkspaceIndex) -> ExternalResolutions; + +enum ExternalTarget { Resolved(Def), Ambiguous(Vec), StillUnresolved } +impl ExternalTarget { fn defs(&self) -> &[Def]; fn best(&self) -> Option<&Def>; } +// StillUnresolved deliberately does not distinguish "package absent from the +// workspace" from "package found but member absent" (QA find, lead-ruled): +// both answer an LSP definition request the same way (no target), and the +// in-file analog of the second case is already Resolution::NotFound before +// the overlay is consulted. If a diagnostic ever wants the distinction, add +// a variant then — not speculatively now. + +impl ExternalResolutions { + fn get(&self, ReferenceId) -> Option<&ExternalTarget>; + fn iter(&self) -> impl Iterator; // reference order + fn counts(&self) -> (usize, usize); // (answered, total) + fn definition_of(&self, &Semantics, offset: u32) -> Option>; +} + +enum Definition<'a> { Local(&'a Symbol), External(&'a [Def]) } +``` + +Additive changes to `vlog_semantic`'s existing API (nothing removed, nothing +renamed): `ReferenceId(pub u32)`, `Semantics::reference(ReferenceId)` and +`Semantics::reference_id_at(offset)` — the overlay needs a stable key for a +reference, and index-into-`references()` is the one that already exists +implicitly. + +### The two layers, and why they are two + +`analyze` gives a file's `Semantics`; `resolve_external` gives an +`ExternalResolutions` **beside** it. `Semantics` is never mutated. + +- A file's own analysis is true regardless of what the rest of the workspace + is doing. Folding workspace answers into it would make every `Semantics` + stale the moment any *other* file is edited. +- The two layers are invalidated by different events — editing this buffer + invalidates the `Semantics`, editing any other file invalidates the index — + so a server recomputes whichever one changed and recomposes cheaply. +- Composition is one function: `ExternalResolutions::definition_of` asks the + in-file layer first (a local declaration always wins over a workspace one), + then the overlay, then falls back to "the cursor is on a declaration". + `Semantics::definition_of` still works alone, for a server with no + workspace open. + +The overlay holds an entry **only** for references the in-file layer left as +`ExternalCandidate`; a locally-resolved reference is absent from it entirely, +which is also how a caller tells "resolved locally" from "not an external +candidate at all" without re-reading the `Resolution`. + +## Resolution rules + +An external candidate carries `paths` — every import in the lexical chain that +could supply the name, in the order they are written, or the single unit name +for an instantiation. The paths are tried **in that order** and the first path +with any hit wins: + +1. `p::*` and `p::x` both mean *the name this use spells, inside unit `p`* — + looked up in the index's member table for `p`. (For `p::x` the tail always + equals the use's own name, both for a `p::x` expression and for an + `import p::x` that only offers itself for the name `x`; the use's name is + what is looked up, so the two spellings need no separate handling.) +2. A bare path is the **unit itself** when the use spells the unit's name — an + instantiated module, the `p` head of `p::x`, the package of an import. +3. A bare path whose name differs from the use's is a **member of that unit**: + the `.port` (or `.PARAM` override) of a connection to a module declared in + another file. + +Two paths that could both supply the name do not make an ambiguity: the first +one written wins, which is exactly the rule the single-file layer already +applies to two in-file wildcard imports ("imports are consulted in the order +written"). Ambiguity means something else — see below. + +### What is indexed + +- **Units** (`units(name)`): every file-scope `module`, `package` and + `typedef`. File-scope typedefs are indexed for `workspace_symbols` and for a + future include-aware lookup; nothing resolves to them today, because a use of + a type declared in another file with no import path is `NotFound`, not an + external candidate, and so never reaches this layer. +- **Package members**: everything declared at a package's top level — params, + typedefs, enum variants, functions, tasks, nets and vars. This is what makes + `import p::*` and `p::x` reach *into* the package's file. +- **Module members**: ports and parameters only. That is exactly what a + connection list or a `#(.W(8))` override can name; an internal net of another + module stays unreachable, which is correct and is a test. +- **`` `define`` tables**: `defines::collect_defines` per file, keyed by + `FileId`, read off the same token stream the parse used. + +A declaration whose `name_span` is empty (the single-file layer's "I could not +locate this name in the source") is **not** indexed: an editor must never be +sent to a zero-width range. + +### Duplicates and ambiguity + +Real workspaces collide: the corpus declares the same module name in several +files (vendored copies, `_reg_top` variants, an `.sv` and a `.v` of the same +block). Every declaration is kept. + +- `units(name)` / `member(unit, name)` return **all** of them, in + **disambiguation order: by file path (byte-wise `PathBuf` sort), then by + position within the file**. `FileId`s are assigned in that same sorted order, + so `FileId` order *is* path order, and the order does not depend on the order + the caller happened to hand the files over (asserted by a test). +- One hit → `ExternalTarget::Resolved`. Several → `ExternalTarget::Ambiguous` + holding all of them in that order. `best()` takes the first; + `Definition::External` hands the whole slice to the caller, because LSP's + `textDocument/definition` accepts several locations and showing all of them + is more honest than silently picking one. +- No kind filtering: a name declared as a module in one file and a package in + another is ambiguous over both. Distinguishing them would need the reference + to say which it wanted, which the recorded paths do not carry. +- A path handed to `build` twice is one file; the first copy wins. + +### `` `define`` lookup has a home, not a policy + +`find_define(name)` returns **every** definition in the workspace, in file +order. Which one a given use actually sees depends on the `` `include`` graph +and on `` `ifdef``, neither of which this index models (and neither of which the +define table models either — `docs/features/define-table/README.md`). Hover can +show "defined as 8 in `defs.svh:12`, as 16 in `other.svh:3`"; picking one +silently would be a guess. `defines(file)` is the exact per-file table when the +caller does know which file it means. + +## Assumptions + +- The caller does the I/O, the file discovery and the encoding decisions, and + hands over `(PathBuf, &str)`. `build` does the tokenizing and parsing itself + (with the tolerant parser) so that every file contributes the declarations + that *did* parse — 42 % of corpus files still hit a parse error, and a + workspace index that skipped them would be useless on real RTL. +- Sources outlive the `build` call only; the index copies out the names and + spans it needs and keeps no borrow. Slicing a `Def.name_span` is the + caller's job, against the same text it passed in — the index does not retain + file contents (860 corpus files are ~30 MB; keeping them would double the + memory a server already spends on open buffers). +- A file that does not *lex* (an unterminated string or block comment) still + gets a `FileId` and an empty define table, and contributes no declarations. + The lexer is all-or-nothing, so there is nothing to salvage. +- The corner where a module's name equals one of its own port names + (`module foo (input foo);`, and a connection `.foo(x)` on it) resolves the + bare path to the module rather than the port, by rule 2 above. Nothing in + the corpus does this. +- `build` is O(files) and single-threaded. Measured at 860 files below; a + workspace an order of magnitude larger would want the same rayon treatment + `vfmt` already applies to formatting, which is a change of caller, not of + this API. + +## Non-goals + +- **No incrementality.** `build` is a pure function of its inputs; a changed + workspace means calling it again. TODO.md §6 defers salsa-style + incrementality explicitly, and per-file recompute is fine at Verilog sizes. +- **No `` `include`` following.** The index does not build the include graph, + so it cannot say which define or which typedef a given file actually sees. +- **No elaboration**: no parameter binding, no instance hierarchy, no + cross-file type checking. +- **No filesystem walking, no config discovery.** The caller decides what the + workspace is. +- **The index does not rewrite `Semantics`.** By design, see the two layers + above. + +## Handshakes + +**Consumed from `vlog_parser`:** + +- `tokenize`, `parse_tolerant`, `parse_source_tolerant` — the tolerant path, + never failing. +- `defines::collect_defines(&[Token]) -> DefineTable`, `Define`, + `DefineTable::all/latest/entries`. +- `span::TextRange`. + +The concurrent parser change adding `name_span` to AST nodes (the handshake +`docs/features/vlog-semantic/README.md` filed) landed mid-run. This module was +written against the AST as it stood and does **not** adopt the new fields: it +consumes only `Symbol.name_span` from `vlog_semantic`, whose meaning is +unchanged by where the span comes from. Nothing here needs revisiting when +`scan.rs` is deleted. + +**Consumed from `vlog_semantic` (this crate):** + +- `analyze`, `Semantics::{scope, symbol, references, reference, file_scope, + symbol_at, reference_id_at}`, `Symbol.{name, kind, name_span, child_scope}`, + `Scope.symbols`, `Resolution::ExternalCandidate { paths }`. +- The `paths` contract in particular: "every import in the chain that could + supply the name, in scope order" for a lexical use, `"p::x"` for a package + member, the bare unit name for an instantiation or a `.port`. The three + rules above are exactly a reading of that contract; if `bind.rs`/`resolve.rs` + ever change the spelling of a path, `follow_one` in `workspace.rs` changes + with it. + +**Promised to consumers (`vfmt_server`):** + +- `WorkspaceIndex::build` never panics and never fails, on any input, + including files that do not lex. +- The index is deterministic: same `(path, source)` set → same `FileId`s, same + order in every returned slice, regardless of iteration order. +- `Def.name_span` is a non-empty byte range in `Def.file` that slices back to + exactly the name that was looked up (asserted over the whole corpus). +- `resolve_external` does not mutate `Semantics` and holds no borrow of the + index in its result. + +## Corpus acceptance + +`cargo test -p vlog_semantic --test workspace -- --nocapture`, over the 860 +`.v`/`.sv`/`.svh` files in `corpus/` (Ibex, OpenTitan, PULP common_cells, +picorv32), 2026-08-19: + +``` +workspace index: 860 files in 0.68s — 521 modules, 63 packages, + 38 file-scope typedefs, 8044 exported members, + 502 define directives +``` + +Build time is a debug build, single-threaded, sources already in memory +(reading them costs the caller another ~0.1 s). Well inside the ~2 s budget; +re-running the whole build on every workspace change is affordable, which is +why there is no incrementality. + +**The headline.** For each file: analyze it, resolve its external candidates +against the index, and count what happened. + +| population | references | external candidates | workspace answers | one target | ambiguous | still unresolved | external rate after | +|---|---:|---:|---:|---:|---:|---:|---:| +| every file | 73 708 | 14 325 (19.4 %) | **81.4 %** | 75.4 % | 6.0 % | 18.6 % | 3.6 % | +| files that parse cleanly | 46 408 | 9 101 (19.6 %) | **87.0 %** | 78.9 % | 8.1 % | 13.0 % | **2.6 %** | + +Read against `docs/features/vlog-semantic/README.md`'s baseline: on cleanly +parsed files the single-file layer resolved 79.5 % of uses and left 19.6 % as +external candidates. The workspace layer answers 87 % of those, so the +unresolved-external rate over *all* references falls **19.6 % → 2.6 %**, and +~96 % of every identifier in the corpus now has somewhere to jump to. +"Ambiguous" counts as answered: it is a list of real locations, which is what +LSP's definition request takes. + +**Where the ambiguity comes from** — all of it real, none of it a defect. The +top shapes are OpenTitan's technology libraries: `prim_buf`, `prim_flop`, +`prim_xor2` and their ports/params are declared once in +`ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/` and again in +`.../prim_xilinx/rtl/`. Which one a build uses is a build-system choice this +index has no access to, so both are offered. 98 distinct ambiguous shapes in +the whole corpus. + +**The honest gaps** (top unresolved paths, clean-file population): + +| path | uses | what it is | +|---|---:|---| +| `picorv32` | 429 | *is* in the corpus, but its `module` header contains a `` `ifdef`` inside the port list, so the declaration is swallowed by an error node and never indexes. Moves when the parser moves, not when this feature does. | +| `sail_ibexspec` | 168 | a formal-verification model not vendored into the corpus | +| `picorv32_axi` | 141 | same `` `ifdef``-in-header problem as `picorv32` | +| `SB_SPRAM256KA` | 44 | an iCE40 vendor primitive — no source anywhere | +| `PLLE2_ADV` | 32 | a Xilinx vendor primitive — likewise | + +Over all files the list also shows `uvm_pkg::*` (220) and `uart_reg_pkg::*` +(214) — a verification library and a generated register package, neither +checked into the corpus. Every one of these is a workspace that genuinely does +not contain the definition; none is a lookup this layer got wrong. + +**Properties the test asserts** (not the percentages): no panic anywhere; +`build` twice over the same sources gives byte-identical file ids, counts and +symbol fingerprint; every single answer's `name_span` slices back to exactly +the name the reference spells, in the file the answer names; build under 5 s; +and more than half of all external candidates answered on clean files. + +## Status / TODO + +- [x] `crates/vlog_semantic/src/workspace.rs`: `WorkspaceIndex::build` over + `(PathBuf, &str)` pairs, tolerant parse inside +- [x] Units indexed: modules, packages, file-scope typedefs — duplicates kept, + path-sorted disambiguation order +- [x] Members indexed: package exports (params, typedefs, enum variants, + functions, tasks, nets, vars) and module ports/params +- [x] Per-file `` `define`` tables + workspace-wide `find_define` +- [x] `resolve_external` → `ExternalResolutions` overlay keyed by + `ReferenceId`, `Semantics` untouched +- [x] Composed `definition_of`, `workspace_symbols`, `members_of` +- [x] Unit tests: cross-file instantiation, cross-file port, wildcard and + explicit import, package member, enum variant, duplicate → `Ambiguous`, + broken file, empty workspace, rebuild after edit, path-order + independence, define lookup +- [x] Corpus acceptance: build time, counts, resolution rate, determinism, + every answer's span slices back to the name +- [x] TODO.md §6 workspace-index checkbox +- [ ] Deferred (non-goals above): `` `include`` graph, incrementality, + elaboration + +## Work log + +**2026-08-19 — dev agent.** Built `workspace.rs` and `tests/workspace.rs`. +Key decisions, all argued above: + +- **Overlay, not mutation.** The task named this; the argument that made it + obviously right is invalidation: the two layers go stale on different + events. +- **Members are indexed for modules too**, not only packages. The single-file + layer emits an external candidate for every `.port` of every instantiation + of an out-of-file module, and on this corpus those are a large share of all + external candidates — indexing ports and params costs one `matches!` arm and + converts them. Restricted to ports and params so an internal net of another + module never becomes reachable. +- **First path wins; ambiguity is per-path.** Consistent with the single-file + rule for two competing in-file imports. Ambiguity is reserved for the thing + it really means — the same name declared in more than one file. +- **`FileId` follows sorted paths**, assigned after sorting inside `build`, so + determinism does not depend on the caller and "disambiguation order" is + simply ascending `FileId`. +- **Empty `name_span`s are dropped** rather than indexed: the single-file layer + documents an empty span as "the name is not literally spelled here", and an + editor sent to a zero-width range is worse than no answer. +- **`find_define` returns all definitions.** No include graph exists, so any + single answer would be a guess; the table is a home for the lookup, not a + policy. + +Two additive items in the existing crate API (`ReferenceId`, +`Semantics::reference`/`reference_id_at`) — an overlay needs a key, and +`reference_at` returned only a `&Reference`, which cannot be used as one. + +Checks at the end: `cargo test -p vlog_semantic` 46 tests green (6 scan unit + +19 behavior + 1 vlog-semantic corpus + 20 new), `cargo clippy -p vlog_semantic +--all-targets` silent, `cargo fmt -p vlog_semantic -- --check` clean, +`cargo test --workspace` green (19 test binaries, 0 failures). + +Mid-run the parser agent's `name_span` change landed and briefly broke +`vlog_parser`/`bind.rs` compilation. Per the task brief this module did not +adopt the new AST fields; it depends only on `vlog_semantic`'s own +`Symbol.name_span`, so it needed no change once their work compiled again. + +## QA log + +**2026-08-19 — QA agent.** Verified every claim in the review request. No +BLOCKING findings (no silent corruption, no wrong definition target, no +nondeterminism). Two minor, non-blocking findings below. + +**Gates (`-p vlog_semantic`).** +- `cargo test -p vlog_semantic`: **46/46 green** — 6 `scan` unit + 1 corpus + + 19 `semantics` + 20 `workspace`, matching the claim exactly. +- `cargo clippy -p vlog_semantic --all-targets`: silent. +- `cargo fmt -p vlog_semantic -- --check`: clean. +- `cargo test --workspace`: green, 19 test binaries (16 with tests + 3 + doc-test binaries at 0 tests each), 0 failures. Ran clean on the first try; + no vlog_parser churn observed during this pass. +- `git diff -- crates/vlog_semantic/src/lib.rs crates/vlog_semantic/src/model.rs`: + confirmed additive-only — `mod workspace;`, the `workspace::*` re-export + block, `ReferenceId` (new struct in `model.rs`), and + `Semantics::{reference, reference_id_at}` are all new; nothing renamed or + removed. (`bind.rs` also has unrelated non-additive edits adapting to the + concurrent parser's `name_span`/`ImportPath` change — outside this + feature's scope, not evaluated here, and not part of the workspace-index + diff.) + +**Corpus numbers — reproduced exactly, 3 runs:** +``` +workspace index: 860 files in 0.70s / 0.70s / 0.69s — 521 modules, 63 packages, + 38 file-scope typedefs, 8044 exported members, 502 define directives +``` +Every count byte-identical across all 3 runs; times within the claimed +0.68–0.71 s band. Full headline table (every file / clean files) reproduced +exactly: 73708/14325(19.4%)/81.4%(75.4%+6.0%)/18.6%/3.6% and +46408/9101(19.6%)/87.0%(78.9%+8.1%)/13.0%/2.6% — matches the README table and +work-log figures to the decimal. Spot-checked the ambiguity claim +independently: `corpus/ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/` and +`.../prim_xilinx/rtl/` do contain the same file basenames (`prim_and2.sv`, +`prim_buf.sv`, `prim_clock_buf.sv`, `prim_flop.sv`, `prim_pkg.sv`, ...) — +the OpenTitan ambiguity claim is real corpus structure, not asserted blind. + +**Attack probes (18 scratch tests, `crates/vlog_semantic/tests/qa_probe.rs`, +written, run, and deleted — no trace left in the tree):** +- Same module name in 3 files, **4 permuted input orderings**: all kept + (`units("dup").len() == 3`), ascending `FileId`, `FileId` order == path + order (`a_first.sv` < `b_second.sv` < `c_third.sv`) regardless of caller + order, and the resulting `Vec` byte-identical across all 4 orderings. +- Garbage-only file (`@@@ !!! not verilog`): 1 file id, 0 declarations, no + panic. Unlexable file (unterminated string): still gets a file id and an + empty define table, no panic. +- Same path handed twice with **different content** (not just identical + content, which is all the existing suite covers): one file in the index + either way; content of the **first entry in the caller's input order** + wins (verified both orderings — first-wins is consistent with `build`'s + `sort_by` being a stable sort over equal keys, then `dedup_by` keeping the + first of each run). Matches the documented "first copy wins" rule. Not + silent corruption — deterministic and exactly what the README promises. +- Package member name shadowing a module name workspace-wide: `units()` and + `member()` are confirmed separate namespaces — `units("shadow")` sees only + the module, `member("p", "shadow")` sees only the package member, no + cross-contamination. +- Empty-string source: 1 file id, zero of everything, no panic. Zero-member + package (`package p; endpackage`): unit indexed as `Package`, + `members_of` empty, `member("p", anything)` empty — no panic on an empty + child scope. +- `import p::absent_member` where `p` is declared in another file but has no + such member: **2** external candidates come out of this one import + statement — the path head `p` itself (resolves fine to the package, since + `p` really is in the workspace) and the tail `absent_member` + (`ExternalTarget::StillUnresolved`, confirmed via `overlay.get`). Compared + against the in-file equivalent (`p` declared in the *same* file, + `p::absent_member` used): `resolve.rs`'s `Target::PackageMember` arm + returns `Resolution::NotFound` directly when the package is known locally + and lacks the member — it never becomes an `ExternalCandidate` at all + (`overlay.counts()` is `(0, 0)` for that reference). So the two layers are + *behaviorally* consistent (both end in "no target" for a real absence) but + *representationally* different: in-file collapses to `NotFound` before the + overlay ever sees it, cross-file surfaces as `StillUnresolved` because + `ExternalTarget` has no `NotFound` variant to distinguish "no such member" + from "no such package in the workspace either." This asymmetry is not + documented anywhere in the README's Resolution rules section. **Minor, + non-blocking** — the observable behavior (no definition offered) is + correct either way, but a future consumer inspecting `ExternalTarget` + variants alone cannot tell "package exists, member doesn't" from "package + doesn't exist in the workspace at all." Worth a one-line mention in + Resolution rules or Assumptions if the lead wants it; not fixed here per + the write-scope restriction on this pass (QA log only). +- `find_define("K")` defined in 3 files with 3 different values: all 3 + returned, in file-path order (`a.svh` < `m.svh` < `z.svh`), not value order + and not any other ranking — confirms "no resolution order is implied" as + documented. + +**Overlay correctness (3-file scratch workspace: A instantiates B, imports +`p::*`, uses `p::K` and absent `q::Z`):** +- Instantiation of `b` in A resolves via `definition_of` to `Definition::External` + pointing at B.sv, `name_span` slices to exactly `"b"`. +- `K` resolves to `Definition::External` pointing at P.sv, slices to `"K"`. +- `q::Z` (q not declared anywhere): `definition_of` returns `None`, and the + underlying overlay entry is confirmed `ExternalTarget::StillUnresolved` + (not just "None for some other reason"). +- A local symbol (`localparam int SHARED` inside the module) shadowing an + imported package member of the same name: `definition_of` returns + `Definition::Local` pointing at the in-file declaration — two-layer + precedence (local always wins over the overlay) confirmed. +- `reference_id_at(offset)` round-trips: any offset inside a reference's name + span maps to the same `ReferenceId`, and `sem.reference(id)` gives back the + right reference. + +**`workspace_symbols` probes:** +- True substring match (not prefix-only): `"FIFO"` matches + `my_fifo_thing` (match in the middle of the name). +- Case-insensitive both directions: `"FIFO"` and `"fIfO"` both match + `my_fifo_thing`. +- Empty query: matches both units and members (confirmed a package unit and + one of its members both appear). +- A query matching a unit and a member of the same spelled name + (`"shadow"` module vs. `p::shadow` param, same fixture as the namespace + probe): both appear, exactly 2 hits, one with `container: None` and one + with `container: Some("p")` — no cross-contamination in + `workspace_symbols` either. +- `"zzz"` (no match): empty result, no panic. + +**Determinism stress:** corpus index counts identical across 3 independent +full 860-file builds (see corpus numbers above); a 3-file local workspace +built 5× in a row gives byte-identical `IndexCounts` every time; the +corpus test's own internal build-twice-and-fingerprint-`workspace_symbols("")` +assertion also passed. No nondeterminism found anywhere probed. + +**CLAUDE.md compliance:** +- No `unwrap()`/`expect()`/`panic!` anywhere in `workspace.rs` (grepped, + zero hits) — library code paths return `Option`/empty slices instead, as + required. +- README has all required sections (Goal, Assumptions, Handshakes, + Status/TODO, Work log, QA log, Review) present and populated. +- TODO.md §6 "Workspace index for cross-file navigation" checkbox: checked, + and the summary line under it (87% of external candidates, 19.6%→2.6%, + 0.7s/860 files) matches the reproduced corpus numbers exactly — honest. +- The stale out-of-scope line noted in `docs/features/vlog-semantic/README.md` + (line 223, "Requested of `vlog_parser` — not done here — out of scope for + this...") was located but **left untouched** per instructions — lead's + call, not this feature's file. +- One doc-comment gap found: `IndexCounts` in `workspace.rs` (around line + 238) has doc comments on `files`, `typedefs`, `members`, `defines` but + **not** on `pub modules: usize` or `pub packages: usize` — the only two + undocumented public fields found in the whole module. **Minor, + non-blocking**, self-explanatory field names, not fixed here per the + write-scope restriction (docs/features/workspace-index/README.md QA log + only, no source edits this pass). + +**Verdict: PASS on all 6 claims.** No blocking findings. Two minor, +non-blocking documentation gaps noted above for the lead/dev to close: +(1) `IndexCounts::modules`/`IndexCounts::packages` missing doc comments, +(2) the cross-file-vs-in-file `NotFound`/`StillUnresolved` asymmetry for +"package known, member absent" is real, consistent in effect, but +undocumented. + +## Review + +**2026-08-19 — lead. Verdict: accepted; commits jointly with name-spans +(round 10). The owner's cross-file requirement — `import pkg::*;` at +the top of a file resolving anywhere in the workspace — is now met.** + +Points reviewed and accepted: + +1. **The two-layer overlay design** is the architectural decision of + the round: `Semantics` stays a pure single-file fact, the overlay is + keyed by `ReferenceId`, and the two invalidate on different events + (this buffer vs. any other file). That's the shape an editor + actually needs, and it kept the whole feature additive — QA + confirmed nothing in the existing API was renamed or moved. +2. **FileIds assigned after path sort** makes determinism a property + of the data, not the caller — QA's permuted-input and + same-path-different-content probes are exactly the attacks that + design defeats. +3. **Ambiguity kept, not resolved**: OpenTitan's prim_generic vs + prim_xilinx duplicates are real, and handing all locations to the + LSP (which supports several) is more honest than inventing a + ranking. Same reasoning accepted for `find_define` being unranked + without an `` `include`` graph. +4. **87% of external candidates answered** (19.6% → 2.6% on clean + files), with the residue traced to named causes — the + `ifdef-in-port-list parse gap (roadmap item 6) and genuinely absent + sources. The acceptance metric was measured against the number the + vlog-semantic review set, which is how these baselines are supposed + to work. + +Lead fixes on acceptance: the two missing `IndexCounts` doc comments, +and QA's notable finding — `StillUnresolved` not distinguishing +package-absent from member-absent — is now documented as a deliberate +ruling in the API sketch above (both mean "no target" to an LSP; add a +variant when a diagnostic needs it, not speculatively). + +With this, TODO §6's foundations are all delivered: spans, tolerant +parsing, define table, single-file semantics, workspace index. What +remains is the server itself and editor packaging.