From 9ef1058059d35e0cd7533006affd6e7d272d6985 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 5 Sep 2026 10:41:54 -0500 Subject: [PATCH] Package re-exports as real references: bound halves, RX facts, the member walk through re-exports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §48 (docs/features/package-reexports). Closes topo §2.9-16 and dpi-export's request (a). `bind_export_path` records `export pkg::item` as a `Target::Package` use and a `Target::UnitMember` use, with no scope import (a re-export brings nothing into the exporting scope, IEEE 1800 §26.6). `FileFacts` gains the `RX` group (`FACTS_FORMAT` 17 → 18): per package its re-export edges (package, source, item|*), with `export *::*` expanded into the package's own imports at record time. `workspace/reexport.rs`: the member lookup and listing follow re-exports transitively with a visited set, layered over `own_chain`/`own_members` so the walk cannot recurse into itself; `Affected::exporters` keeps one-file updates exact and `fingerprint()` shows the edges. Definition, hover, completion after `pkg::`, references and rename all read the one edge. Census 103 870 → 103 875 references (the corpus's two package export lines), 0 unplaced; 0 of 860 corpus files differ. opentitan: `spi_device_pkg::SramDepth`, reached only through a re-export, resolves. Co-Authored-By: Claude Fable 5.1 --- TODO.md | 12 +- crates/lucisv_server/tests/e2e.rs | 145 ++++++ crates/vlog_semantic/src/bind/item.rs | 49 +- crates/vlog_semantic/src/facts.rs | 33 +- .../vlog_semantic/src/workspace/external.rs | 49 +- crates/vlog_semantic/src/workspace/index.rs | 38 +- crates/vlog_semantic/src/workspace/mod.rs | 13 +- crates/vlog_semantic/src/workspace/record.rs | 10 +- .../vlog_semantic/src/workspace/reexport.rs | 189 +++++++ crates/vlog_semantic/src/workspace/update.rs | 24 + crates/vlog_semantic/tests/reexports.rs | 380 ++++++++++++++ docs/features/dpi-export/README.md | 5 + docs/features/package-reexports/README.md | 481 ++++++++++++++++++ docs/topo.md | 2 +- 14 files changed, 1392 insertions(+), 38 deletions(-) create mode 100644 crates/vlog_semantic/src/workspace/reexport.rs create mode 100644 crates/vlog_semantic/tests/reexports.rs create mode 100644 docs/features/package-reexports/README.md diff --git a/TODO.md b/TODO.md index bae6817..33a577f 100644 --- a/TODO.md +++ b/TODO.md @@ -4842,12 +4842,14 @@ dpi-export handshake). Two halves, both here: and the delta explained (new references only); FACTS_FORMAT bump test (an older store is dropped whole). -- [ ] 48.1 binding of `export` halves, no scope import -- [ ] 48.2 `RX` facts, FACTS_FORMAT 18, member walk through re-exports -- [ ] docs: feature README; topo §2.9-16 struck (lead); dpi-export +- [x] 48.1 binding of `export` halves, no scope import +- [x] 48.2 `RX` facts, FACTS_FORMAT 18, member walk through re-exports +- [x] docs: feature README; topo §2.9-16 struck (lead); dpi-export handshake (a) answered -- [ ] Gates (guarded); census delta explained -- [ ] QA: the three-file workspace over the wire; cycles; unknown items; +- [x] Gates (guarded); census delta explained — references 103 870 → 103 875 + (+5: the corpus's two package `export` lines, five name halves in all), + every other number flat +- [x] QA: the three-file workspace over the wire; cycles; unknown items; an opentitan UVM package tree read-only (definition through a re-export, before/after) diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index c2137dd..e3cbd94 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -8167,3 +8167,148 @@ fn an_open_still_publishes_its_diagnostics_with_no_edit_behind_it() { let codes: Vec<&str> = items.iter().filter_map(|d| d["code"].as_str()).collect(); assert!(codes.contains(&"no-tabs"), "the open published nothing about the tab: {items:#?}"); } + +/// package-reexports (2026-09-05, TODO §48): `export b_pkg::x;` over the real +/// wire, in the shape a UVM tree writes it — a package that declares, a +/// package that re-exports, and a third file that only ever names the +/// re-exporting one. +/// +/// What only an e2e test can settle: that all five capabilities read the same +/// re-export edge. Definition and hover land on `b_pkg`'s declaration however +/// the name is reached (bare under `import a_pkg::*`, or written out as +/// `a_pkg::x`); completion after `a_pkg::` offers it; find-references from +/// `x`'s own declaration lists the `export` line **and** the uses through it; +/// and a rename edits every one of them, the `export` line's item half +/// included. The wildcard forms are here too — `export b_pkg::*;` and +/// `export *::*;` beside an `import` — because the walk that follows them is +/// the walk definition asks (`docs/features/package-reexports/README.md`). +#[test] +fn a_name_reached_through_a_package_reexport_is_navigated_listed_and_renamed() { + let dir = temp_dir("reexport"); + let b = dir.join("b_pkg.sv"); + let b_text = "package b_pkg;\n localparam int x = 8;\n localparam int y = 9;\nendpackage\n"; + std::fs::write(&b, b_text).expect("write"); + let a = dir.join("a_pkg.sv"); + let a_text = "package a_pkg;\n export b_pkg::x;\nendpackage\n"; + std::fs::write(&a, a_text).expect("write"); + std::fs::write(dir.join("w_pkg.sv"), "package w_pkg;\n export b_pkg::*;\nendpackage\n") + .expect("write"); + std::fs::write( + dir.join("s_pkg.sv"), + "package s_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n", + ) + .expect("write"); + let top = dir.join("top.sv"); + let top_text = "\ +module top; + import a_pkg::*; + localparam W = x; + localparam V = a_pkg::x; + localparam Y = w_pkg::y; + localparam Z = s_pkg::y; +endmodule +"; + std::fs::write(&top, top_text).expect("write"); + + let root = format!("file://{}", dir.display()); + let a_uri = format!("file://{}", a.display()); + let b_uri = format!("file://{}", b.display()); + let top_uri = format!("file://{}", top.display()); + let at = |id: u32, method: &str, line: u32, character: u32| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/{method}","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":{line},"character":{character}}}}}}}"# + )) + }; + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(WIDE_SCOPE), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(top_text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{b_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(b_text).expect("json") + )), + // The bare `x`, reached through `import a_pkg::*`. + at(2, "definition", 2, 17), + // ...and written out as `a_pkg::x`, hovered and completed. + at(3, "hover", 3, 24), + at(4, "completion", 3, 24), + // The two wildcard forms, each in its own package. + at(5, "definition", 4, 24), + at(6, "definition", 5, 24), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{b_uri}"}},"position":{{"line":1,"character":17}},"context":{{"includeDeclaration":false}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":8,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{b_uri}"}},"position":{{"line":1,"character":17}},"newName":"addr"}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")) + }; + let jumped_to = |id: u32, line: u64| { + let result = &response(id)["result"]; + let target = result.get("uri").map_or(&result[0], |_| result); + assert!( + target["uri"].as_str().expect("a uri").ends_with("b_pkg.sv"), + "response {id} did not land in the declaring package: {result:#?}" + ); + assert_eq!(target["range"]["start"]["line"], line, "response {id}"); + }; + + jumped_to(2, 1); + let hover = response(3)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(hover.contains("b_pkg.sv:2"), "the declaring file and line: got {hover}"); + assert!(hover.contains("localparam int x = 8"), "got {hover}"); + + let items = response(4)["result"]["items"].as_array().expect("a completion list"); + let labels: Vec<&str> = items.iter().filter_map(|item| item["label"].as_str()).collect(); + assert!(labels.contains(&"x"), "the re-exported name is offered: {labels:?}"); + assert!(!labels.contains(&"y"), "and only what `a_pkg` re-exports: {labels:?}"); + + jumped_to(5, 2); + jumped_to(6, 2); + + let references = response(7)["result"].as_array().expect("a list"); + let sites: Vec<(&str, u64)> = references + .iter() + .map(|site| { + let uri = site["uri"].as_str().expect("a uri"); + ( + uri.rsplit('/').next().unwrap_or(uri), + site["range"]["start"]["line"].as_u64().unwrap_or(u64::MAX), + ) + }) + .collect(); + assert!(sites.contains(&("a_pkg.sv", 1)), "the `export` line itself: {sites:?}"); + assert!(sites.contains(&("top.sv", 2)), "the bare use: {sites:?}"); + assert!(sites.contains(&("top.sv", 3)), "and the qualified one: {sites:?}"); + + let changes = &response(8)["result"]["changes"]; + assert_eq!( + changes[&a_uri].as_array().expect("the export line is rewritten").len(), + 1, + "{changes:#?}" + ); + assert_eq!(changes[&a_uri][0]["newText"], "addr"); + assert_eq!(changes[&a_uri][0]["range"]["start"]["line"], 1); + assert_eq!(changes[&a_uri][0]["range"]["start"]["character"], 16); + assert_eq!(changes[&top_uri].as_array().expect("both uses").len(), 2, "{changes:#?}"); + assert_eq!(changes[&b_uri].as_array().expect("the declaration").len(), 1, "{changes:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_semantic/src/bind/item.rs b/crates/vlog_semantic/src/bind/item.rs index 96b6b7f..677f897 100644 --- a/crates/vlog_semantic/src/bind/item.rs +++ b/crates/vlog_semantic/src/bind/item.rs @@ -169,16 +169,21 @@ impl<'a> Binder<'a> { self.bind_expr(net, scope); } } + // A package re-export names two things another file declares, and + // both are references — see [`Binder::bind_export_path`]. A **DPI** + // export stays the opaque leaf it was: it names a function + // declared elsewhere in this same scope, and saying which one is a + // separate question (`docs/features/dpi-export/README.md`). + ItemKind::Export(ExportDecl::Package(paths)) => { + for path in paths { + self.bind_export_path(path, scope); + } + } // Opaque leaves: verbatim text this crate makes no claims about. // `Verbatim` is a constraint or covergroup body — no symbol is // bound for its name and nothing inside it is scanned, the same - // contract macro invocations have. `Export` is a leaf too: a DPI - // export names a function declared elsewhere in the same scope, - // and a package re-export does not bring the name into this scope - // (an `import` alongside it does that). Resolving either one is a - // vlog_semantic decision, not the parser's — see - // `docs/features/dpi-export/README.md` Handshakes. - ItemKind::Export(_) + // contract macro invocations have. + ItemKind::Export(ExportDecl::Dpi(_)) | ItemKind::Directive(_) | ItemKind::MacroItem(_) | ItemKind::Timeunit(_) @@ -258,6 +263,36 @@ impl<'a> Binder<'a> { }); } + /// Record one `pkg::item` / `pkg::*` path of an `export` — **the two + /// halves an import records, and no import at all**. + /// + /// A re-export makes the name visible to whoever imports *this* package; + /// it brings nothing into the exporting package's own scope (IEEE 1800 + /// §26.6). So `pkg` and `item` are ordinary uses — that is what makes + /// `export b_pkg::x;` a go-to-definition into `b_pkg` and puts the line in + /// `x`'s reference set — and no [`Import`] is pushed, which is what keeps + /// a bare `x` written beside it unresolved unless an `import` says + /// otherwise. + /// + /// `export *::*;` names nothing at all: both halves are the `*` the + /// parser stores as a name, and there is nothing to resolve. What it + /// *means* — everything this package imports is re-exported — is the + /// workspace layer's business (`workspace::reexport`). + pub(super) fn bind_export_path(&mut self, path: &ImportPath, scope: ScopeId) { + if path.pkg.text == "*" { + return; + } + if path.item.text != "*" { + self.use_name( + scope, + &path.item.text, + path.item.span, + Target::UnitMember(path.pkg.text.clone()), + ); + } + self.use_name(scope, &path.pkg.text, path.pkg.span, Target::Package); + } + fn bind_instantiation(&mut self, i: &Instantiation, scope: ScopeId) { // `module_span` has the documented despace caveat for `pkg :: mod`, // so it is taken only when it slices back to the stored name. diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index af41ab2..2306d2d 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -21,8 +21,8 @@ use vlog_parser::span::TextRange; use crate::model::SymbolKind; use crate::workspace::{ - Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, ReferenceFact, - SiteFact, Utf16Pos, Utf16Range, + Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, Reexport, + ReferenceFact, SiteFact, Utf16Pos, Utf16Range, }; /// The version of the encoding below. Bump it on **any** change to what a @@ -121,7 +121,19 @@ use crate::workspace::{ /// cached — silence about a macro argument the rename really did leave /// behind, which is the failure the warning exists to prevent. See /// `docs/features/macro-word-census/README.md`. -pub const FACTS_FORMAT: u32 = 17; +/// +/// 17 → 18 (2026-09-05, package-reexports): a new `RX` group — each package's +/// re-exports (`export b_pkg::x;`, `export b_pkg::*;`, and `export *::*;` +/// already expanded to that package's imports), and once more a wider +/// reference census, since both halves of a re-export line are references +/// where they used to be nothing at all. It is a new field, so an older record +/// would be read short by one group; and it is what makes `a_pkg::x` resolve +/// to `b_pkg`'s declaration, so a store written by a 0.44.0 build would answer +/// definition, hover, completion, find-references and the rename preflight as +/// though no package in the workspace re-exported anything — for exactly the +/// files it had cached, which is the half-right answer this bump exists to +/// prevent. See `docs/features/package-reexports/README.md`. +pub const FACTS_FORMAT: u32 = 18; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. @@ -171,6 +183,15 @@ impl FileFacts { out.text(base); out.site(subclass); } + // Three strings an edge: the package that writes the `export`, the + // package it takes the name from, and the name (or `*`). Two letters + // because `R` is the reference group. + out.tag("RX", self.reexports.len()); + for (exporter, entry) in &self.reexports { + out.text(exporter); + out.text(&entry.package); + out.text(&entry.item); + } out.tag("R", self.references.len()); for reference in &self.references { out.reference(reference); @@ -236,6 +257,11 @@ impl FileFacts { for _ in 0..input.tag("S")? { subclasses.push((input.text()?, input.site()?)); } + let mut reexports = Vec::new(); + for _ in 0..input.tag("RX")? { + let exporter = input.text()?; + reexports.push((exporter, Reexport { package: input.text()?, item: input.text()? })); + } let mut references = Vec::new(); for _ in 0..input.tag("R")? { references.push(input.reference()?); @@ -258,6 +284,7 @@ impl FileFacts { members, instantiations, subclasses, + reexports, references, words, macro_words, diff --git a/crates/vlog_semantic/src/workspace/external.rs b/crates/vlog_semantic/src/workspace/external.rs index b558f88..c2bbcf8 100644 --- a/crates/vlog_semantic/src/workspace/external.rs +++ b/crates/vlog_semantic/src/workspace/external.rs @@ -5,12 +5,12 @@ //! unit — are the same functions `index` lists members with, so a completion //! list and a lookup cannot disagree. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind}; use crate::Semantics; -use super::{Def, WorkspaceIndex}; +use super::{reexport, Def, WorkspaceIndex}; /// What the workspace layer made of one external-candidate reference. #[derive(Debug, Clone, PartialEq, Eq)] @@ -122,12 +122,34 @@ pub(super) fn resolve_fact( /// the inherited ones too. A unit that extends nothing (every package, every /// module) is one map lookup, exactly as before. /// +/// A miss there is then asked of the packages `unit` **re-exports** from +/// (`export b_pkg::x;` — [`reexport::member`]), which is what makes +/// `a_pkg::x` find `x` where `b_pkg` declares it. That walk is a no-op — one +/// empty map lookup — for a unit that re-exports nothing, which is every unit +/// in almost every workspace. +/// /// Map reads only — [`WorkspaceIndex::member`] and /// [`WorkspaceIndex::base_of`], both `BTreeMap`s — so a hover pays a handful /// of comparisons and no file is read. The walk is bounded by the visited set /// as well as by the workspace: `class a extends b; class b extends a;` /// terminates, and so does a chain that meets itself further up. pub(super) fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] { + let found = own_chain(index, unit, name); + if !found.is_empty() { + return found; + } + reexport::member(index, unit, name) +} + +/// [`member_chain`] **without** the re-export hop: `unit` and its `extends` +/// chain, and nothing else. +/// +/// Split out because the re-export walk needs it: every hop it takes asks one +/// package for one name, and asking through [`member_chain`] there would +/// recurse into the very walk that called it. So the layering is exactly two +/// deep — a re-export hop reaches a package's own members and its bases, and +/// the re-export walk itself is what chases a chain of re-exports. +pub(super) fn own_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] { let found = index.member(unit, name); if !found.is_empty() { return found; @@ -141,6 +163,29 @@ pub(super) fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str &[] } +/// Every member `unit` and its bases export, nearest first and one entry per +/// name — the listing half of [`own_chain`], and the same first-hit-wins rule +/// it applies, so what is listed for a unit is what a lookup in it would find. +/// +/// [`WorkspaceIndex::members_of_chain`]'s inner half, shared with the +/// re-export walk for the same reason [`own_chain`] is. +pub(super) fn own_members<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<(&'i str, &'i Def)> { + let mut hops: Vec<&str> = vec![unit]; + hops.extend(base_chain(index, unit)); + let mut out: Vec<(&'i str, &'i Def)> = Vec::new(); + let mut seen: HashSet<&str> = HashSet::new(); + for hop in hops { + for (name, defs) in index.members_of(hop) { + if let Some(def) = defs.first() { + if seen.insert(name) { + out.push((name, def)); + } + } + } + } + out +} + /// **The hops [`member_chain`] takes past `unit` itself**, with the lookup /// left to the caller: what `unit` extends, then what *that* extends, and so /// on upward. diff --git a/crates/vlog_semantic/src/workspace/index.rs b/crates/vlog_semantic/src/workspace/index.rs index 395423f..fa563bc 100644 --- a/crates/vlog_semantic/src/workspace/index.rs +++ b/crates/vlog_semantic/src/workspace/index.rs @@ -13,11 +13,11 @@ use vlog_parser::defines::{Define, DefineTable}; use crate::model::SymbolKind; -use super::external::{base_chain, fold_path, last_segment, member_chain}; +use super::external::{fold_path, last_segment, member_chain, own_members}; use super::record::{FileFacts, ReferenceFact}; use super::{ - Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge, ReferenceSite, - WorkspaceIndex, WorkspaceSymbol, + reexport, Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge, + Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol, }; impl WorkspaceIndex { @@ -97,32 +97,36 @@ impl WorkspaceIndex { /// empty list, never a guess. /// /// **The same walk one member lookup takes.** The units searched are - /// `unit` and then [`base_chain`]'s hops, in that order, and a name - /// declared in more than one of them is listed once from the nearest — - /// which is the first-hit-wins rule `member_chain` applies, so a - /// subclass's override is what is listed *and* what a lookup would find. - /// Map reads only: no file is opened. + /// `unit` and then its `extends` hops ([`own_members`]), then the packages + /// `unit` **re-exports** from ([`reexport::members`]) — exactly + /// `member_chain`'s order — and a name found in more than one of them is + /// listed once from the nearest. So a subclass's override, and a package's + /// own declaration of a name it also re-exports, are what is listed *and* + /// what a lookup would find. Map reads only: no file is opened. pub fn members_of_chain(&self, path: &str) -> Vec<(&str, &Def)> { let Some(unit) = fold_path(self, path) else { return Vec::new(); }; - let mut hops: Vec<&str> = vec![unit.as_str()]; - hops.extend(base_chain(self, &unit)); let mut out: Vec<(&str, &Def)> = Vec::new(); let mut seen: HashSet<&str> = HashSet::new(); - for hop in hops { - for (name, defs) in self.members_of(hop) { - if let Some(def) = defs.first() { - if seen.insert(name) { - out.push((name, def)); - } - } + for (name, def) in + own_members(self, &unit).into_iter().chain(reexport::members(self, &unit)) + { + if seen.insert(name) { + out.push((name, def)); } } out.sort_by_key(|(name, _)| *name); out } + /// What one package re-exports, in file order then source order — the + /// edges `reexport`'s two walks follow. Empty for every unit that + /// re-exports nothing, which is all but a handful in any workspace. + pub(super) fn reexports(&self, unit: &str) -> &[Reexport] { + self.reexports.get(unit).map_or(&[], Vec::as_slice) + } + /// The **declared type** of one member of one unit, as the next unit name /// to look in — the hop that walks a chain `pkt_t::hdr::addr` across /// files, and the one a `MemberSite::Unit` path is folded by. diff --git a/crates/vlog_semantic/src/workspace/mod.rs b/crates/vlog_semantic/src/workspace/mod.rs index 9af914e..4374521 100644 --- a/crates/vlog_semantic/src/workspace/mod.rs +++ b/crates/vlog_semantic/src/workspace/mod.rs @@ -16,19 +16,23 @@ //! This file is the index's vocabulary: the records it hands out ([`Def`], //! [`DeclLines`], the edges) and the [`WorkspaceIndex`] tables themselves. //! `index` answers questions of a built index, `update` changes one after it -//! is built, `record` reads off what one file contributes ([`FileFacts`]), and +//! is built, `record` reads off what one file contributes ([`FileFacts`]), //! `external` is the overlay — [`resolve_external`] — and the member and -//! inheritance walks it shares with `index`. +//! inheritance walks it shares with `index`, and `reexport` is the one edge +//! neither of those two could hold: what `export b_pkg::x;` makes reachable +//! through the package that writes it. mod external; mod index; mod record; +mod reexport; mod update; pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget}; pub use index::{index_order, IndexBuilder}; pub use record::FileFacts; pub(crate) use record::{Decl, ReferenceFact, SiteFact}; +pub(crate) use reexport::Reexport; use std::collections::{BTreeMap, HashSet}; use std::path::PathBuf; @@ -294,6 +298,11 @@ pub struct WorkspaceIndex { /// Base class name → every class extending it, in file order then walk /// order. subclasses: BTreeMap>, + /// Exporting package name → the packages and names it re-exports, in file + /// order then source order. Followed at *query* time rather than folded + /// into `members`, so a re-export costs nothing until something asks a + /// package for a name it does not itself declare. See `reexport`. + reexports: BTreeMap>, /// The same census read the other way: class name → the base it extends, /// as written. Built in [`WorkspaceIndex::merge`] from the very edges that /// fill `subclasses`, so the two cannot disagree and no [`FileFacts`] diff --git a/crates/vlog_semantic/src/workspace/record.rs b/crates/vlog_semantic/src/workspace/record.rs index 8ab0cb1..1291dd2 100644 --- a/crates/vlog_semantic/src/workspace/record.rs +++ b/crates/vlog_semantic/src/workspace/record.rs @@ -18,7 +18,10 @@ use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex}; use crate::model::{Resolution, Symbol, SymbolKind}; use crate::{analyze, classes, instantiations, Semantics}; -use super::{DeclLines, DeclPositions, DeclSite, Def, FileId, InstanceOccurrence, Utf16Range}; +use super::{ + reexport, DeclLines, DeclPositions, DeclSite, Def, FileId, InstanceOccurrence, Reexport, + Utf16Range, +}; /// One declaration as a single file contributes it, before that file has a /// [`FileId`]. The id depends on where the file's path sorts among all of @@ -108,6 +111,10 @@ pub struct FileFacts { /// Class declarations with a base, each under the base's name, in walk /// order. pub(crate) subclasses: Vec<(String, DeclSite)>, + /// Package re-exports, each under the name of the package that writes it, + /// in source order — [`super::reexport::of`]'s answer, `export *::*;` + /// already expanded to that package's imports. + pub(crate) reexports: Vec<(String, Reexport)>, /// Uses of declarations another file may name, stored before file ids and /// cross-file candidates have been resolved by the finished index. pub(crate) references: Vec, @@ -274,6 +281,7 @@ fn facts_from_analysis( members: Vec::new(), instantiations: edges_of(tree, src, lines), subclasses: inheritance_of(tree), + reexports: reexport::of(tree), references: Vec::new(), words: census.words, macro_words: census.macro_words, diff --git a/crates/vlog_semantic/src/workspace/reexport.rs b/crates/vlog_semantic/src/workspace/reexport.rs new file mode 100644 index 0000000..79a5cd4 --- /dev/null +++ b/crates/vlog_semantic/src/workspace/reexport.rs @@ -0,0 +1,189 @@ +//! Package re-exports (IEEE 1800 §26.6) as real edges of the index: the +//! [`Reexport`] record one file contributes, the read-off that produces it, +//! and the two walks that follow it — one name looked up through a chain of +//! re-exports ([`member`]), and every name such a chain offers ([`members`]). +//! +//! `export b_pkg::x;` inside `a_pkg` does not put `x` in `a_pkg`'s scope; it +//! makes `x` reachable to whoever imports `a_pkg`. The binder records the two +//! halves as references and nothing more (`bind::Binder::bind_export_path`), +//! so everything that makes `a_pkg::x` *mean* `b_pkg`'s `x` is here. +//! +//! See `docs/features/package-reexports/README.md`. + +use std::collections::{HashSet, VecDeque}; + +use vlog_parser::ast::{ExportDecl, Item, ItemKind, SourceFile}; + +use super::external::{own_chain, own_members}; +use super::{Def, WorkspaceIndex}; + +/// One name (or one wildcard) a package re-exports from another. +/// +/// The two halves as written, with no interpretation applied: `item` is the +/// bare `*` of `export b_pkg::*;` exactly as the parser stores it, because +/// "everything that package exports" is a question only the finished index +/// can answer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Reexport { + /// The package the name is taken from, as written. + pub(crate) package: String, + /// The name re-exported, or `*` for every name `package` exports. + pub(crate) item: String, +} + +impl Reexport { + /// Whether this edge lets `name` through. + fn admits(&self, name: &str) -> bool { + self.item == "*" || self.item == name + } + + /// The one name this edge carries, or `None` for a wildcard. + fn only(&self) -> Option<&str> { + (self.item != "*").then_some(self.item.as_str()) + } +} + +/// Every package re-export one file writes, under the name of the package +/// that writes it, in source order. +/// +/// **`export *::*;` is expanded here, into the exporting package's own +/// imports.** It means "everything imported into this package is re-exported" +/// (§26.6), and which packages those are is a property of this one file — the +/// very file being read off — so recording it as a flag for a later walk to +/// interpret would only move the same lookup somewhere with less information. +/// `export *::*;` in a package that imports nothing therefore records nothing, +/// which is also what it re-exports. +pub(super) fn of(tree: &SourceFile) -> Vec<(String, Reexport)> { + let mut out = Vec::new(); + for item in &tree.items { + let ItemKind::Package { name, items, .. } = &item.kind else { + continue; + }; + for entry in exports_of(items) { + out.push((name.clone(), entry)); + } + } + out +} + +/// The re-export edges one package body writes. +fn exports_of(items: &[Item]) -> Vec { + let mut out: Vec = Vec::new(); + let mut everything = false; + for item in items { + let ItemKind::Export(ExportDecl::Package(paths)) = &item.kind else { + continue; + }; + for path in paths { + if path.pkg.text == "*" { + everything = true; + } else { + add(&mut out, &path.pkg.text, &path.item.text); + } + } + } + if everything { + for item in items { + if let ItemKind::Import(paths) = &item.kind { + for path in paths { + add(&mut out, &path.pkg.text, &path.item.text); + } + } + } + } + out +} + +/// One edge, unless the package already writes it — `export b_pkg::x;` beside +/// an `import b_pkg::x;` under an `export *::*;` is one edge, not two. +fn add(out: &mut Vec, package: &str, item: &str) { + let entry = Reexport { package: package.to_string(), item: item.to_string() }; + if !out.contains(&entry) { + out.push(entry); + } +} + +/// `name` in the packages `unit` re-exports it from, transitively. +/// +/// Breadth-first over the edges that *admit* `name` — `pkg::name` and +/// `pkg::*`, never `pkg::other` — asking each package reached for `name` in +/// its own members and its bases ([`own_chain`]). The first package that has +/// it answers, so the nearest re-export wins, on the same first-hit-wins rule +/// the `extends` chain follows. +/// +/// **Terminates on any workspace.** A package is asked at most once (the +/// visited set), so `a_pkg` re-exporting `b_pkg::*` while `b_pkg` re-exports +/// `a_pkg::*` walks two hops and stops. Map reads only: no file is opened. +pub(super) fn member<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] { + // The overwhelmingly common case, and the one every member miss in a + // workspace without re-exports pays: one map read, nothing allocated. + if index.reexports(unit).is_empty() { + return &[]; + } + let mut seen: HashSet<&str> = HashSet::from([unit]); + let mut queue: VecDeque<&'i str> = VecDeque::new(); + admitting(index, unit, name, &mut queue); + while let Some(hop) = queue.pop_front() { + if !seen.insert(hop) { + continue; + } + let found = own_chain(index, hop, name); + if !found.is_empty() { + return found; + } + admitting(index, hop, name, &mut queue); + } + &[] +} + +/// The packages one hop further on that still let `name` through. +fn admitting<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str, queue: &mut VecDeque<&'i str>) { + queue.extend( + index.reexports(unit).iter().filter(|e| e.admits(name)).map(|e| e.package.as_str()), + ); +} + +/// Every name `unit` re-exports, with the declaration each one names — the +/// listing twin of [`member`], and what a completion after `a_pkg::` adds to +/// the package's own members. +/// +/// A `pkg::*` edge contributes everything that package exports **and** carries +/// on through that package's own re-exports; a `pkg::x` edge contributes at +/// most `x`, and carries on only through edges that admit `x`. The visited set +/// is keyed by (package, name-filter), so a cycle terminates here too, and a +/// name reached twice is left to the caller to deduplicate against the unit's +/// own members — which is what keeps a local declaration ahead of a +/// re-exported one of the same name. +pub(super) fn members<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<(&'i str, &'i Def)> { + let mut out: Vec<(&'i str, &'i Def)> = Vec::new(); + let mut seen: HashSet<(&str, Option<&str>)> = HashSet::new(); + let mut queue: VecDeque<(&'i str, Option<&'i str>)> = hops(index, unit); + while let Some((package, only)) = queue.pop_front() { + if !seen.insert((package, only)) { + continue; + } + match only { + None => { + out.extend(own_members(index, package)); + queue.extend(hops(index, package)); + } + Some(name) => { + out.extend(own_chain(index, package, name).first().map(|def| (name, def))); + queue.extend( + index + .reexports(package) + .iter() + .filter(|e| e.admits(name)) + .map(|e| (e.package.as_str(), Some(name))), + ); + } + } + } + out +} + +/// One package's re-export edges as walk items: the package reached, and the +/// one name the edge carries (`None` for a wildcard). +fn hops<'i>(index: &'i WorkspaceIndex, unit: &str) -> VecDeque<(&'i str, Option<&'i str>)> { + index.reexports(unit).iter().map(|e| (e.package.as_str(), e.only())).collect() +} diff --git a/crates/vlog_semantic/src/workspace/update.rs b/crates/vlog_semantic/src/workspace/update.rs index 300a00f..f8c2b51 100644 --- a/crates/vlog_semantic/src/workspace/update.rs +++ b/crates/vlog_semantic/src/workspace/update.rs @@ -216,6 +216,15 @@ impl WorkspaceIndex { } } } + // The re-export edges, which decide what `a_pkg::x` means and are + // therefore an observable in their own right — a merge that dropped + // one would otherwise show up only as whichever references happened to + // resolve through it. + for (exporter, edges) in &self.reexports { + for edge in edges { + out.push_str(&format!("reexport {exporter} <- {}::{}\n", edge.package, edge.item)); + } + } for (name, edges) in self.subclasses() { for edge in edges { out.push_str(&format!( @@ -244,6 +253,7 @@ impl WorkspaceIndex { self.members.clear(); self.instantiations.clear(); self.subclasses.clear(); + self.reexports.clear(); self.macro_definitions.clear(); } Some(affected) => { @@ -259,6 +269,9 @@ impl WorkspaceIndex { for name in &affected.bases { self.subclasses.remove(name); } + for name in &affected.exporters { + self.reexports.remove(name); + } for name in &affected.macros { self.macro_definitions.remove(name); } @@ -303,6 +316,12 @@ impl WorkspaceIndex { .or_default() .push(InheritanceEdge { file, subclass: subclass.clone() }); } + for (exporter, entry) in &facts.reexports { + if affected.is_some_and(|a| !a.exporters.contains(exporter)) { + continue; + } + self.reexports.entry(exporter.clone()).or_default().push(entry.clone()); + } for (entry, define) in facts.defines.entries().iter().enumerate() { if define.kind != DefineKind::Define || affected.is_some_and(|a| !a.macros.contains(&define.name)) @@ -377,6 +396,10 @@ pub(super) struct Affected { containers: HashSet, modules: HashSet, bases: HashSet, + /// Keys of the `reexports` table — the package that writes the `export`, + /// never the package it takes the name from: a file changing what `a_pkg` + /// re-exports moves `a_pkg`'s edges and no one else's. + exporters: HashSet, macros: HashSet, } @@ -392,6 +415,7 @@ impl Affected { self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone())); self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone())); self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone())); + self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone())); self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone())); } } diff --git a/crates/vlog_semantic/tests/reexports.rs b/crates/vlog_semantic/tests/reexports.rs new file mode 100644 index 0000000..05e00fa --- /dev/null +++ b/crates/vlog_semantic/tests/reexports.rs @@ -0,0 +1,380 @@ +//! Package re-exports (IEEE 1800 §26.6), both halves: what the binder records +//! for an `export` line, and what the workspace index makes of it — the walk +//! that lets `a_pkg::x` find the `x` `b_pkg` declares. +//! +//! See `docs/features/package-reexports/README.md`. + +use std::path::PathBuf; + +use vlog_parser::parse_source_tolerant; +use vlog_semantic::{ + analyze, resolve_external, Def, Definition, FileFacts, Resolution, Semantics, SymbolKind, + WorkspaceIndex, +}; + +fn semantics(src: &str) -> Semantics { + let (file, _) = parse_source_tolerant(src); + analyze(&file, src) +} + +fn index(files: &[(&str, &str)]) -> WorkspaceIndex { + WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s))) +} + +/// The one reference spelled `name`, or a panic naming what was recorded. +fn only_reference<'a>(sem: &'a Semantics, name: &str) -> &'a vlog_semantic::Reference { + let mut found = sem.references().iter().filter(|r| r.name == name); + let first = found.next().unwrap_or_else(|| { + panic!("no reference to `{name}`: {:?}", sem.references().iter().map(|r| &r.name)) + }); + assert!(found.next().is_none(), "more than one reference to `{name}`"); + first +} + +/// The workspace declarations go-to-definition offers at `needle`. +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; + match resolve_external(sem, ws).definition_of(sem, offset) { + Some(Definition::External(defs)) => defs.to_vec(), + _ => Vec::new(), + } +} + +/// The names completion offers after `unit::`. +fn offered(ws: &WorkspaceIndex, unit: &str) -> Vec { + ws.members_of_chain(unit).into_iter().map(|(name, _)| name.to_string()).collect() +} + +// ---------------------------------------------------------------------- +// 48.1 — the binding half +// ---------------------------------------------------------------------- + +/// Both halves of `export b_pkg::x;` are uses, each on its own bytes: the +/// package half is what a jump to `b_pkg` follows, and the item half is what +/// puts this very line in `x`'s reference set (and so in a rename's edit set). +#[test] +fn an_export_records_both_halves_on_exactly_their_own_bytes() { + let src = "package a_pkg;\n export b_pkg::x;\nendpackage\n"; + let sem = semantics(src); + + for name in ["b_pkg", "x"] { + let reference = only_reference(&sem, name); + assert_eq!( + &src[reference.name_span.as_range()], + name, + "the span of `{name}` covers other bytes" + ); + } + assert_eq!( + only_reference(&sem, "x").resolution, + Resolution::ExternalCandidate { paths: vec!["b_pkg::x".to_string()] }, + "the item is a member of the package it is taken from" + ); + assert_eq!( + only_reference(&sem, "b_pkg").resolution, + Resolution::ExternalCandidate { paths: vec!["b_pkg".to_string()] }, + "the package half is the package itself" + ); +} + +/// `export b_pkg::*;` has no item to name — the `*` is a wildcard, not an +/// identifier — so only the package half is recorded, exactly as +/// `import b_pkg::*;` records only the package half. +#[test] +fn a_wildcard_export_records_the_package_half_alone() { + let sem = semantics("package a_pkg;\n export b_pkg::*;\nendpackage\n"); + assert_eq!( + sem.references().iter().map(|r| r.name.as_str()).collect::>(), + ["b_pkg"], + "the `*` is not a name" + ); +} + +/// `export *::*;` names nothing at all — neither half is an identifier. +#[test] +fn an_export_of_everything_records_no_reference() { + let sem = semantics("package a_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n"); + assert_eq!( + sem.references().iter().map(|r| r.name.as_str()).collect::>(), + ["b_pkg"], + "only the `import` line names anything" + ); +} + +/// **The negative that defines a re-export.** `export b_pkg::x;` makes `x` +/// visible to whoever imports `a_pkg`; it does not make `x` visible *inside* +/// `a_pkg`. So a bare `x` written beside the export is not found and carries +/// no path to the workspace — until an `import` alongside it says otherwise, +/// which is the second half of the test. +#[test] +fn a_reexported_name_is_not_visible_bare_inside_the_exporting_package() { + let exported = "package a_pkg;\n export b_pkg::x;\n localparam Y = x;\nendpackage\n"; + let sem = semantics(exported); + let uses: Vec<&Resolution> = + sem.references().iter().filter(|r| r.name == "x").map(|r| &r.resolution).collect(); + assert_eq!(uses.len(), 2, "the export's item and the bare use"); + assert!( + uses.contains(&&Resolution::NotFound), + "the bare `x` is not found and offers the workspace nothing: {uses:?}" + ); + + let imported = + "package a_pkg;\n import b_pkg::*;\n export b_pkg::x;\n localparam Y = x;\nendpackage\n"; + let sem = semantics(imported); + assert!( + sem.references() + .iter() + .filter(|r| r.name == "x") + .any(|r| matches!(&r.resolution, Resolution::ExternalCandidate { paths } + if paths.contains(&"b_pkg::*".to_string()))), + "an `import` beside the `export` is what brings the name in" + ); +} + +// ---------------------------------------------------------------------- +// 48.2 — the resolution half +// ---------------------------------------------------------------------- + +/// The three-file shape: `b_pkg` declares, `a_pkg` re-exports one name, and a +/// third file reaches it two ways — `a_pkg::x` written out, and a bare `x` +/// under `import a_pkg::*`. +const B_PKG: &str = + "package b_pkg;\n localparam int x = 8;\n localparam int y = 9;\nendpackage\n"; + +#[test] +fn a_single_name_reexport_answers_for_the_package_that_declares_it() { + let sources = [ + ("a.sv", "package a_pkg;\n export b_pkg::x;\nendpackage\n"), + ("b.sv", B_PKG), + ("top.sv", "module top;\n import a_pkg::*;\n localparam W = x;\n localparam V = a_pkg::x;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[2].1); + + for needle in ["x;\n localparam V", "x;\nendmodule"] { + let defs = external_defs(&sem, &ws, sources[2].1, needle); + assert_eq!(defs.len(), 1, "{needle}: {defs:?}"); + assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv")); + assert_eq!(defs[0].kind, SymbolKind::LocalParam); + assert_eq!(defs[0].lines.name, 2, "b_pkg's own declaration line"); + } + + assert_eq!(offered(&ws, "a_pkg"), ["x"], "the one name it re-exports, and not `y`"); +} + +/// `export b_pkg::*;` offers every member `b_pkg` exports, and answers for +/// each of them. +#[test] +fn a_wildcard_reexport_offers_every_member_of_the_package() { + let sources = [ + ("a.sv", "package a_pkg;\n export b_pkg::*;\nendpackage\n"), + ("b.sv", B_PKG), + ("top.sv", "module top;\n localparam W = a_pkg::y;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[2].1); + + assert_eq!(offered(&ws, "a_pkg"), ["x", "y"]); + let defs = external_defs(&sem, &ws, sources[2].1, "y;\nendmodule"); + assert_eq!(defs.len(), 1, "{defs:?}"); + assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv")); +} + +/// `export *::*;` re-exports what the package **imports**, which is the one +/// reading of §26.6 a single file can settle — so `a_pkg::y` resolves through +/// an `import b_pkg::*` that the export makes visible onward. +#[test] +fn an_export_of_everything_reexports_what_the_package_imports() { + let sources = [ + ("a.sv", "package a_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n"), + ("b.sv", B_PKG), + ("top.sv", "module top;\n localparam W = a_pkg::y;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[2].1); + + assert_eq!(offered(&ws, "a_pkg"), ["x", "y"]); + assert_eq!(external_defs(&sem, &ws, sources[2].1, "y;\nendmodule").len(), 1); + + // And a package that imports one name re-exports exactly that one. + let narrow = [ + ("a.sv", "package a_pkg;\n import b_pkg::x;\n export *::*;\nendpackage\n"), + ("b.sv", B_PKG), + ]; + assert_eq!(offered(&index(&narrow), "a_pkg"), ["x"]); + + // A package that imports nothing re-exports nothing, which is what + // `export *::*;` means there. + let empty = [("a.sv", "package a_pkg;\n export *::*;\nendpackage\n"), ("b.sv", B_PKG)]; + assert!(offered(&index(&empty), "a_pkg").is_empty()); +} + +/// A chain of re-exports is followed to its end: `a_pkg` ← `mid_pkg` ← +/// `b_pkg`. +#[test] +fn a_chain_of_reexports_is_followed_transitively() { + let sources = [ + ("a.sv", "package a_pkg;\n export mid_pkg::*;\nendpackage\n"), + ("b.sv", B_PKG), + ("mid.sv", "package mid_pkg;\n export b_pkg::x;\nendpackage\n"), + ("top.sv", "module top;\n localparam W = a_pkg::x;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[3].1); + + assert_eq!(offered(&ws, "a_pkg"), ["x"], "`y` is not re-exported by the middle package"); + let defs = external_defs(&sem, &ws, sources[3].1, "x;\nendmodule"); + assert_eq!(defs.len(), 1, "{defs:?}"); + assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv")); +} + +/// A cycle terminates and answers honestly: `a_pkg` re-exports `b_pkg::*` +/// while `b_pkg` re-exports `a_pkg::*`. Each package is asked once, so the +/// name that really is declared is found and the name that is not simply is +/// not. +#[test] +fn a_reexport_cycle_terminates() { + let sources = [ + ("a.sv", "package a_pkg;\n export b_pkg::*;\nendpackage\n"), + ("b.sv", "package b_pkg;\n localparam int x = 8;\n export a_pkg::*;\nendpackage\n"), + ( + "top.sv", + "module top;\n localparam W = a_pkg::x;\n localparam V = a_pkg::nope;\nendmodule\n", + ), + ]; + let ws = index(&sources); + let sem = semantics(sources[2].1); + + assert_eq!(offered(&ws, "a_pkg"), ["x"]); + assert_eq!(offered(&ws, "b_pkg"), ["x"], "and the other way round"); + assert_eq!(external_defs(&sem, &ws, sources[2].1, "x;\n localparam V").len(), 1); + assert!( + external_defs(&sem, &ws, sources[2].1, "nope;\nendmodule").is_empty(), + "a name nobody declares stays unanswered rather than looping" + ); +} + +/// A re-export of a name the package does not declare resolves to nothing and +/// panics nowhere — the `export` line's item is simply an unanswered +/// reference, exactly like any other name the workspace does not hold. +#[test] +fn a_reexport_of_a_name_the_package_does_not_declare_is_unresolved() { + let sources = [ + ("a.sv", "package a_pkg;\n export b_pkg::missing;\nendpackage\n"), + ("b.sv", B_PKG), + ("top.sv", "module top;\n localparam W = a_pkg::missing;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[0].1); + + assert!(external_defs(&sem, &ws, sources[0].1, "missing;\nendpackage").is_empty()); + assert!(offered(&ws, "a_pkg").is_empty(), "nothing is offered that nothing declares"); + let top = semantics(sources[2].1); + assert!(external_defs(&top, &ws, sources[2].1, "missing;\nendmodule").is_empty()); +} + +/// A package's own declaration beats a name it also re-exports — the +/// first-hit-wins rule the `extends` chain follows, applied one hop further +/// out. Listed once, and from the nearer of the two. +#[test] +fn a_local_declaration_wins_over_a_reexported_name_of_the_same_spelling() { + let sources = [ + ("a.sv", "package a_pkg;\n localparam int x = 1;\n export b_pkg::*;\nendpackage\n"), + ("b.sv", B_PKG), + ("top.sv", "module top;\n localparam W = a_pkg::x;\nendmodule\n"), + ]; + let ws = index(&sources); + let sem = semantics(sources[2].1); + + assert_eq!(offered(&ws, "a_pkg"), ["x", "y"], "one `x`, not two"); + let defs = external_defs(&sem, &ws, sources[2].1, "x;\nendmodule"); + assert_eq!(defs.len(), 1, "{defs:?}"); + assert_eq!( + ws.path(defs[0].file).expect("indexed"), + PathBuf::from("a.sv"), + "the package's own declaration answers" + ); +} + +/// The reference posting a rename fans out from: every use of `b_pkg`'s `x`, +/// **including the `export` line's item half**, is filed under `x`'s own +/// declaration. +#[test] +fn the_export_line_and_every_use_through_it_post_against_the_declaration() { + let sources = [ + ("a.sv", "package a_pkg;\n export b_pkg::x;\nendpackage\n"), + ("b.sv", B_PKG), + ("top.sv", "module top;\n import a_pkg::*;\n localparam W = x;\nendmodule\n"), + ]; + let ws = index(&sources); + let x = ws.member("b_pkg", "x").first().expect("b_pkg declares x").clone(); + + let sites: Vec = ws + .references_to(&x) + .iter() + .map(|site| ws.path(site.file).expect("indexed").to_path_buf()) + .collect(); + assert!(sites.contains(&PathBuf::from("a.sv")), "the export line itself: {sites:?}"); + assert!(sites.contains(&PathBuf::from("top.sv")), "and the use through it: {sites:?}"); +} + +// ---------------------------------------------------------------------- +// The record: the `RX` group and the format bump +// ---------------------------------------------------------------------- + +/// The new group round-trips, and a record written **without** it — which is +/// every record a `FACTS_FORMAT` 17 build wrote — decodes to nothing rather +/// than being read short by one group. +#[test] +fn the_reexport_group_round_trips_and_a_format_17_record_is_rejected() { + for src in [ + "package a_pkg;\n import c_pkg::*;\n export b_pkg::x, b_pkg::*;\n export *::*;\nendpackage\n", + // ... and a record with an empty `RX` group, which is nearly every file. + "module plain;\n wire clk;\nendmodule\n", + ] { + let facts = FileFacts::of(PathBuf::from("/w/r.sv"), src); + let line = facts.encode().expect("encodes"); + let back = FileFacts::decode(&line).expect("decodes"); + assert_eq!(back, facts, "every field, the re-exports included"); + assert_eq!(back.encode(), Some(line.clone()), "and re-encodes byte for byte"); + + let fields: Vec<&str> = line.split('\t').collect(); + let at = fields.iter().position(|field| *field == "RX").expect("RX tag"); + let format_17 = [&fields[..at], &fields[at + 2 + 3 * facts_rx_len(&facts)..]] + .concat() + .join("\t"); + assert!( + FileFacts::decode(&format_17).is_none(), + "a format-17 record decoded as a format-18 one: {format_17}" + ); + } +} + +/// How many `RX` entries a record holds, counted off its encoding — the test +/// above cuts exactly that many triples out. +fn facts_rx_len(facts: &FileFacts) -> usize { + let line = facts.encode().expect("encodes"); + let fields: Vec<&str> = line.split('\t').collect(); + let at = fields.iter().position(|field| *field == "RX").expect("RX tag"); + fields[at + 1].parse().expect("a count") +} + +/// An incremental update produces the very index a full build would — with +/// the re-export table included, which the fingerprint now names. +#[test] +fn an_update_and_a_build_agree_on_the_reexport_table() { + let a = "package a_pkg;\n export b_pkg::x;\nendpackage\n"; + let b = B_PKG; + let built = index(&[("a.sv", a), ("b.sv", b)]); + + let mut updated = index(&[("a.sv", "package a_pkg;\nendpackage\n"), ("b.sv", b)]); + assert!(!updated.fingerprint().contains("reexport a_pkg"), "nothing re-exported yet"); + updated.update_file(PathBuf::from("a.sv"), a); + assert_eq!(updated.fingerprint(), built.fingerprint()); + assert!(built.fingerprint().contains("reexport a_pkg <- b_pkg::x")); + + // And removing the export again leaves the table as empty as it started. + updated.update_file(PathBuf::from("a.sv"), "package a_pkg;\nendpackage\n"); + assert!(!updated.fingerprint().contains("reexport a_pkg")); + assert!(updated.members_of_chain("a_pkg").is_empty()); +} diff --git a/docs/features/dpi-export/README.md b/docs/features/dpi-export/README.md index dd036ea..b896aa8 100644 --- a/docs/features/dpi-export/README.md +++ b/docs/features/dpi-export/README.md @@ -86,6 +86,11 @@ taught anything new. unasked; (b) a DPI export's `name` refers to a function declared elsewhere in the same scope and could be a `use_name`. Note the `*::*` form has `"*"` as its **package** name, which no existing code expects. + **(a) answered 2026-09-05 by TODO §48** — `bind_export_path` records exactly + those two halves and pushes no scope import, and the index follows the edge + (`docs/features/package-reexports/README.md`). `*::*` still records no + reference, for the reason given: neither half is a name. **(b) is still + open** — a DPI export's `name` is unbound. - **vlog_semantic / vlog_linter**: DPI-imported functions and tasks now arrive as ordinary `ItemKind::Function` / `ItemKind::Task` with `stmts` empty and `is_prototype` set, so `bind_function` already declares them as symbols — a diff --git a/docs/features/package-reexports/README.md b/docs/features/package-reexports/README.md new file mode 100644 index 0000000..d150238 --- /dev/null +++ b/docs/features/package-reexports/README.md @@ -0,0 +1,481 @@ +# package re-exports (TODO §48) + +## Goal + +`export b_pkg::x;` inside `package a_pkg` was an opaque leaf: the binder bound +nothing for it and the index recorded nothing about it, so a file that did +`import a_pkg::*` and named `x` resolved nothing, `a_pkg::` offered nothing, +and a rename of `x` left the `export` line behind. This round makes the +re-export a real edge in both layers, which is `docs/topo.md` §2.9-16 and +request (a) of `docs/features/dpi-export/README.md`. + +**The binding half.** `bind_export_path` (beside `bind_import_path`, sharing +its path walk) records the two halves an import records — `pkg` as a +`Target::Package` use, `item` as a `Target::UnitMember(pkg)` use — and pushes +**no** scope import, because a re-export brings nothing into the exporting +package (IEEE 1800 §26.6). `export *::*;` records nothing: neither half is an +identifier. A DPI export (`export "DPI-C" function f;`) stays the opaque leaf +it was. + +**The resolution half.** `FileFacts` gains an `RX` group (`FACTS_FORMAT` +17 → 18): per package, the packages and names it re-exports. The member walk +in `workspace/external.rs` — the one lookup both the overlay and the index's +own reference postings go through — follows those edges after a unit's own +members and its `extends` chain, with a visited set so a cycle terminates. So +definition, hover, completion after `a_pkg::`, find-references and rename all +read the same edge and cannot disagree about it. + +## Assumptions + +- **`export *::*;` is expanded at record time into the exporting package's own + imports**, rather than stored as a flag for a later walk to interpret. §26.6 + reads "everything imported into this package is re-exported", and which + packages those are is a property of the very file being read off — so a flag + would only move the same lookup somewhere with strictly less information, + and nothing would ever read it. `export *::*;` in a package that imports + nothing therefore records nothing, which is also what it re-exports. **This + is the one deviation from §48's letter**, which asked for "`(pkg, item)` + pairs, `(pkg, "*")`, and a `*::*` flag"; the first two are exactly what `RX` + holds, and the third is expanded instead of stored. Behaviour is identical + either way (pinned in `an_export_of_everything_reexports_what_the_package_imports`). +- **A re-export is followed only for a *package*.** The `RX` group is keyed by + the name of the package whose body writes the `export`, and only + `ItemKind::Package` bodies are scanned. A compilation-unit-scope `export` is + not recorded; the LRM does not put one there. +- **The re-export hop is taken after a unit's own members and its bases**, + never before, so a package's own declaration of a name it also re-exports is + what a lookup finds and what completion lists + (`a_local_declaration_wins_over_a_reexported_name_of_the_same_spelling`). +- **The walk is two levels deep, deliberately.** Each hop of the re-export walk + asks `own_chain` — a package and its `extends` chain — not `member_chain`, + which would recurse into the very walk that called it. Chasing a chain of + re-exports is the walk's own job, and it does it with an explicit queue. +- **The visited set is package names for a lookup, `(package, name)` pairs for + a listing.** A lookup for one name only ever follows edges that admit that + name, so the filter is constant and a package need be asked once; a listing + follows every edge, so the same package may be reached once per specific + name it is re-exported through. Both sets are bounded by the workspace. +- **`WorkspaceIndex::member` is unchanged** — it stays the raw table read. + Every walk that should follow re-exports goes through `member_chain` or + `members_of_chain`, which is where the hop was added. +- **A re-export edge is untyped.** Nothing checks that the named package + exists, that it declares the name, or that the exporting package imports it + (§26.6 requires the last of these, and lucisv is not an elaborator). An edge + that leads nowhere simply answers nothing. + +## Handshakes + +- **vlog_parser → vlog_semantic (consumed, unchanged).** `ItemKind::Export` + carries `ExportDecl::Package(Vec)`, each `ImportPath` holding two + `Name`s with exact token spans, and `export *::*;` is one path whose + **package** half is `"*"`. Both halves' spans come straight off the token, so + §47's `exact_or_empty` guard is not needed here (there is no derived span to + check) — `an_export_records_both_halves_on_exactly_their_own_bytes` asserts + the bytes anyway. +- **vlog_semantic → lucisv_server (promised, additive).** `FACTS_FORMAT` is + **18**. `index_cache` drops a store stamped with any other number, which it + already did; its `a_store_from_any_previous_facts_format_is_dropped_not_misread` + enumerates `1..FACTS_FORMAT` and needed no change. + `WorkspaceIndex::members_of_chain` and the member lookup behind + `resolve_external` may now answer with a `Def` in a package the asking path + never named — the declaring one. No signature changed and no caller was + touched. +- **vlog_semantic internal.** `external::member_chain` keeps its signature and + its contract; `own_chain` and `own_members` are the base-chain halves split + out of it and out of `members_of_chain`, so a re-export hop lists exactly + what a lookup through it would find. `WorkspaceIndex::fingerprint` gained + `reexport …` lines: the edges decide what `a_pkg::x` means, so a merge that + dropped one must be visible as more than whichever references happened to + resolve through it. +- **dpi-export README, request (a): answered** (edited there, one paragraph). + Request (b) — binding a DPI export's `name` — is untouched and still open. + +## Status / TODO + +- [x] 48.1 `bind_export_path`: both halves recorded, no scope import, + `export *::*;` records nothing; the negative pinned +- [x] 48.2 `RX` group, `FACTS_FORMAT` 17 → 18, the member walk and the member + listing follow re-exports transitively with a visited set +- [x] `Affected::exporters` so a restricted merge rebuilds the table, and the + fingerprint witnesses it +- [x] unit tests (`crates/vlog_semantic/tests/reexports.rs`, 14) and one + wire-level e2e (`crates/lucisv_server/tests/e2e.rs`) +- [x] cycle, unknown item, transitive chain, local-beats-reexported +- [x] census re-derived and the delta explained +- [x] gates +- [x] QA + +## Files touched + +Exactly the expected set, plus the two docs edits: + +- `crates/vlog_semantic/src/bind/item.rs` — the `Export` arm split, + `bind_export_path` +- `crates/vlog_semantic/src/workspace/reexport.rs` — **new** (189 lines) +- `crates/vlog_semantic/src/workspace/mod.rs` — `mod reexport;`, the + `reexports` table +- `crates/vlog_semantic/src/workspace/record.rs` — the `FileFacts` field +- `crates/vlog_semantic/src/workspace/index.rs` — `reexports()`, + `members_of_chain` +- `crates/vlog_semantic/src/workspace/external.rs` — `own_chain`, + `own_members`, the hop in `member_chain` +- `crates/vlog_semantic/src/workspace/update.rs` — merge, `Affected`, + fingerprint +- `crates/vlog_semantic/src/facts.rs` — the `RX` group, `FACTS_FORMAT` 18 +- `crates/vlog_semantic/tests/reexports.rs` — **new** +- `crates/lucisv_server/tests/e2e.rs` — one test appended +- `docs/features/dpi-export/README.md` — request (a) answered +- `TODO.md` — §48's own checkboxes + +## Docs to apply at merge (lead) + +**`docs/topo.md` §2.9 row 16** — strike it. Suggested text: + +> ~~16. `ItemKind::Export` is an opaque leaf: a package re-export's `pkg::item` +> halves are not references, so `export b_pkg::x;` is invisible to +> go-to-definition, to find-references and to a rename, and a file importing +> the re-exporting package cannot resolve the name at all.~~ **Closed +> 2026-09-05 (§48, `docs/features/package-reexports/README.md`).** Both halves +> are references (`bind_export_path`, no scope import), the index records each +> package's re-exports (`FACTS_FORMAT` 18, the `RX` group), and the member +> walk follows them transitively with a visited set — definition, hover, +> completion, references and rename all read the one edge. A **DPI** export's +> `name` is still unbound (dpi-export request (b)). + +Nothing to change in `README.md`, `docs/repository-analysis.md` or +`docs/site/`. + +## Work log + +**2026-09-05 — dev (Opus 5).** + +- Read the plan, `docs/topo.md` §2.9-16 and dpi-export's request (a). The + parser already had everything: `ExportDecl::Package(Vec)` with + exact spans on both halves, and `"*"` as the package name for `*::*`. +- **48.1.** Split the `ItemKind::Export` arm in `bind/item.rs`: the package + form calls a new `bind_export_path`, the DPI form stays in the opaque-leaf + arm. `bind_export_path` is `bind_import_path` minus the + `scopes[scope].imports.push(...)`, plus the early return for a `*` package. + Used `Target::Package` rather than the plan's `Target::Unit`, because that is + what `bind_import_path` records for the same half and the plan's own words + were "exactly the halves `bind_import_path` records"; `Package` is the + narrower and therefore the more honest of the two (only a package may be + re-exported), and it produces the same `ExternalCandidate { paths: ["b_pkg"] }` + for the workspace. +- **48.2.** New module `workspace/reexport.rs` — the `Reexport` record, the + read-off (`of`, with the `*::*` expansion), and the two walks (`member`, + `members`). `external.rs` grew `own_chain` and `own_members`, the base-chain + halves the walk asks at each hop; `member_chain` is now `own_chain` else + `reexport::member`, and `members_of_chain` is `own_members` chained with + `reexport::members` under one dedup. New machinery went in the new module + rather than into `external.rs` (301 → 349 lines) or `index.rs` (521 → 523), + as the brief asked. +- Cost of the hop for a workspace with no re-exports: one `BTreeMap` lookup + returning an empty slice, per member miss — `reexport::member` returns on + that lookup before it allocates anything, which matters because + `merge_references` asks `member_chain` once per external reference in the + workspace (hundreds of thousands on opentitan). Nothing else changed shape. +- The fingerprint gained `reexport <- ::` lines, and + `Affected` gained `exporters` so a one-file update rebuilds only that + package's edges — checked by `an_update_and_a_build_agree_on_the_reexport_table`. +- Wrote 14 unit tests and one e2e. Confirmed the e2e really depends on the + feature by temporarily emptying `FileFacts::reexports` (it failed on the + first definition), then restored — the same trick that produced the "before" + binary for the opentitan probe. + +### Census delta + +Re-derived with `cargo test -p vlog_semantic --test corpus -- --nocapture`: + +| | before | after | +|---|---|---| +| files | 860 | 860 | +| symbols | 27 486 | 27 486 | +| references | 103 870 | **103 875** | +| unresolved | 1 197 | 1 197 | +| names unplaced | 0 | 0 | + +**+5 references, nothing else moved** — and they are exactly the five names the +corpus's two *package* re-export lines write: + +- `ibex_mem_intf_agent_pkg.sv:28` `export ibex_mem_intf_pkg::*;` — 1 (the + package half; the `*` is not a name) +- `csr_utils_pkg.sv:10` + `export dv_base_reg_pkg::csr_field_t, dv_base_reg_pkg::decode_csr_or_field;` + — 4 (two package halves, two item halves) + +The corpus's other nine `export` lines are all DPI exports, which are +deliberately unchanged. Unresolved is flat, so all five became external +candidates rather than dead ends; no symbol was declared and no span was +derived, so `symbols` and `unplaced` could not move. + +### Gates (all through `tools/guard.sh`; no guard kill) + +| gate | result | +|---|---| +| `cargo fmt -p vlog_semantic -p lucisv_server` | clean (never `--all`); `--check` clean at the end | +| `cargo clippy --all-targets` | clean, no new `#[allow]` | +| `cargo test --workspace` | **3 829 passed, 0 failed, 44 ignored** — baseline 3 814, **+15** (14 unit tests in `tests/reexports.rs`, 1 e2e) | +| `tools/corpus_check.sh corpus` | **814/820 (99.3%)**, the same six parse errors; `corpus-check-results.tsv` unmodified in `git status` | +| formatter byte-identity | `format --stdout` of all **860** corpus files, this build vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0 differ** | +| `cargo build --release -p lucisv_server` + smoke | OK — the release server answers `definition` on a name reached through `export b_pkg::x;` in a three-file scratch workspace | +| semantic corpus census | 860 files, 27 486 symbols, **103 875** references, 1 197 unresolved, **0 unplaced** (delta above) | +| opentitan `definition` through a re-export | **before `[]`, after the declaration** — see below | + +Largest resident set observed by the guard: nothing came near the 8 GB limit, +and no command was killed. + +### opentitan (read-only, scratch index store) + +The tree does have real package re-exports, so the check was run rather than +skipped: + +- `hw/ip/spi_device/rtl/spi_device_pkg.sv:425-451` — eight (QA's count; the work log first said nine) + `export spi_device_reg_pkg::;` lines, each beside its `import` +- `hw/top_englishbreakfast/ip_autogen/flash_ctrl/rtl/flash_ctrl_top_specific_pkg.sv:12-18` + — seven `export flash_ctrl_pkg::;` lines +- `hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21` — one, used by + `hw/ip/spi_host/dv/tb.sv:31` (added at review from QA's inventory) +- `hw/dv/sv/csr_utils/csr_utils_pkg.sv:10` — the two-path line the corpus copy + also holds + +**The probe.** `hw/ip/spi_device/pre_dv/program/prog_passthrough_sw.sv:205` +writes `spi_device_pkg::SramDepth`, and `SramDepth` is declared in +`spi_device_reg_pkg.sv:10` and reaches `spi_device_pkg` only through +`spi_device_pkg.sv:451`'s `export`. One server session per binary, root +`hw/ip/spi_device`, `index.scope: "workspace"`, `initializationOptions.storagePath` +pointed at a scratch directory, one read-only `didOpen`, one +`textDocument/definition` at line 205 char 52: + +| build | answer | +|---|---| +| before (this tree with `FileFacts::reexports` emptied, release) | `[]` | +| after (this tree, release) | `spi_device_reg_pkg.sv`, LSP range line 9 chars 25–34 — i.e. `SramDepth` on line 10, the declaration | + +The "before" binary was produced by temporarily emptying the record's re-export +list and rebuilding, then restoring it and rebuilding again; `git diff` of +`record.rs` afterwards shows only this round's intended change, and the tree was +never checked out, reset or stashed. `git -C ~/repo/opentitan status --porcelain` +showed only the three pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`, +`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`) +before and after. Probe script: +`/defprobe.py`. + +### File sizes after the round + +`reexport.rs` 189, `external.rs` 301 → 346, `index.rs` 521 → 525, `mod.rs` +340 → 349, `record.rs` 558 → 566, `update.rs` 397 → 421, `bind/item.rs` +555 → 590, `facts.rs` 733 → 760 (all raw line counts, comments included). +Nothing crossed 600; the new machinery went in the new module, as the brief +asked. + +## QA log + +**2026-09-05 — QA (Sonnet).** + +Read the plan (TODO §48), the feature README in full, and the diffs of every +file it lists plus `crates/lucisv_server/tests/e2e.rs`. Built +`cargo build --release -p lucisv -p lucisv_server` once. Every suite run and +every server session below went through `tools/guard.sh`; no guard kill. +Attacked the two stated deviations (`Target::Package`, `*::*` expanded at +record time) directly by reading `bind_export_path` against `bind_import_path` +and `reexport::of`/`exports_of` line by line — both match the README's +justification and produce the documented behavior. + +**Gates.** + +| gate | result | +|---|---| +| `cargo clippy --all-targets` | clean, no new `#[allow]` | +| `tools/guard.sh -- cargo test --workspace` | **3 829 passed, 0 failed, 44 ignored** — matches the dev's number exactly, both before and after my scratch files were removed | +| `tools/guard.sh -- tools/corpus_check.sh corpus` | **814/820 (99.3%)**, same six parse errors; `corpus-check-results.tsv` untouched in `git status` | +| formatter byte-identity vs `~/.cache/lucisv-baselines/lucisv-0.44.0` | 860/860 corpus files, **0 differ** (script wrapped in `tools/guard.sh`) | +| semantic corpus census (`cargo test -p vlog_semantic --test corpus -- --nocapture`) | **860 files, 27 486 symbols, 103 875 references, 1 197 unresolved, 0 unplaced** — exact match | +| census delta grep | confirmed by hand: `corpus/ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:28` (`export ibex_mem_intf_pkg::*;`, 1 name — the package half) and `corpus/ibex/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv:10` (two paths, 4 names) sum to exactly **+5**; the corpus's other 9 `export` lines are all `"DPI-C"` (confirmed by grep), unchanged | + +**Attack 1 — the three-file shape, wire-level (`tests/reexports.rs`, the dev's +`e2e.rs` test, and two temporary tests of my own added to `e2e.rs` and removed +after).** The dev's 14 unit tests and the one e2e test all pass and were read +line-by-line, not just run: they cover single-name, `pkg::*`, `*::*` (with and +without a same-named import), a chain, a two-package cycle, an undeclared +name, local-beats-reexported, and the reference-posting/rename fan-out +(`export` line rewritten, package half untouched implicitly since it is a +different reference). Two gaps I closed with temporary `#[test]`s in +`e2e.rs` (run, confirmed, then deleted — `git diff` on that file is exactly +the dev's 145-line addition again): +- A bare re-exported-but-not-imported name inside the exporting package stays + unresolved **over the real wire**, and a rename of the source declaration + edits **exactly one** site in the exporting file — the `export` line's item + half, column 16 — never the bare use (still `NotFound`) and never the + package half (column 9, a different reference entirely). +- `export *::*;` with **no** `import` beside it offers nothing in completion + and resolves nothing in definition — the negative half of the dev's own + `an_export_of_everything_reexports_what_the_package_imports` unit test, + confirmed again over the wire. + +**Attack 2 — chains, cycles, negatives (12 temporary tests in a new +`crates/vlog_semantic/tests/qa_reexport_attack.rs`, run then deleted).** All +12 passed on the first try — no findings: +- three-package cycle (a→b→c→a via `*`), terminates and answers correctly; +- self re-export of an undeclared name (`export a_pkg::thing;` inside + `a_pkg`) terminates in <2 s and stays unresolved — the visited set seeds + itself with `unit`, so the one-hop-back edge is dropped without a second + lookup; +- self re-export of a name the package **does** declare is indistinguishable + from an ordinary local declaration, because `own_chain` (tried first) wins + before the reexport hop is ever asked; +- re-export of a nonexistent package: unresolved, no panic; +- a package that only **imports** a name (no `export` line at all) does not + leak it — `offered()` is empty, matching §26.6 and the README's stated + assumption; +- duplicate `export b_pkg::x;` lines: the edge table dedupes to one listed + name, but **both** source lines remain real references (`references_to` + finds both) — correct, since dedup lives in `reexport::add`, not in the + binder; +- 50 packages in a straight re-export chain: build + lookup in **2.7 ms** + — no accidental quadratic walk; +- two packages both re-exporting the same name into a third: no panic, one + deterministic answer (whichever edge the BFS queue reaches first, which is + file order — not specified by the plan but not undefined either, and + `members_of_chain`'s dedup-by-first-hit makes the listing agree with the + lookup); +- a DPI export beside a package export inside the same package body + contributes no edge to the reexport table (the split arm in `bind/item.rs` + holds); +- **incremental**: editing the *declaring* package (`b_pkg`, not the + exporter) to drop the re-exported name unresolves `a_pkg::x` on the very + next lookup with only `b.sv` touched — `Affected::exporters` is keyed by + the exporter for good reason, and nothing else needed to invalidate for + this case to work; and adding a fresh `export` line to a package that had + none is visible on the very next lookup, no separate rebuild step. + +**Attack 3 — incremental,** covered above and by the dev's own +`an_update_and_a_build_agree_on_the_reexport_table` (read and re-run). + +**Attack 4 — the `FACTS_FORMAT` 18 bump, for real, not just the existing unit +test.** Built the real `v0.44.0` server in a worktree +(`git worktree add … v0.44.0`, removed after). Ran it against a fresh 3-file +scratch workspace (`b_pkg` declares `x`; `a_pkg` does `export b_pkg::x;`; +`top.sv` does `import a_pkg::*` and uses both the bare and qualified form), +`initializationOptions.storagePath` pointed at a scratch dir: +- 0.44.0, cold: `scan finished: 3 files (0 skipped, 0 from cache)`, + `definition` on `a_pkg::x` → `[]` (matches the README's "before"). + Store header afterward: `lucisv-index-cache 2 17 0.44.0`. +- 0.44.0 again, same store: `3 from cache` — sanity that the store format + itself round-trips for the version that wrote it. +- **New server, same (format-17) store**: `scan finished: 3 files (0 skipped, + **0** from cache)` — dropped whole, not misread, exactly as + `index_cache.rs`'s module doc promises (silent, not logged as an error; + the "0 from cache" `--verbose` timing line is the observable). `definition` + now correctly lands on `b_pkg.sv`'s declaration. Store header rewritten to + `lucisv-index-cache 2 18 …`; `RX 1` appears for `a.sv`, `RX 0` for the + other two. +- **New server again, same (now format-18) store**: `3 from cache` — the + round trip holds, same correct answer, `RX` group intact. + +**Attack 5 — census,** re-run and cross-checked by hand above; matches +exactly. + +**Attack 6 — opentitan, read-only, scratch stores throughout.** Enumerated +every `^\s*export ` line under `hw/` myself rather than trusting the dev's +inventory, and found it **incomplete**: `hw/ip/spi_device/rtl/spi_device_pkg.sv` +has **8** `export spi_device_reg_pkg::;` lines (425, 431, 433, 435, 437, +439, 441, 451), not the nine the dev's work log states, and the dev's list +omits `hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21` +(`export spi_host_env_cfg_pkg::SPI_HOST_NUM_CS;`) entirely — see **findings** +below. Both are documentation-accuracy issues in the work log, not behavior +bugs; I tested the missed file anyway. +- **Reproduced the dev's own probe with the real `v0.44.0` binary** (not the + dev's "emptied-`reexports`-field" stand-in): root `hw/ip/spi_device`, + `prog_passthrough_sw.sv:205` char 52 — real 0.44.0 → `[]`; new server, same + workspace → `spi_device_reg_pkg.sv` line 9 chars 25–34 (`SramDepth`'s + declaration). Exact match to the dev's claim. +- **Every other real-world re-export site**, new server only (all correct, + real UVM/DV code, not synthetic): + - `hw/ip/spi_host/dv/tb.sv:31` — bare `SPI_HOST_NUM_CS` under + `import spi_host_env_pkg::*` → `spi_host_env_cfg_pkg.sv:7`, the real + declaration, through the exact chain the missed inventory entry describes. + - `hw/top_englishbreakfast/ip_autogen/flash_ctrl/rtl/flash_ctrl_lcmgr.sv:56` + — bare `NumSeeds` under `import flash_ctrl_top_specific_pkg::*` → + `hw/ip/flash_ctrl/rtl/flash_ctrl_pkg.sv:10`, across two disjoint top-level + `hw/` subtrees (root had to be the whole `hw/`, 3 976 files, 182 s to + scan — well inside the guard's defaults, no kill). + - `hw/vendor/.../ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:28` + (`export ibex_mem_intf_pkg::*;`) — completion after + `ibex_mem_intf_agent_pkg::` in a synthetic **in-memory-only** overlay + buffer (a `didOpen` at a URI under the read-only tree that was never + saved, so nothing touched disk) lists exactly `ibex_mem_intf_pkg`'s five + members plus the package's own local `ibex_mem_intf_request_sequencer` + and `rw_e` — and none of `uvm_pkg`/`mem_model_pkg`/`ibex_cosim_agent_pkg`, + which that package only imports, never re-exports. Definition on + `DATA_WIDTH` through the same path lands on `ibex_mem_intf_pkg.sv`. + - `hw/dv/sv/csr_utils/csr_utils_pkg.sv:10` — both `csr_field_t` and + `decode_csr_or_field` (the export line's own item halves) resolve to + `dv_base_reg_pkg.sv`. +- **30 random `pkg::name` positions**, old vs new server, same workspace + (`hw/ip/spi_device`, 64 files): first pass (no file opened) was a false + start — this server needs the target file **open** for `definition` to + answer at all, old or new, so I reran with the 8 distinct files in the + sample opened first. **29 of 29 usable positions** (one sample line fell + outside `.sv`/`.svh` and was dropped) answered **identically** between + 0.44.0 and the new build but one: `spi_device_pkg.sv:433` + (`export spi_device_reg_pkg::SramPayloadDepth;`) — old `[]`, new resolves to + `spi_device_reg_pkg.sv`. That is the export line's own item reference, + exactly the new capability `bind_export_path` adds — not a regression, the + feature working as designed on real code outside the corpus. No other + position moved. +- `git -C ~/repo/opentitan status --porcelain` before and after every session: + only the three pre-existing modifications + (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, + `hw/top_earlgrey/ip/ast/rtl/ast.sv`). + +**Attack 7 — formatter byte-identity,** covered in the gates table; the +`ExportDecl::Package`/`Dpi` arm split changes no formatting. + +### Findings + +- **LOW — doc accuracy, `docs/features/package-reexports/README.md` Work + log, "opentitan" section.** States "nine `export spi_device_reg_pkg::…;` + lines" for `hw/ip/spi_device/rtl/spi_device_pkg.sv`; there are 8 + (lines 425, 431, 433, 435, 437, 439, 441, 451 — verified by + `grep -c '^\s*export spi_device_reg_pkg::'`). Off-by-one in the write-up + only; every one of the 8 resolves correctly (checked above). +- **LOW — doc completeness, same section.** The inventory of real package + `export` lines under `hw/` omits + `hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21` + (`export spi_host_env_cfg_pkg::SPI_HOST_NUM_CS;`), a genuine re-export used + by real code (`hw/ip/spi_host/dv/tb.sv:31`, bare `SPI_HOST_NUM_CS` through + `import spi_host_env_pkg::*`). Tested directly above — resolves correctly — + so this is a documentation gap, not a functional one. +- No MEDIUM or HIGH findings. No panic, no corruption, no idempotency + violation, no incorrect resolution, no regression in any of the attacks + above, across both a synthetic scratch workspace and ~4 000 files of real + read-only opentitan RTL/DV code. + +### Verdict + +**PASS.** The two findings above are both LOW (documentation accuracy in the +feature README's Work log, not in the shipped behavior) and do not block +merge; the lead may want the dev to fix the "nine" → "eight" count and add +the missed `spi_host_env_pkg.sv` line to the inventory, but nothing about the +binding, the resolution walk, the incremental update, the on-disk format +bump, or the formatter needs rework. + +## Review + +## Review + +**2026-09-05 — lead.** Accepted; ships in 0.45.0 with §47 and §49. Both +halves of the plan are the ruled ones and the two deviations are right: +`Target::Package` is what the import half already records, and expanding +`export *::*` into the package's own imports at record time is the honest +encoding of §26.6 — a stored flag would have had no reader. The walk is +two layers deep by construction (`own_chain` at every hop, never back into +`member_chain`) with a visited set seeded on the starting unit, and QA's +cycles, 50-package chain (2.7 ms) and self re-export all terminate. The +store bump was verified against a genuine 0.44.0-written store. The census +moved by exactly the five references the corpus's two package export lines +carry. On opentitan a real gap closed: `spi_device_pkg::SramDepth` is +reached only through a re-export and now resolves, with the four further +sites QA found all correct. The two doc counts QA caught are corrected +above. diff --git a/docs/topo.md b/docs/topo.md index a2fe365..07916d8 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -627,7 +627,7 @@ update the filing README(s) and this file. | ~~13~~ | ~~Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap~~ — **delivered 2026-09-01 by struct-members**: anonymous enum variants land in the enclosing scope via the shared `bind_enum_body`; an anonymous `struct {…} s;` declarator and every inline nested struct field carry their own `Struct` child scope, and `member_scope` accepts any symbol whose child scope is a `Struct` scope. Residue filed in the struct-members README: cross-file anonymous struct *variables*, `typeDefinition` inside an anonymous aggregate written as a data declaration | types-decls | ~~vlog_semantic~~ done | | ~~14~~ | ~~A `program` node with `name_span`/`end_label_span` for linked editing~~ — **delivered by vendor-formal-grammar (0.30.0)**: `parser/item.rs` routes `program` to `parse_module("endprogram")`; the resulting `ItemKind::Module` carries both spans and `linked.rs::module_pairs` consumes them. Confirmed in the 2026-09-04 source audit. | linked-editing | ~~vlog_parser~~ done | | ~~15~~ | ~~Bind semantics: whether a `bind`'s target scope and connections should resolve through the workspace index (today only the instantiated module name is recorded)~~ — **delivered 2026-09-02 by bind-semantics**: `BindDirective::target` is `Vec`; a lone target binds as `Target::Module`, an instance path records nothing (a guess would be a wrong answer); each connection's port half is `Target::Port(inst.module)` and its expression half `Target::BindScope` — the target's own scope first (`resolve::in_bind_target`, `None` on a miss because generate blocks open scopes of their own), the workspace's one-segment member path when the target lives elsewhere, the writing scope last. `FACTS_FORMAT` 14 → 15 | bind | ~~vlog_semantic~~ done | -| 16 | DPI/package re-export halves as real references (`export pkg::item` doesn't resolve; `*::*` has `"*"` as its package name, which nothing expects) | dpi-export | vlog_semantic | +| ~~16~~ | ~~DPI/package re-export halves as real references (`export pkg::item` doesn't resolve; `*::*` has `"*"` as its package name, which nothing expects)~~ — **closed 2026-09-05 by package-reexports (TODO §48):** both halves of `export pkg::item` are references (`bind_export_path`, no scope import); the index records each package's re-exports (`FACTS_FORMAT` 18, the `RX` group, `*::*` expanded to the package's own imports at record time); the member walk follows them transitively with a visited set, so definition, hover, completion, references and rename read the one edge. A DPI export's `name` is still unbound (dpi-export request (b)). | dpi-export | vlog_semantic | | ~~17~~ | ~~Inline aggregate as a parameter-override *argument* (`m #(.T(struct packed { logic a; })) u ();`) is rejected in expression position; M4's `instantiation_plan` drops such a `parameter type` default rather than emit unparseable text~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.3):** `parse_expr_or_type` routes a `struct`/`union`/`enum` head to the type grammar; the value is an `ExprKind::Type` printed by the type printer. `instantiation_plan` emits a one-line `parameter type` aggregate default; a multi-line one is still dropped by the "written across several lines" rule, not the grammar. | refactor-instantiate (gap 1; its gap 2 was delivered by ansi-first-port) | vlog_parser | | ~~18~~ | ~~A macro-invocation census in `FileFacts`~~ — **delivered 2026-09-02**: the engine half by sva-bodies (`macro_use_warnings` pinned for a file in the source set) and the server half by macro-word-census (TODO §29.2): `FileFacts::macro_words` (`words::harvest_raw`, tag `MW`, `FACTS_FORMAT` 16 → 17, +3.1 % corpus / +1.7 % opentitan store), `WorkspaceIndex::files_naming_in_macros`, and a warning appended by `lucisv_server::rename` for every such file **outside** the set `rename_sources` built — no rung, nothing read (58 files in 186 µs on opentitan for `clk`). | refactor-rename; sva-bodies; macro-word-census | ~~vlog_semantic~~ done | | ~~19~~ | ~~An execute-command spelling of the instantiation skeleton (plain-text `render` through the same `plan_for`), for clients without `textDocument/inlineCompletion` — since the 2026-08-30 names-only popup, such a client (Neovim's built-in LSP, today) has no path to the full skeleton at all. Filed at lead review after correcting the dev's assumption that a `lucisv/instantiate` command already existed (it never did).~~ — **delivered 2026-09-02 by bind-semantics**: `lucisv.instantiate [uri, position, module]` (`lucisv_server/src/instantiate.rs`, advertised by `main.rs::commands()`, routed through `ports::execute`) — `plan_for` → plain `render` under `completion::layout_at` → `workspace/applyEdit`; `at_instantiation_site` validates the position; escaped names go in as plain text. Pinned at the plan level: the command's plan renders to the ghost's text. `editors/nvim/README.md` documents it | inline-instantiation (lead) | ~~lucisv_server~~ done |